text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
* @module Bspline */ import { Point3d, Vector3d } from "../geometry3d/Point3dVector3d"; import { Geometry } from "../Geometry"; import { Point3dArray } from "../geometry3d/PointHelpers"; import { ProxyCurve } from "../curve/ProxyCurve"; import { CurvePrimitive } from "../curve/CurvePrimitive"; import { BSplineCurveOps } from "../bspline/BSplineCurveOps"; import { BSplineCurve3d } from "./BSplineCurve"; import { GeometryQuery } from "../curve/GeometryQuery"; import { Transform } from "../geometry3d/Transform"; import { GeometryHandler } from "../geometry3d/GeometryHandler"; import { XYZProps } from "../geometry3d/XYZProps"; /** * fitPoints and end condition data for [[InterpolationCurve3d]] * * This is a "json compatible" version of [[InterpolationCurve3dOptions]] * @public */ export interface InterpolationCurve3dProps { /** order of the computed bspline (one more than degree) */ order?: number; /** true if the B-spline construction should be periodic */ closed?: boolean; /** if closed and no knots, compute chord length knots (1) or uniform knots (0). Chord length knots give best fit. */ isChordLenKnots?: number; /** if !closed but first and last fitPoints are equal, pivot computed start/end tangent(s) so that they are colinear (1) or leave them be (0). */ isColinearTangents?: number; /** if !closed and start/endTangent is given, set its magnitude to the first/last fit point chord length (1) or to the magnitude of the Bessel tangent (0). Bessel gives best fit. */ isChordLenTangents?: number; /** if !closed and start/endTangent is absent, compute it using the natural end condition (1) or Bessel (0). Bessel gives best fit. */ isNaturalTangents?: number; /** optional start tangent, pointing into curve. Magnitude is ignored. */ startTangent?: XYZProps; /** optional end tangent, pointing into curve. Magnitude is ignored. */ endTangent?: XYZProps; /** points that the curve must pass through */ fitPoints: XYZProps[]; /** parameters for curve fitting, one per fit point */ knots?: number[]; } /** * fitPoints and end condition data for [[InterpolationCurve3d]] * * This is a "typed object" version of the serializer-friendly [[InterpolationCurve3dProps]] * * Typical use cases rarely require all parameters, so the constructor does not itemize them as parameters. * @public */ export class InterpolationCurve3dOptions { /** * Constructor. * @param fitPoints points to CAPTURE * @param knots array to CAPTURE */ public constructor(fitPoints?: Point3d[], knots?: number[]) { this._fitPoints = fitPoints ? fitPoints : []; this._knots = knots; } private _order?: number; private _closed?: boolean; private _isChordLenKnots?: number; private _isColinearTangents?: number; private _isChordLenTangents?: number; private _isNaturalTangents?: number; private _startTangent?: Vector3d; private _endTangent?: Vector3d; private _fitPoints: Point3d[]; private _knots?: number[]; /** `order` as property */ public get order(): number { return Geometry.resolveNumber(this._order, 4); } public set order(val: number) { this._order = val; } /** `closed` as property */ public get closed(): boolean { return Geometry.resolveValue(this._closed, false); } public set closed(val: boolean) { this._closed = val; } /** `isChordLenKnots` as property */ public get isChordLenKnots(): number { return Geometry.resolveNumber(this._isChordLenKnots, 0); } public set isChordLenKnots(val: number) { this._isChordLenKnots = val; } /** `isColinearTangents` as property */ public get isColinearTangents(): number { return Geometry.resolveNumber(this._isColinearTangents, 0); } public set isColinearTangents(val: number) { this._isColinearTangents = val; } /** `isChordLenTangents` as property */ public get isChordLenTangents(): number { return Geometry.resolveNumber(this._isChordLenTangents, 0); } public set isChordLenTangents(val: number) { this._isChordLenTangents = val; } /** `isNaturalTangents` as property */ public get isNaturalTangents(): number { return Geometry.resolveNumber(this._isNaturalTangents, 0); } public set isNaturalTangents(val: number) { this._isNaturalTangents = val; } /** access POSSIBLY UNDEFINED start tangent. Setter CAPTURES. */ public get startTangent(): Vector3d | undefined { return this._startTangent; } public set startTangent(val: Vector3d | undefined) { this._startTangent = val; } /** access POSSIBLY UNDEFINED end tangent. Setter CAPTURES. */ public get endTangent(): Vector3d | undefined { return this._endTangent; } public set endTangent(val: Vector3d | undefined) { this._endTangent = val; } /** access POINTER TO fit points. Setter CAPTURES. */ public get fitPoints(): Point3d[] { return this._fitPoints; } public set fitPoints(val: Point3d[]) { this._fitPoints = val; } /** access POSSIBLY UNDEFINED knots array. Setter CAPTURES. */ public get knots(): number[] | undefined { return this._knots; } public set knots(val: number[] | undefined) { this._knots = val; } /** One step setup of properties not named in constructor. * * CAPTURE pointers to tangents. * * OPTIONALLY downgrade "0" values to undefined. */ public captureOptionalProps( order: number | undefined, closed: boolean | undefined, isChordLenKnots: number | undefined, isColinearTangents: number | undefined, isChordLenTangent: number | undefined, isNaturalTangents: number | undefined, startTangent: Vector3d | undefined, endTangent: Vector3d | undefined ) { this._order = Geometry.resolveToUndefined(order, 0); this._closed = Geometry.resolveToUndefined(closed, false); this._isChordLenKnots = Geometry.resolveToUndefined(isChordLenKnots, 0); this._isColinearTangents = Geometry.resolveToUndefined(isColinearTangents, 0); this._isChordLenTangents = Geometry.resolveToUndefined(isChordLenTangent, 0); this._isNaturalTangents = Geometry.resolveToUndefined(isNaturalTangents, 0); this._startTangent = startTangent; this._endTangent = endTangent; } /** Clone with strongly typed members reduced to simple json, with "undefined" members omitted */ public cloneAsInterpolationCurve3dProps(): InterpolationCurve3dProps { const props: InterpolationCurve3dProps = { fitPoints: Point3dArray.cloneDeepJSONNumberArrays(this.fitPoints), knots: this._knots?.slice(), }; if (this._order !== undefined) props.order = this._order; if (this._closed !== undefined) props.closed = this._closed; if (this._isChordLenKnots !== undefined) props.isChordLenKnots = this._isChordLenKnots; if (this._isColinearTangents !== undefined) props.isColinearTangents = this._isColinearTangents; if (this._isChordLenTangents !== undefined) props.isChordLenTangents = this._isChordLenTangents; if (this._isNaturalTangents !== undefined) props.isNaturalTangents = this._isNaturalTangents; if (this._startTangent !== undefined) props.startTangent = this._startTangent?.toArray(); if (this._endTangent !== undefined) props.endTangent = this._endTangent?.toArray(); return props; } /** Clone with strongly typed members reduced to simple json. */ public clone(): InterpolationCurve3dOptions { const clone = new InterpolationCurve3dOptions(Point3dArray.clonePoint3dArray(this.fitPoints), this.knots?.slice()); clone._order = this.order; clone._closed = this.closed; clone._isChordLenKnots = this.isChordLenKnots; clone._isColinearTangents = this.isColinearTangents; clone._isChordLenTangents = this.isChordLenTangents; clone._isNaturalTangents = this.isNaturalTangents; clone._startTangent = this._startTangent?.clone(); clone._endTangent = this._endTangent?.clone(); return clone; } /** Clone with strongly typed members reduced to simple json. */ public static create(source: InterpolationCurve3dProps): InterpolationCurve3dOptions { const result = new InterpolationCurve3dOptions(Point3dArray.clonePoint3dArray(source.fitPoints), source.knots?.slice()); result._order = source.order; result._closed = source.closed; result._isChordLenKnots = source.isChordLenKnots; result._isColinearTangents = source.isColinearTangents; result._isChordLenTangents = source.isChordLenTangents; result._isNaturalTangents = source.isNaturalTangents; result._startTangent = source.startTangent ? Vector3d.fromJSON(source.startTangent) : undefined; result._endTangent = source.endTangent ? Vector3d.fromJSON(source.endTangent) : undefined; return result; } // ugh. // vector equality test with awkward rule that 000 matches undefined. private static areAlmostEqualAllow000AsUndefined(a: Vector3d | undefined, b: Vector3d | undefined): boolean { if (a !== undefined && a.maxAbs() === 0) a = undefined; if (b !== undefined && b.maxAbs() === 0) b = undefined; if (a !== undefined && b !== undefined) return a.isAlmostEqual(b); return a === undefined && b === undefined; } public static areAlmostEqual(dataA: InterpolationCurve3dOptions | undefined, dataB: InterpolationCurve3dOptions | undefined): boolean { if (dataA === undefined && dataB === undefined) return true; if (dataA !== undefined && dataB !== undefined) { if (Geometry.areEqualAllowUndefined(dataA.order, dataB.order) && Geometry.areEqualAllowUndefined(dataA.closed, dataB.closed) && Geometry.areEqualAllowUndefined(dataA.isChordLenKnots, dataB.isChordLenKnots) && Geometry.areEqualAllowUndefined(dataA.isColinearTangents, dataB.isColinearTangents) && Geometry.areEqualAllowUndefined(dataA.isNaturalTangents, dataB.isNaturalTangents) && this.areAlmostEqualAllow000AsUndefined(dataA.startTangent, dataB.startTangent) && this.areAlmostEqualAllow000AsUndefined(dataA.endTangent, dataB.endTangent) && Geometry.almostEqualArrays(dataA.fitPoints, dataB.fitPoints, (a: Point3d, b: Point3d) => a.isAlmostEqual(b))) { if (Geometry.almostEqualNumberArrays(dataA.knots, dataB.knots, (a: number, b: number) => a === b)) return true; if (dataA.knots === undefined && dataB.knots === undefined) return true; /* alas .. need to allow tricky mismatch of end replication */ let knotsA = dataA.knots, knotsB = dataB.knots; if (dataA.knots === undefined) // construct undefined knots to compare against defined knots knotsA = BSplineCurveOps.C2CubicFit.constructFitParametersFromPoints(dataA.fitPoints, dataA.isChordLenKnots, dataA.closed); else if (dataB.knots === undefined) knotsB = BSplineCurveOps.C2CubicFit.constructFitParametersFromPoints(dataB.fitPoints, dataB.isChordLenKnots, dataB.closed); knotsA = BSplineCurveOps.C2CubicFit.convertCubicKnotVectorToFitParams(knotsA, dataA.fitPoints.length, false); knotsB = BSplineCurveOps.C2CubicFit.convertCubicKnotVectorToFitParams(knotsB, dataB.fitPoints.length, false); return Geometry.almostEqualNumberArrays(knotsA, knotsB, (a: number, b: number) => Geometry.isAlmostEqualNumber(a, b)); } } return false; } /** reverse the order or sense of all start-to-end related properties. */ public reverseInPlace() { this.fitPoints.reverse(); if (this.knots) this.knots.reverse(); // Swap pointers to tangents. They don't need to be negated because they point into the curve. const oldStart = this._startTangent; this._startTangent = this.endTangent; this._endTangent = oldStart; } } /** * Interpolating curve. * * Derive from [[ProxyCurve]] * * Use a [[BSplineCurve3d]] as the proxy * * * @public */ export class InterpolationCurve3d extends ProxyCurve { public readonly curvePrimitiveType = "interpolationCurve"; private _options: InterpolationCurve3dOptions; /** * CAPTURE properties and proxy curve. */ private constructor(properties: InterpolationCurve3dOptions, proxyCurve: CurvePrimitive) { super(proxyCurve); this._options = properties; } public override dispatchToGeometryHandler(handler: GeometryHandler) { return handler.handleInterpolationCurve3d(this); } /** * Create an [[InterpolationCurve3d]] based on points, knots, and other properties in the [[InterpolationCurve3dProps]] or [[InterpolationCurve3dOptions]]. * * This saves a COPY OF the options or props. * * Use createCapture () if the options or props can be used without copy */ public static create(options: InterpolationCurve3dOptions | InterpolationCurve3dProps): InterpolationCurve3d | undefined { let optionsCopy; if (options instanceof InterpolationCurve3dOptions) { optionsCopy = options.clone(); } else { optionsCopy = InterpolationCurve3dOptions.create(options); } return InterpolationCurve3d.createCapture(optionsCopy); } /** Create an [[InterpolationCurve3d]] * * The options object is captured into the new curve object (not copied) */ public static createCapture(options: InterpolationCurve3dOptions): InterpolationCurve3d | undefined { const proxyCurve = BSplineCurve3d.createFromInterpolationCurve3dOptions(options); if (proxyCurve) return new InterpolationCurve3d(options, proxyCurve); return undefined; } /** Return a (copy of) the defining points, packed as a Float64Array */ public copyFitPointsFloat64Array(): Float64Array { return Point3dArray.cloneXYZPropsAsFloat64Array(this._options.fitPoints); } /** * Return json key-value pairs for for this [[InterpolationCurve3d]]. * @returns */ public toJSON(): any { return this._options.cloneAsInterpolationCurve3dProps(); } /** Clone the [[InterpolationCurve3dProps]] object in this [[InterpolationCurve3d]] */ public cloneProps(): InterpolationCurve3dProps { return this._options.cloneAsInterpolationCurve3dProps(); } /** return the options pointer */ public get options(): InterpolationCurve3dOptions { return this._options; } /** * Reverse the curve direction. * * This updates both the defining properties and the proxy bspline. */ public reverseInPlace(): void { this._proxyCurve.reverseInPlace(); this._options.reverseInPlace(); } /** * Transform this [[InterpolationCurve3d]] and its defining data in place */ public tryTransformInPlace(transform: Transform): boolean { const proxyOk = this._proxyCurve.tryTransformInPlace(transform); if (proxyOk) { transform.multiplyPoint3dArrayInPlace(this._options.fitPoints); if (this._options.startTangent) transform.multiplyVectorInPlace(this._options.startTangent); if (this._options.endTangent) transform.multiplyVectorInPlace(this._options.endTangent); } return proxyOk; } /** Return a deep clone */ public override clone(): InterpolationCurve3d { return new InterpolationCurve3d(this._options.clone(), this._proxyCurve.clone()); } public override isAlmostEqual(other: GeometryQuery): boolean { if (other instanceof InterpolationCurve3d) { return InterpolationCurve3dOptions.areAlmostEqual(this._options, other._options); } return false; } /** Test if `other` is also an [[InterpolationCurve3d]] */ public isSameGeometryClass(other: GeometryQuery): boolean { return other instanceof InterpolationCurve3d; } }
the_stack
import { TestBed, fakeAsync, tick, flush, } from '@angular/core/testing'; import { ApolloTestingModule, ApolloTestingController, } from 'apollo-angular/testing'; import { Observable } from 'rxjs'; import { DaffCategoryIdRequest, DaffCategory, DaffCategoryFilterEqualRequest, DaffCategoryFilterRangeRequestOption, daffCategoryComputeFilterRangePairLabel, DaffGetCategoryResponse, DaffCategoryRequestKind, DaffCategoryFilterRangeNumericRequest, DaffCategoryUrlRequest, } from '@daffodil/category'; import { MagentoGetACategoryResponse, MagentoGetCategoryFilterTypesResponse, MagentoCategory, MagentoSortFields, MagentoAggregation, MagentoCategoryFilterTypeField, MagentoPageInfo, MagentoGetCategoryQuery, MagentoGetCategoryFilterTypes, MagentoGetProductsResponse, MagentoGetProductsQuery, } from '@daffodil/category/driver/magento'; import { DaffCategoryDriverMagentoCategoryFactory, DaffCategoryDriverMagentoSortFieldsFactory, DaffCategoryDriverMagentoCategoryFilterTypeFieldFactory, DaffCategoryDriverMagentoPageInfoFactory, DaffCategoryDriverMagentoAggregationPriceFactory, DaffCategoryDriverMagentoAggregationSelectFactory, } from '@daffodil/category/driver/magento/testing'; import { DaffCategoryFactory, DaffCategoryPageMetadataFactory, DaffCategoryFilterRequestEqualFactory, DaffCategoryFilterRequestRangeNumericFactory, DaffCategoryFilterRangeNumericRequestOptionFactory, } from '@daffodil/category/testing'; import { MagentoProduct } from '@daffodil/product/driver/magento'; import { MagentoSimpleProductFactory } from '@daffodil/product/driver/magento/testing'; import { DaffProductFactory } from '@daffodil/product/testing'; import { DaffMagentoCategoryService } from './category.service'; describe('Driver | Magento | Category | CategoryService', () => { let categoryService: DaffMagentoCategoryService; let categoryFactory: DaffCategoryFactory; let categoryPageMetadataFactory: DaffCategoryPageMetadataFactory; let controller: ApolloTestingController; let productFactory: DaffProductFactory; let equalFilterRequestFactory: DaffCategoryFilterRequestEqualFactory; let rangeFilterRequestFactory: DaffCategoryFilterRequestRangeNumericFactory; let rangeFilterRequestOptionFactory: DaffCategoryFilterRangeNumericRequestOptionFactory; let magentoCategoryFactory: DaffCategoryDriverMagentoCategoryFactory; let magentoSortFieldsFactory: DaffCategoryDriverMagentoSortFieldsFactory; let priceAggregateFactory: DaffCategoryDriverMagentoAggregationPriceFactory; let selectAggregateFactory: DaffCategoryDriverMagentoAggregationSelectFactory; let magentoFilterTypeFieldFactory: DaffCategoryDriverMagentoCategoryFilterTypeFieldFactory; let magentoProductFactory: MagentoSimpleProductFactory; let magentoPageInfoFactory: DaffCategoryDriverMagentoPageInfoFactory; let mockCategoryRequest: DaffCategoryIdRequest; let mockCategory: DaffCategory; let equalFilterRequest: DaffCategoryFilterEqualRequest; let rangeFilterRequest: DaffCategoryFilterRangeNumericRequest; let rangeFilterRequestOption: DaffCategoryFilterRangeRequestOption<number>; let rangeFilterRequestOptionLabel: string; let mockMagentoCategory: MagentoCategory; let mockMagentoSortFields: MagentoSortFields; let mockMagentoSelectAggregation: MagentoAggregation; let mockMagentoPriceAggregation: MagentoAggregation; let mockMagentoSelectFilterTypeField: MagentoCategoryFilterTypeField; let mockMagentoPriceFilterTypeField: MagentoCategoryFilterTypeField; let mockMagentoProduct: MagentoProduct; let mockMagentoPageInfo: MagentoPageInfo; let mockGetCategoryResponse: MagentoGetACategoryResponse; let mockGetFilterTypesResponse: MagentoGetCategoryFilterTypesResponse; let mockGetProductsResponse: MagentoGetProductsResponse; beforeEach(() => { TestBed.configureTestingModule({ imports: [ ApolloTestingModule, ], providers: [ DaffMagentoCategoryService, ], }); categoryService = TestBed.inject(DaffMagentoCategoryService); controller = TestBed.inject(ApolloTestingController); categoryFactory = TestBed.inject(DaffCategoryFactory); categoryPageMetadataFactory = TestBed.inject(DaffCategoryPageMetadataFactory); productFactory = TestBed.inject(DaffProductFactory); equalFilterRequestFactory = TestBed.inject(DaffCategoryFilterRequestEqualFactory); rangeFilterRequestFactory = TestBed.inject(DaffCategoryFilterRequestRangeNumericFactory); rangeFilterRequestOptionFactory = TestBed.inject(DaffCategoryFilterRangeNumericRequestOptionFactory); magentoCategoryFactory = TestBed.inject(DaffCategoryDriverMagentoCategoryFactory); magentoSortFieldsFactory = TestBed.inject(DaffCategoryDriverMagentoSortFieldsFactory); selectAggregateFactory = TestBed.inject(DaffCategoryDriverMagentoAggregationSelectFactory); priceAggregateFactory = TestBed.inject(DaffCategoryDriverMagentoAggregationPriceFactory); rangeFilterRequestOptionFactory = TestBed.inject(DaffCategoryFilterRangeNumericRequestOptionFactory); magentoProductFactory = TestBed.inject(MagentoSimpleProductFactory); magentoPageInfoFactory = TestBed.inject(DaffCategoryDriverMagentoPageInfoFactory); magentoFilterTypeFieldFactory = TestBed.inject(DaffCategoryDriverMagentoCategoryFilterTypeFieldFactory); mockCategory = categoryFactory.create(); mockCategoryRequest = { kind: DaffCategoryRequestKind.ID, id: mockCategory.id, }; mockMagentoProduct = magentoProductFactory.create(); mockMagentoCategory = magentoCategoryFactory.create({ uid: mockCategory.id, products: { items: [ mockMagentoProduct, ], }, }); mockMagentoSortFields = magentoSortFieldsFactory.create(); mockMagentoPriceAggregation = priceAggregateFactory.create(); mockMagentoSelectAggregation = selectAggregateFactory.create(); mockMagentoSelectFilterTypeField = magentoFilterTypeFieldFactory.create({ name: mockMagentoSelectAggregation.attribute_code, type: { name: mockMagentoSelectAggregation.type, }, }); mockMagentoPriceFilterTypeField = magentoFilterTypeFieldFactory.create({ name: mockMagentoPriceAggregation.attribute_code, type: { name: mockMagentoPriceAggregation.type, }, }); mockMagentoPageInfo = magentoPageInfoFactory.create(); // transformedCategory = categoryFactory.create(); // transformedCategoryPageMetadata = categoryPageMetadataFactory.create(); // transformedProducts = productFactory.createMany(3); mockGetCategoryResponse = { categoryList: [ mockMagentoCategory, ], }; mockGetFilterTypesResponse = { __type: { inputFields: [ mockMagentoPriceFilterTypeField, mockMagentoSelectFilterTypeField, ], }, }; mockGetProductsResponse = { products: { // items: [ // mockMagentoProduct, // ], // TODO: fixme items: [], total_count: 1, page_info: mockMagentoPageInfo, aggregations: [ mockMagentoPriceAggregation, mockMagentoSelectAggregation, ], sort_fields: mockMagentoSortFields, }, }; }); it('should be created', () => { expect(categoryService).toBeTruthy(); }); describe('get | getting a category by ID', () => { let result: Observable<DaffGetCategoryResponse>; beforeEach(() => { result = categoryService.get(mockCategoryRequest); }); it('should return a category with the correct info', done => { result.subscribe(res => { expect(res.category.id).toEqual(mockMagentoCategory.uid); expect(res.category.name).toEqual(mockMagentoCategory.name); done(); }); const categoryOp = controller.expectOne(MagentoGetCategoryQuery); const filterTypesOp = controller.expectOne(MagentoGetCategoryFilterTypes); const productsOp = controller.expectOne(MagentoGetProductsQuery()); categoryOp.flushData(mockGetCategoryResponse); filterTypesOp.flushData(mockGetFilterTypesResponse); productsOp.flushData(mockGetProductsResponse); }); describe('when filters are requested', () => { beforeEach(() => { equalFilterRequest = equalFilterRequestFactory.create({ name: mockMagentoSelectFilterTypeField.name, value: mockMagentoSelectAggregation.options.map(agg => agg.value), }); rangeFilterRequestOption = rangeFilterRequestOptionFactory.create(); rangeFilterRequest = rangeFilterRequestFactory.create({ name: mockMagentoPriceFilterTypeField.name, value: rangeFilterRequestOption, }); rangeFilterRequestOptionLabel = daffCategoryComputeFilterRangePairLabel(rangeFilterRequestOption.min, rangeFilterRequestOption.max); mockCategoryRequest = { ...mockCategoryRequest, kind: DaffCategoryRequestKind.ID, filter_requests: [ equalFilterRequest, rangeFilterRequest, ], }; result = categoryService.get(mockCategoryRequest); }); it('should apply those filters', done => { result.subscribe(res => { equalFilterRequest.value.forEach(option => { expect(res.categoryPageMetadata.filters[equalFilterRequest.name].options[option].applied).toBeTrue(); }); expect(res.categoryPageMetadata.filters[rangeFilterRequest.name].options[rangeFilterRequestOptionLabel].applied).toBeTrue(); done(); }); const categoryOp = controller.expectOne(MagentoGetCategoryQuery); const filterTypesOp = controller.expectOne(MagentoGetCategoryFilterTypes); const productsOp = controller.expectOne(MagentoGetProductsQuery()); categoryOp.flushData(mockGetCategoryResponse); filterTypesOp.flushData(mockGetFilterTypesResponse); productsOp.flushData(mockGetProductsResponse); }); }); }); describe('getByUrl | getting a category by URL', () => { let mockCategoryUrlRequest: DaffCategoryUrlRequest; let url: string; let result: Observable<DaffGetCategoryResponse>; beforeEach(() => { url = '/test/url?with=query#fragment'; mockCategoryUrlRequest = { kind: DaffCategoryRequestKind.URL, url, }; result = categoryService.getByUrl(mockCategoryUrlRequest); }); it('should return a category with the correct info', fakeAsync(() => { result.subscribe(res => { expect(res.category.id).toEqual(mockMagentoCategory.uid); expect(res.category.name).toEqual(mockMagentoCategory.name); flush(); }); const categoryOp = controller.expectOne(MagentoGetCategoryQuery); const filterTypesOp = controller.expectOne(MagentoGetCategoryFilterTypes); categoryOp.flushData(mockGetCategoryResponse); filterTypesOp.flushData(mockGetFilterTypesResponse); tick(); const productsOp = controller.expectOne(MagentoGetProductsQuery()); productsOp.flushData(mockGetProductsResponse); })); it('should query the category with the truncated URL', fakeAsync(() => { result.subscribe(); const categoryOp = controller.expectOne(MagentoGetCategoryQuery); const filterTypesOp = controller.expectOne(MagentoGetCategoryFilterTypes); categoryOp.flushData(mockGetCategoryResponse); filterTypesOp.flushData(mockGetFilterTypesResponse); tick(); const productsOp = controller.expectOne(MagentoGetProductsQuery()); productsOp.flushData(mockGetProductsResponse); expect(categoryOp.operation.variables.filters.url_path.eq).toEqual('test/url'); flush(); })); it('should query the products with the category ID', fakeAsync(() => { result.subscribe(); const categoryOp = controller.expectOne(MagentoGetCategoryQuery); const filterTypesOp = controller.expectOne(MagentoGetCategoryFilterTypes); categoryOp.flushData(mockGetCategoryResponse); filterTypesOp.flushData(mockGetFilterTypesResponse); tick(); const productsOp = controller.expectOne(MagentoGetProductsQuery()); productsOp.flushData(mockGetProductsResponse); expect(productsOp.operation.variables.filter.category_uid.eq).toEqual(mockMagentoCategory.uid); flush(); })); describe('when the request applied a filter', () => { beforeEach(() => { equalFilterRequest = equalFilterRequestFactory.create({ name: mockMagentoSelectFilterTypeField.name, value: mockMagentoSelectAggregation.options.map(agg => agg.value), }); rangeFilterRequestOption = rangeFilterRequestOptionFactory.create(); rangeFilterRequest = rangeFilterRequestFactory.create({ name: mockMagentoPriceFilterTypeField.name, value: rangeFilterRequestOption, }); rangeFilterRequestOptionLabel = daffCategoryComputeFilterRangePairLabel(rangeFilterRequestOption.min, rangeFilterRequestOption.max); mockCategoryUrlRequest = { ...mockCategoryUrlRequest, filter_requests: [ equalFilterRequest, rangeFilterRequest, ], }; result = categoryService.getByUrl(mockCategoryUrlRequest); }); it('should apply those filters in the response', fakeAsync(() => { result.subscribe(res => { equalFilterRequest.value.forEach(option => { expect(res.categoryPageMetadata.filters[equalFilterRequest.name].options[option].applied).toBeTrue(); }); expect(res.categoryPageMetadata.filters[rangeFilterRequest.name].options[rangeFilterRequestOptionLabel].applied).toBeTrue(); flush(); }); const categoryOp = controller.expectOne(MagentoGetCategoryQuery); const filterTypesOp = controller.expectOne(MagentoGetCategoryFilterTypes); categoryOp.flushData(mockGetCategoryResponse); filterTypesOp.flushData(mockGetFilterTypesResponse); tick(); const productsOp = controller.expectOne(MagentoGetProductsQuery()); productsOp.flushData(mockGetProductsResponse); })); }); }); afterEach(() => { controller.verify(); }); });
the_stack
import {Component, Injectable, PLATFORM_ID, ViewChild} from '@angular/core'; import {CommonModule, isPlatformServer} from '@angular/common'; import {ComponentFixture, TestBed, inject, fakeAsync} from '@angular/core/testing'; import {Platform} from '@angular/cdk/platform'; import { ɵMatchMedia as MatchMedia, ɵMockMatchMedia as MockMatchMedia, ɵMockMatchMediaProvider as MockMatchMediaProvider, StyleBuilder, StyleUtils, } from '@angular/flex-layout/core'; import {FlexLayoutModule} from '@angular/flex-layout'; import {DefaultFlexDirective, DefaultLayoutDirective, FlexStyleBuilder} from '@angular/flex-layout/flex'; import { customMatchers, expect, makeCreateTestComponent, expectNativeEl, queryFor, expectEl, } from '@angular/flex-layout/_private-utils/testing'; describe('flex directive', () => { let fixture: ComponentFixture<any>; let mediaController: MockMatchMedia; let styler: StyleUtils; let platform: Platform; let platformId: Object; let componentWithTemplate = (template: string) => { fixture = makeCreateTestComponent(() => TestFlexComponent)(template); // Can only Inject() AFTER TestBed.override(...) inject( [MatchMedia, StyleUtils, Platform, PLATFORM_ID], (_matchMedia: MockMatchMedia, _styler: StyleUtils, _platform: Platform, _platformId: Object) => { mediaController = _matchMedia; styler = _styler; platform = _platform; platformId = _platformId; })(); return fixture; }; beforeEach(() => { jasmine.addMatchers(customMatchers); TestBed.configureTestingModule({ imports: [ CommonModule, FlexLayoutModule.withConfig({serverLoaded: true}), ], declarations: [TestFlexComponent, TestQueryWithFlexComponent], providers: [MockMatchMediaProvider] }); }); afterEach(() => { mediaController.clearAll(); }); describe('with static features', () => { afterEach(() => { mediaController.clearAll(); }); it('should add correct styles for default `fxFlex` usage', () => { componentWithTemplate(`<div fxFlex></div>`); fixture.detectChanges(); let dom = fixture.debugElement.children[0]; expectEl(dom).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(dom).toHaveStyle({'flex': '1 1 0%'}, styler); }); it('should add correct styles for `fxFlex` and ngStyle with layout change', () => { // NOTE: the presence of ngIf on the child element is imperative for detecting issue 700 componentWithTemplate(` <div fxLayout="row wrap" fxLayoutAlign="start center"> <div fxFlex="10 1 auto" [ngStyle.lt-md]="{'width.px': 15}" *ngIf="true"></div> </div> `); fixture.detectChanges(); mediaController.activate('sm', true); let element = queryFor(fixture, '[fxFlex]')[0]; expectEl(element).toHaveStyle({'width': '15px'}, styler); expectEl(element).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(element).toHaveStyle({'flex': '10 1 auto'}, styler); }); it('should add correct styles for `fxFlex` with NgForOf', () => { componentWithTemplate(` <div [fxLayout]="direction"> <div *ngFor="let el of els" fxFlex="50"></div> </div> `); fixture.componentInstance.direction = 'row'; fixture.detectChanges(); let element = queryFor(fixture, '[fxFlex]')[0]; expectEl(element).toHaveStyle({'max-width': '50%'}, styler); expectEl(element).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(element).toHaveStyle({'flex': '1 1 100%'}, styler); fixture.componentInstance.direction = 'column'; fixture.detectChanges(); element = queryFor(fixture, '[fxFlex]')[0]; expectEl(element).toHaveStyle({'max-height': '50%'}, styler); expectEl(element).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(element).toHaveStyle({'flex': '1 1 100%'}, styler); }); it('should add correct styles for `fxFlex` and ngStyle without layout change', () => { // NOTE: the presence of ngIf on the child element is imperative for detecting issue 700 componentWithTemplate(` <div fxLayout="row wrap" fxLayoutAlign="start center"> <div fxFlex="10 1 auto" [ngStyle.lt-md]="{'width.px': 15}" *ngIf="true"></div> </div> `); fixture.detectChanges(); mediaController.activate('sm', true); let element = queryFor(fixture, '[fxFlex]')[0]; expectEl(element).toHaveStyle({'width': '15px'}, styler); expectEl(element).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(element).toHaveStyle({'flex': '10 1 auto'}, styler); }); it('should add correct styles for `fxFlex` with multiple layout changes and wraps', () => { componentWithTemplate(` <div [fxLayout]="direction + ' wrap'" fxLayoutAlign="start center"> <div fxFlex="30"></div> </div> `); fixture.debugElement.componentInstance.direction = 'column'; fixture.detectChanges(); let element = queryFor(fixture, '[fxFlex]')[0]; expectNativeEl(fixture).toHaveStyle({'flex-direction': 'column'}, styler); expectEl(element).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(element).toHaveStyle({'flex': '1 1 30%'}, styler); expectEl(element).toHaveStyle({'max-height': '30%'}, styler); fixture.debugElement.componentInstance.direction = 'row'; fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({'flex-direction': 'row'}, styler); expectEl(element).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(element).toHaveStyle({'flex': '1 1 30%'}, styler); expectEl(element).toHaveStyle({'max-width': '30%'}, styler); fixture.debugElement.componentInstance.direction = 'column'; fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({'flex-direction': 'column'}, styler); expectEl(element).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(element).toHaveStyle({'flex': '1 1 30%'}, styler); expectEl(element).toHaveStyle({'max-height': '30%'}, styler); }); it('should add correct styles for `fxFlex` with gap in grid mode and wrap parent', () => { componentWithTemplate(` <div [fxLayout]="direction + ' wrap'" fxLayoutGap="10px grid"> <div fxFlex="30"></div> <div fxFlex="30"></div> <div fxFlex="30"></div> </div> `); fixture.debugElement.componentInstance.direction = 'row'; fixture.detectChanges(); let element = queryFor(fixture, '[fxFlex]')[0]; expectNativeEl(fixture).toHaveStyle({'flex-direction': 'row'}, styler); expectEl(element).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(element).toHaveStyle({'flex': '1 1 30%'}, styler); expectEl(element).toHaveStyle({'max-width': '30%'}, styler); fixture.debugElement.componentInstance.direction = 'row-reverse'; fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({'flex-direction': 'row-reverse'}, styler); expectEl(element).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(element).toHaveStyle({'flex': '1 1 30%'}, styler); expectEl(element).toHaveStyle({'max-width': '30%'}, styler); fixture.debugElement.componentInstance.direction = 'column'; fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({'flex-direction': 'column'}, styler); expectEl(element).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(element).toHaveStyle({'flex': '1 1 30%'}, styler); expectEl(element).toHaveStyle({'max-height': '30%'}, styler); fixture.debugElement.componentInstance.direction = 'column-reverse'; fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({'flex-direction': 'column-reverse'}, styler); expectEl(element).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(element).toHaveStyle({'flex': '1 1 30%'}, styler); expectEl(element).toHaveStyle({'max-height': '30%'}, styler); }); it('should add correct styles for `fxFlex` and ngStyle with multiple layout changes', () => { // NOTE: the presence of ngIf on the child element is imperative for detecting 700 componentWithTemplate(` <div fxLayout="row wrap" fxLayoutAlign="start center"> <div fxFlex="10 1 auto" [ngStyle.lt-md]="{'width.px': 15}" *ngIf="true"></div> </div> `); mediaController.activate('sm', true); fixture.detectChanges(); let element = queryFor(fixture, '[fxFlex]')[0]; expectEl(element).toHaveStyle({'width': '15px'}, styler); expectEl(element).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(element).toHaveStyle({'flex': '10 1 auto'}, styler); mediaController.activate('md', true); fixture.detectChanges(); expectEl(element).not.toHaveStyle({'width': '15px'}, styler); expectEl(element).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(element).toHaveStyle({'flex': '10 1 auto'}, styler); }); it('should apply `fxGrow` value to flex-grow when used default `fxFlex`', () => { componentWithTemplate(`<div fxFlex fxGrow="10"></div>`); fixture.detectChanges(); let dom = fixture.debugElement.children[0]; expectEl(dom).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(dom).toHaveStyle({'flex': '10 1 0%'}, styler); }); it('should apply `fxShrink` value to flex-shrink when used default `fxFlex`', () => { componentWithTemplate(`<div fxFlex fxShrink="10"></div>`); fixture.detectChanges(); let dom = fixture.debugElement.children[0]; expectEl(dom).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(dom).toHaveStyle({'flex': '1 10 0%'}, styler); }); it('should apply both `fxGrow` and `fxShrink` when used with default fxFlex', () => { componentWithTemplate(`<div fxFlex fxGrow="4" fxShrink="5"></div>`); fixture.detectChanges(); let dom = fixture.debugElement.children[0]; expectEl(dom).toHaveStyle({'box-sizing': 'border-box'}, styler); expectEl(dom).toHaveStyle({'flex': '4 5 0%'}, styler); }); it('should add correct styles for flex-basis unitless 0 input', () => { componentWithTemplate(`<div fxFlex="1 1 0"></div>`); fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 0%', 'box-sizing': 'border-box', }, styler); expectNativeEl(fixture).not.toHaveStyle({ 'max-width': '*' }, styler); }); it('should add correct styles for flex-basis 0px input', () => { componentWithTemplate(`<div fxFlex="1 1 0px"></div>`); fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 0%', 'box-sizing': 'border-box', }, styler); expectNativeEl(fixture).not.toHaveStyle({ 'max-width': '*' }, styler); }); it('should add correct styles for noshrink with basis', () => { componentWithTemplate(`<div fxFlex="1 0 50%"></div>`); fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 0 50%', 'box-sizing': 'border-box', }, styler); expectNativeEl(fixture).not.toHaveStyle({ 'max-width': '*' }, styler); }); it('should add correct styles for `fxFlex="2%"` usage', () => { componentWithTemplate(`<div fxFlex='2%'></div>`); fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({ 'max-width': '2%', 'flex': '1 1 100%', 'box-sizing': 'border-box', }, styler); }); it('should work with percentage values', () => { componentWithTemplate(`<div fxFlex='37%'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 100%', 'max-width': '37%', 'box-sizing': 'border-box', }, styler); }); it('should work with pixel values', () => { componentWithTemplate(`<div fxFlex='37px'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 37px', 'box-sizing': 'border-box', }, styler); }); it('should work with "1 0 auto" values', () => { componentWithTemplate(`<div fxFlex='1 0 auto'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 0 auto', 'box-sizing': 'border-box', }, styler); }); it('should work fxLayout parents', () => { componentWithTemplate(` <div fxLayout='column' class='test'> <div fxFlex='30px' fxFlex.gt-sm='50' > </div> </div> `); fixture.detectChanges(); let parent = queryFor(fixture, '.test')[0]; let element = queryFor(fixture, '[fxFlex]')[0]; // parent flex-direction found with 'column' with child height styles expectEl(parent).toHaveStyle({'flex-direction': 'column', 'display': 'flex'}, styler); expectEl(element).toHaveStyle({'min-height': '30px'}, styler); expectEl(element).not.toHaveStyle({'min-width': '30px'}, styler); }); it('should work fxLayout parents default in column mode', () => { componentWithTemplate(` <div fxLayout='column' class='test'> <div fxFlex> </div> </div> `); fixture.detectChanges(); let parent = queryFor(fixture, '.test')[0]; let element = queryFor(fixture, '[fxFlex]')[0]; // parent flex-direction found with 'column' with child height styles expectEl(parent).toHaveStyle({'flex-direction': 'column', 'display': 'flex'}, styler); if (platform.BLINK) { expectEl(element).toHaveStyle({ 'flex': '1 1 1e-09px', 'box-sizing': 'border-box', }, styler); } else if (platform.FIREFOX || platform.WEBKIT || platform.IOS) { expectEl(element).toHaveStyle({ 'flex': '1 1 1e-9px', 'box-sizing': 'border-box', }, styler); } else if (platform.EDGE) { expectEl(element).toHaveStyle({ 'flex': '1 1 0px', 'box-sizing': 'border-box', }, styler); } else { expectEl(element).toHaveStyle({ 'flex': '1 1 0.000000001px', 'box-sizing': 'border-box', }, styler); } }); it('should CSS stylesheet and not inject flex-direction on parent', () => { componentWithTemplate(` <style> .test { flex-direction:column; display: flex; } </style> <div class='test'> <div fxFlex='30px' fxFlex.gt-sm='50'></div> </div> `); fixture.detectChanges(); let parent = queryFor(fixture, '.test')[0]; let element = queryFor(fixture, '[fxFlex]')[0]; // TODO(CaerusKaru): Domino is unable to detect this style if (!isPlatformServer(platformId)) { // parent flex-direction found with 'column' with child height styles expectEl(parent).toHaveCSS({'flex-direction': 'column', 'display': 'flex'}, styler); expectEl(element).toHaveStyle({'min-height': '30px'}, styler); expectEl(element).not.toHaveStyle({'min-width': '30px'}, styler); } }); it('should work with non-direct-parent fxLayouts', fakeAsync(() => { componentWithTemplate(` <div fxLayout='column'> <div class='test'> <div fxFlex='40px' fxFlex.gt-sm='50'></div> </div> </div> `); fixture.detectChanges(); let element = queryFor(fixture, '[fxFlex]')[0]; let parent = queryFor(fixture, '.test')[0]; // The parent flex-direction not found; // A flex-direction should have been auto-injected to the parent... // fallback to 'row' and set child width styles accordingly expectEl(parent).toHaveStyle({'flex-direction': 'row'}, styler); expectEl(element).toHaveStyle({'min-width': '40px'}, styler); expectEl(element).not.toHaveStyle({'min-height': '40px'}, styler); })); it('should work with styled-parent flex directions', () => { componentWithTemplate(` <div fxLayout='row'> <div style='flex-direction: column' class='parent'> <div fxFlex='60px'></div> </div> </div> `); fixture.detectChanges(); let element = queryFor(fixture, '[fxFlex]')[0]; let parent = queryFor(fixture, '.parent')[0]; // parent flex-direction found with 'column'; set child with height styles expectEl(element).toHaveStyle({'min-height': '60px'}, styler); expectEl(parent).toHaveStyle({'flex-direction': 'column'}, styler); }); it('should work with "1 1 auto" values', () => { componentWithTemplate(` <div fxLayout='column'> <div fxFlex='auto' fxFlex.gt-sm='50' > </div> <div fxFlex='auto' fxFlex.gt-sm='24.4'> </div> <div fxFlex='auto' fxFlex.gt-sm='25.6'> </div> </div> `); fixture.detectChanges(); let nodes = queryFor(fixture, '[fxFlex]'); expect(nodes.length).toEqual(3); expectEl(nodes[1]).not.toHaveStyle({'max-height': '*', 'min-height': '*'}, styler); expectEl(nodes[1]).toHaveStyle({ 'flex': '1 1 auto', 'box-sizing': 'border-box' }, styler); }); // Note: firefox is disabled due to a current bug with Firefox 57 it('should work with calc values', () => { // @see http://caniuse.com/#feat=calc for IE issues with calc() componentWithTemplate(`<div fxFlex='calc(30vw - 10px)'></div>`); if (platform.WEBKIT || platform.IOS) { expectNativeEl(fixture).toHaveStyle({ 'box-sizing': 'border-box', 'flex-grow': '1', 'flex-shrink': '1', 'flex-basis': 'calc(-10px + 30vw)' }, styler); } else if (!(platform.FIREFOX || platform.EDGE)) { expectNativeEl(fixture).toHaveStyle({ 'box-sizing': 'border-box', 'flex-grow': '1', 'flex-shrink': '1', 'flex-basis': 'calc(30vw - 10px)' }, styler); } }); it('should work with calc without internal whitespaces', fakeAsync(() => { // @see http://caniuse.com/#feat=calc for IE issues with calc() componentWithTemplate('<div fxFlex="calc(75%-10px)"></div>'); if (!(platform.FIREFOX || platform.EDGE)) { fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({ 'box-sizing': 'border-box', 'flex-grow': '1', 'flex-shrink': '1', 'flex-basis': 'calc(75% - 10px)' // correct version has whitespace }, styler); } })); it('should work with "auto" values', () => { componentWithTemplate(`<div fxFlex='auto'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 auto' }, styler); }); it('should work with "nogrow" values', () => { componentWithTemplate(`<div fxFlex='nogrow'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '0 1 auto' }, styler); }); it('should work with "grow" values', () => { componentWithTemplate(`<div fxFlex='grow'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 100%' }, styler); }); it('should work with "initial" values', () => { componentWithTemplate(`<div fxFlex='initial'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '0 1 auto' }, styler); }); it('should work with "noshrink" values', () => { componentWithTemplate(`<div fxFlex='noshrink'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 0 auto' }, styler); }); it('should work with "none" values', () => { componentWithTemplate(`<div fxFlex='none'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '0 0 auto' }, styler); }); it('should work with full-spec values', () => { componentWithTemplate(`<div fxFlex='1 2 0.9em'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 2 0.9em' }, styler); }); it('should set a min-width when the shrink == 0', () => { componentWithTemplate(`<div fxFlex='1 0 37px'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 0 37px', 'min-width': '37px', 'box-sizing': 'border-box', }, styler); }); it('should set a min-width and max-width when the grow == 0 and shrink == 0', () => { componentWithTemplate(`<div fxFlex='0 0 375px'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '0 0 375px', 'max-width': '375px', 'min-width': '375px', 'box-sizing': 'border-box', }, styler); }); it('should not set max-width to 69px when fxFlex="1 0 69px"', () => { componentWithTemplate(`<div fxFlex='1 0 69px'></div>`); expectNativeEl(fixture).not.toHaveStyle({ 'max-width': '69px', }, styler); }); it('should not set a max-width when the shrink == 0', () => { componentWithTemplate(`<div fxFlex='1 0 303px'></div>`); fixture.detectChanges(); let dom = fixture.debugElement.children[0]; expectEl(dom).not.toHaveStyle({'max-width': '*'}, styler); }); it('should not set min-width to 96px when fxFlex="0 1 96px"', () => { componentWithTemplate(`<div fxFlex='0 1 96px'></div>`); expectNativeEl(fixture).not.toHaveStyle({ 'min-width': '96px', }, styler); }); it('should not set a min-width when the grow == 0', () => { componentWithTemplate(`<div fxFlex='0 1 313px'></div>`); fixture.detectChanges(); let dom = fixture.debugElement.children[0]; expectEl(dom).not.toHaveStyle({'min-width': '*'}, styler); }); it('should set a min-width when basis is a Px value', () => { componentWithTemplate(`<div fxFlex='312px'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 312px', 'max-width': '312px', 'min-width': '312px' }, styler); }); it('should set a min-width and max-width when basis is a rem value', () => { componentWithTemplate(`<div fxFlex='12rem'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 12rem', 'max-width': '12rem', 'min-width': '12rem' }, styler); }); describe('', () => { it('should ignore fxLayout settings on same element', () => { componentWithTemplate(` <div fxLayout='column' fxFlex='37%'> </div> `); expectNativeEl(fixture) .not.toHaveStyle({ 'flex-direction': 'row', 'flex': '1 1 37%', 'max-height': '37%', }, styler); }); it('should set max-height for `fxFlex="<%val>"` with parent using fxLayout="column" ', () => { let template = ` <div fxLayout='column'> <div fxFlex='37%'></div> </div> `; componentWithTemplate(template); fixture.detectChanges(); expectEl(queryFor(fixture, '[fxFlex]')[0]) .toHaveStyle({ 'flex': '1 1 100%', 'max-height': '37%', }, styler); }); it('should set max-width for `fxFlex="<%val>"`', () => { componentWithTemplate(`<div fxFlex='37%'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 100%', 'max-width': '37%', }, styler); }); it('should set max-width for `fxFlex="2%"` usage', () => { componentWithTemplate(`<div fxFlex='2%'></div>`); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 100%', 'max-width': '2%', }, styler); }); }); }); describe('with responsive features', () => { afterEach(() => { mediaController.clearAll(); }); it('should initialize the component with the smallest lt-xxx matching breakpoint', () => { componentWithTemplate(` <div fxFlex="25px" fxFlex.lt-lg='50%' fxFlex.lt-sm='33%'> </div> `); fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 25px', 'max-width': '25px' }, styler); mediaController.activate('xl', true); fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 25px', 'max-width': '25px' }, styler); mediaController.activate('md', true); fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 100%', 'max-width': '50%' }, styler); mediaController.activate('xs', true); fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 100%', 'max-width': '33%' }, styler); }); it('should initialize the component with the largest gt-xxx matching breakpoint', () => { componentWithTemplate(` <div fxFlex='auto' fxFlex.gt-xs='33%' fxFlex.gt-sm='50%' > </div> `); mediaController.activate('xl', true); fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 100%', 'max-width': '50%' }, styler); mediaController.activate('sm', true); fixture.detectChanges(); expectNativeEl(fixture).toHaveStyle({ 'flex': '1 1 100%', 'max-width': '33%' }, styler); }); it('should fallback properly to default flex values', () => { componentWithTemplate(` <div fxLayout='column'> <div fxFlex='auto' fxFlex.gt-sm='50' > </div> <div fxFlex='auto' fxFlex.gt-sm='24.4'> </div> <div fxFlex='auto' fxFlex.gt-sm='25.6'> </div> </div> `); mediaController.useOverlaps = true; mediaController.activate('sm'); fixture.detectChanges(); let nodes = queryFor(fixture, '[fxFlex]'); expect(nodes.length).toEqual(3); expectEl(nodes[0]).toHaveStyle({'flex': '1 1 auto'}, styler); expectEl(nodes[1]).toHaveStyle({'flex': '1 1 auto'}, styler); expectEl(nodes[2]).toHaveStyle({'flex': '1 1 auto'}, styler); mediaController.activate('xl'); fixture.detectChanges(); nodes = queryFor(fixture, '[fxFlex]'); expectEl(nodes[0]).toHaveStyle({'flex': '1 1 100%', 'max-height': '50%'}, styler); expectEl(nodes[1]).toHaveStyle({'flex': '1 1 100%', 'max-height': '24.4%'}, styler); expectEl(nodes[2]).toHaveStyle({'flex': '1 1 100%', 'max-height': '25.6%'}, styler); mediaController.activate('sm'); fixture.detectChanges(); nodes = queryFor(fixture, '[fxFlex]'); expect(nodes.length).toEqual(3); expectEl(nodes[0]).toHaveStyle({'flex': '1 1 auto'}, styler); expectEl(nodes[1]).toHaveStyle({'flex': '1 1 auto'}, styler); expectEl(nodes[2]).toHaveStyle({'flex': '1 1 auto'}, styler); expectEl(nodes[0]).not.toHaveStyle({'max-height': '50%'}, styler); expectEl(nodes[1]).not.toHaveStyle({'max-height': '24.4%'}, styler); expectEl(nodes[2]).not.toHaveStyle({'max-height': '25.6%'}, styler); expectEl(nodes[0]).not.toHaveStyle({'max-height': '*'}, styler); expectEl(nodes[1]).not.toHaveStyle({'max-height': '*'}, styler); expectEl(nodes[2]).not.toHaveStyle({'max-height': '*'}, styler); }); it('should fallback to the default layout from gt-md selectors', () => { componentWithTemplate(` <div fxLayout='column'> <div fxFlex='auto' fxFlex.gt-md='50' > </div> <div fxFlex='auto' fxFlex.gt-md='24.4'> </div> <div fxFlex='auto' fxFlex.gt-md='25.6'> </div> </div> `); mediaController.activate('md'); fixture.detectChanges(); let nodes = queryFor(fixture, '[fxFlex]'); expect(nodes.length).toEqual(3); expectEl(nodes[0]).toHaveStyle({'flex': '1 1 auto'}, styler); expectEl(nodes[1]).toHaveStyle({'flex': '1 1 auto'}, styler); expectEl(nodes[2]).toHaveStyle({'flex': '1 1 auto'}, styler); mediaController.activate('sm'); fixture.detectChanges(); nodes = queryFor(fixture, '[fxFlex]'); expectEl(nodes[0]).toHaveStyle({'flex': '1 1 auto'}, styler); expectEl(nodes[1]).toHaveStyle({'flex': '1 1 auto'}, styler); expectEl(nodes[2]).toHaveStyle({'flex': '1 1 auto'}, styler); mediaController.activate('lg', true); fixture.detectChanges(); nodes = queryFor(fixture, '[fxFlex]'); expectEl(nodes[0]).toHaveStyle({'flex': '1 1 100%', 'max-height': '50%'}, styler); expectEl(nodes[1]).toHaveStyle({'flex': '1 1 100%', 'max-height': '24.4%'}, styler); expectEl(nodes[2]).toHaveStyle({'flex': '1 1 100%', 'max-height': '25.6%'}, styler); }); it('should fallback to the default layout from lt-md selectors', () => { componentWithTemplate(` <div fxLayout='column'> <div fxFlex='auto' fxFlex.lt-md='50' > </div> </div> `); mediaController.activate('md', true); fixture.detectChanges(); let nodes = queryFor(fixture, '[fxFlex]'); expect(nodes.length).toEqual(1); expectEl(nodes[0]).toHaveStyle({'flex': '1 1 auto'}, styler); mediaController.activate('sm', true); fixture.detectChanges(); nodes = queryFor(fixture, '[fxFlex]'); expectEl(nodes[0]).toHaveStyle({ 'flex': '1 1 100%', 'max-height': '50%' }, styler); mediaController.activate('lg', true); fixture.detectChanges(); nodes = queryFor(fixture, '[fxFlex]'); expectEl(nodes[0]).toHaveStyle({'flex': '1 1 auto'}, styler); }); }); describe('with API directive queries', () => { beforeEach(inject( [MatchMedia, StyleUtils, Platform, PLATFORM_ID], (_matchMedia: MockMatchMedia, _styler: StyleUtils, _platform: Platform, _platformId: Object) => { mediaController = _matchMedia; styler = _styler; platform = _platform; platformId = _platformId; })); afterEach(() => { mediaController.clearAll(); }); it('should query the ViewChild `fxLayout` directive properly', () => { fixture = TestBed.createComponent(TestQueryWithFlexComponent); fixture.detectChanges(); const layout: DefaultLayoutDirective = fixture.debugElement.componentInstance.layout; expect(layout).toBeDefined(); expect(layout.activatedValue).toBe(''); expectNativeEl(fixture).toHaveStyle({ 'flex-direction': 'row' }, styler); layout.activatedValue = 'column'; expect(layout.activatedValue).toBe('column'); expectNativeEl(fixture).toHaveStyle({ 'flex-direction': 'column' }, styler); }); it('should query the ViewChild `fxFlex` directive properly', () => { fixture = TestBed.createComponent(TestQueryWithFlexComponent); fixture.detectChanges(); const flex: DefaultFlexDirective = fixture.debugElement.componentInstance.flex; // Test for percentage value assignments expect(flex).toBeDefined(); expect(flex.activatedValue).toBe('50%'); let nodes = queryFor(fixture, '[fxFlex]'); expect(nodes.length).toEqual(1); expectEl(nodes[0]).toHaveStyle({'max-width': '50%'}, styler); // Test for raw value assignments that are converted to percentages flex.activatedValue = '35'; expect(flex.activatedValue).toBe('35'); nodes = queryFor(fixture, '[fxFlex]'); expect(nodes.length).toEqual(1); expectEl(nodes[0]).toHaveStyle({'max-width': '35%'}, styler); // Test for pixel value assignments flex.activatedValue = '27.5px'; expect(flex.activatedValue).toBe('27.5px'); nodes = queryFor(fixture, '[fxFlex]'); expect(nodes.length).toEqual(1); expectEl(nodes[0]).toHaveStyle({'max-width': '27.5px'}, styler); }); it('should restore `fxFlex` value after breakpoint activations', () => { fixture = TestBed.createComponent(TestQueryWithFlexComponent); fixture.detectChanges(); const flex: DefaultFlexDirective = fixture.debugElement.componentInstance.flex; // Test for raw value assignments that are converted to percentages expect(flex).toBeDefined(); flex.activatedValue = '35'; expect(flex.activatedValue).toBe('35'); let nodes = queryFor(fixture, '[fxFlex]'); expect(nodes.length).toEqual(1); expectEl(nodes[0]).toHaveStyle({'max-width': '35%'}, styler); mediaController.activate('sm'); fixture.detectChanges(); // Test for breakpoint value changes expect(flex.activatedValue).toBe('71%'); nodes = queryFor(fixture, '[fxFlex]'); expectEl(nodes[0]).toHaveStyle({'max-width': '71%'}, styler); mediaController.activate('lg'); fixture.detectChanges(); // Confirm activatedValue was restored properly when `sm` deactivated expect(flex.activatedValue).toBe('35'); nodes = queryFor(fixture, '[fxFlex]'); expectEl(nodes[0]).toHaveStyle({'max-width': '35%'}, styler); }); }); describe('with flex token enabled', () => { beforeEach(() => { // Configure testbed to prepare services TestBed.configureTestingModule({ imports: [ CommonModule, FlexLayoutModule.withConfig({addFlexToParent: true, serverLoaded: true}), ], declarations: [TestFlexComponent, TestQueryWithFlexComponent], providers: [MockMatchMediaProvider] }); }); afterEach(() => { mediaController.clearAll(); }); it('should work with non-direct-parent fxLayouts', fakeAsync(() => { componentWithTemplate(` <div fxLayout='column'> <div class='test'> <div fxFlex='40px' fxFlex.gt-sm='50'></div> </div> </div> `); fixture.detectChanges(); let element = queryFor(fixture, '[fxFlex]')[0]; let parent = queryFor(fixture, '.test')[0]; // The parent flex-direction not found; // A flex-direction should have been auto-injected to the parent... // fallback to 'row' and set child width styles accordingly expectEl(parent).toHaveStyle({'flex-direction': 'row'}, styler); expectEl(element).toHaveStyle({'min-width': '40px'}, styler); expectEl(element).not.toHaveStyle({'min-height': '40px'}, styler); })); }); describe('with prefixes disabled', () => { beforeEach(() => { // Configure testbed to prepare services TestBed.configureTestingModule({ imports: [ CommonModule, FlexLayoutModule.withConfig({ disableVendorPrefixes: true, serverLoaded: true, }), ], declarations: [TestFlexComponent, TestQueryWithFlexComponent], providers: [MockMatchMediaProvider] }); }); afterEach(() => { mediaController.clearAll(); }); it('should work with non-direct-parent fxLayouts', fakeAsync(() => { componentWithTemplate(` <div fxLayout='column'> <div class='test'> <div fxFlex='40px' fxFlex.gt-sm='50'></div> </div> </div> `); fixture.detectChanges(); let element = queryFor(fixture, '[fxFlex]')[0]; let parent = queryFor(fixture, '.test')[0]; // The parent flex-direction not found; // A flex-direction should have been auto-injected to the parent... // fallback to 'row' and set child width styles accordingly expect(parent.nativeElement.getAttribute('style')).not.toContain('-webkit-flex-direction'); expectEl(element).toHaveStyle({'min-width': '40px'}, styler); expectEl(element).not.toHaveStyle({'min-height': '40px'}, styler); })); }); describe('with column basis zero disabled', () => { let styleBuilder: FlexStyleBuilder; beforeEach(() => { // Configure testbed to prepare services TestBed.configureTestingModule({ imports: [ CommonModule, FlexLayoutModule.withConfig({ useColumnBasisZero: false, serverLoaded: true, }), ], declarations: [TestFlexComponent, TestQueryWithFlexComponent], providers: [MockMatchMediaProvider] }); }); afterEach(() => { mediaController.clearAll(); }); it('should set flex basis to auto', () => { componentWithTemplate(` <div fxLayout='column'> <div fxFlex></div> </div> `); styleBuilder = TestBed.get(FlexStyleBuilder); // Reset the cache because the layout config is only set at startup styleBuilder.shouldCache = false; fixture.detectChanges(); let element = queryFor(fixture, '[fxFlex]')[0]; expectEl(element).toHaveStyle({'flex': '1 1 auto'}, styler); }); }); describe('with custom builder', () => { beforeEach(() => { // Configure testbed to prepare services TestBed.configureTestingModule({ imports: [ CommonModule, FlexLayoutModule.withConfig({ useColumnBasisZero: false, serverLoaded: true, }), ], declarations: [TestFlexComponent, TestQueryWithFlexComponent], providers: [ MockMatchMediaProvider, { provide: FlexStyleBuilder, useClass: MockFlexStyleBuilder, } ] }); }); afterEach(() => { mediaController.clearAll(); }); it('should set flex basis to input', fakeAsync(() => { componentWithTemplate(` <div fxLayout='column'> <div fxFlex="25"></div> </div> `); fixture.detectChanges(); let element = queryFor(fixture, '[fxFlex]')[0]; expectEl(element).toHaveStyle({'flex': '1 1 30%'}, styler); })); }); }); @Injectable() export class MockFlexStyleBuilder extends StyleBuilder { shouldCache = false; buildStyles(_input: string) { return {'flex': '1 1 30%'}; } } // ***************************************************************** // Template Component // ***************************************************************** @Component({ selector: 'test-layout', template: `<span>PlaceHolder Template HTML</span>` }) class TestFlexComponent { direction = 'column'; els = new Array(5); } @Component({ selector: 'test-query-with-flex', template: ` <div fxLayout> <div fxFlex='50%' fxFlex.sm='71%'></div> </div> ` }) class TestQueryWithFlexComponent { @ViewChild(DefaultFlexDirective, {static: true}) flex!: DefaultFlexDirective; @ViewChild(DefaultLayoutDirective, {static: true}) layout!: DefaultLayoutDirective; }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormEntitlement { interface Header extends DevKit.Controls.IHeader { /** Choose a contact or account for which this entitlement has been defined. */ CustomerId: DevKit.Controls.Lookup; /** Enter the date when the entitlement ends. */ EndDate: DevKit.Controls.Date; /** Type the total number of entitlement terms that are left. */ RemainingTerms: DevKit.Controls.Decimal; /** For internal use only. */ StateCode: DevKit.Controls.OptionSet; } interface tab_general_Sections { contacts: DevKit.Controls.Section; entitlementapplications: DevKit.Controls.Section; entitlementterms: DevKit.Controls.Section; entitlementterms_2: DevKit.Controls.Section; entitlementtermsInUCI: DevKit.Controls.Section; fieldservice: DevKit.Controls.Section; information: DevKit.Controls.Section; notes: DevKit.Controls.Section; products: DevKit.Controls.Section; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface Tabs { general: tab_general; } interface Body { Tab: Tabs; /** Select the type of entitlement terms. */ AllocationTypeCode: DevKit.Controls.OptionSet; /** Choose a contact or account for which this entitlement has been defined. */ CustomerId: DevKit.Controls.Lookup; /** Select whether to decrease the remaining terms when the case is created or when it is resolved. */ DecreaseRemainingOn: DevKit.Controls.OptionSet; /** Type additional information to describe the Entitlement */ Description: DevKit.Controls.String; /** Enter the date when the entitlement ends. */ EndDate: DevKit.Controls.Date; /** Entity type for which the entitlement applies */ entitytype: DevKit.Controls.OptionSet; /** Shows whether this entitlement is the default one for the specified customer. */ IsDefault: DevKit.Controls.Boolean; /** The work order entities to which the entitlement is applicable. */ msdyn_AppliesTo: DevKit.Controls.OptionSet; /** The priority level when considering which eligible entitlement to apply, where the lower the number the higher the priority. */ msdyn_EntitlementPrioritization: DevKit.Controls.Integer; /** The percent discount the entitlement applies to the work order. */ msdyn_PercentDiscount: DevKit.Controls.Double; /** The price list that the entitlement applies to the work order. */ msdyn_PriceListToApply: DevKit.Controls.Lookup; /** Type a meaningful name for the entitlement. */ Name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Type the total number of entitlement terms that are left. */ RemainingTerms: DevKit.Controls.Decimal; /** Tells whether case creation is restricted based on entitlement terms. */ RestrictCaseCreation: DevKit.Controls.Boolean; /** Choose the service level agreement (SLA) associated with the entitlement. */ SLAId: DevKit.Controls.Lookup; /** Enter the date when the entitlement starts. */ StartDate: DevKit.Controls.Date; /** Type the total number of entitlement terms. */ TotalTerms: DevKit.Controls.Decimal; } interface Navigation { navCases: DevKit.Controls.NavigationItem } interface Grid { grid_EntitlementChannel: DevKit.Controls.Grid; grid_EntitlementApplications: DevKit.Controls.Grid; editableEntitlementChannelGridControl: DevKit.Controls.Grid; grid_EntitlementProducts: DevKit.Controls.Grid; grid_EntitlementContacts: DevKit.Controls.Grid; } } class FormEntitlement extends DevKit.IForm { /** * DynamicsCrm.DevKit form Entitlement * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Entitlement */ Body: DevKit.FormEntitlement.Body; /** The Header section of form Entitlement */ Header: DevKit.FormEntitlement.Header; /** The Navigation of form Entitlement */ Navigation: DevKit.FormEntitlement.Navigation; /** The Grid of form Entitlement */ Grid: DevKit.FormEntitlement.Grid; } class EntitlementApi { /** * DynamicsCrm.DevKit EntitlementApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier for Account associated with Entitlement. */ AccountId: DevKit.WebApi.LookupValueReadonly; /** Select the type of entitlement terms. */ AllocationTypeCode: DevKit.WebApi.OptionSetValue; /** Unique identifier for Contact associated with Entitlement. */ ContactId: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the entitlement. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; customerid_account: DevKit.WebApi.LookupValue; customerid_contact: DevKit.WebApi.LookupValue; /** Select whether to decrease the remaining terms when the case is created or when it is resolved. */ DecreaseRemainingOn: DevKit.WebApi.OptionSetValue; /** Type additional information to describe the Entitlement */ Description: DevKit.WebApi.StringValue; /** The primary email address for the entity. */ EmailAddress: DevKit.WebApi.StringValue; /** Enter the date when the entitlement ends. */ EndDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Unique identifier for entity instances */ EntitlementId: DevKit.WebApi.GuidValue; /** Unique identifier for Entitlement Template associated with Entitlement. */ EntitlementTemplateId: DevKit.WebApi.LookupValue; /** Entity type for which the entitlement applies */ entitytype: DevKit.WebApi.OptionSetValue; /** Exchange rate for the currency associated with the contact with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Shows whether this entitlement is the default one for the specified customer. */ IsDefault: DevKit.WebApi.BooleanValue; /** Select the access someone will have to the knowledge base on the portal. */ KbAccessLevel: DevKit.WebApi.OptionSetValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** The work order entities to which the entitlement is applicable. */ msdyn_AppliesTo: DevKit.WebApi.OptionSetValue; /** The priority level when considering which eligible entitlement to apply, where the lower the number the higher the priority. */ msdyn_EntitlementPrioritization: DevKit.WebApi.IntegerValue; /** The percent discount the entitlement applies to the work order. */ msdyn_PercentDiscount: DevKit.WebApi.DoubleValue; /** The price list that the entitlement applies to the work order. */ msdyn_PriceListToApply: DevKit.WebApi.LookupValue; /** Type a meaningful name for the entitlement. */ Name: DevKit.WebApi.StringValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Contains the id of the process associated with the entity. */ ProcessId: DevKit.WebApi.GuidValue; /** Type the total number of entitlement terms that are left. */ RemainingTerms: DevKit.WebApi.DecimalValue; /** Tells whether case creation is restricted based on entitlement terms. */ RestrictCaseCreation: DevKit.WebApi.BooleanValue; /** Choose the service level agreement (SLA) associated with the entitlement. */ SLAId: DevKit.WebApi.LookupValue; /** Contains the id of the stage where the entity is located. */ StageId: DevKit.WebApi.GuidValue; /** Enter the date when the entitlement starts. */ StartDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** For internal use only. */ StateCode: DevKit.WebApi.OptionSetValue; /** Select the reason code that explains the status of the entitlement. */ StatusCode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Type the total number of entitlement terms. */ TotalTerms: DevKit.WebApi.DecimalValue; /** Unique identifier of the currency associated with the contact. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */ TraversedPath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace Entitlement { enum AllocationTypeCode { /** 192350000 */ Discount_and_Price_List, /** 0 */ Number_of_cases, /** 1 */ Number_of_hours } enum DecreaseRemainingOn { /** 1 */ Case_Creation, /** 0 */ Case_Resolution } enum entitytype { /** 0 */ Case, /** 192350000 */ Work_Order } enum KbAccessLevel { /** 2 */ None, /** 1 */ Premium, /** 0 */ Standard } enum msdyn_AppliesTo { /** 690970002 */ Both_Work_Order_Products_Services, /** 690970000 */ Work_Order_Products, /** 690970001 */ Work_Order_Services } enum StateCode { /** 1 */ Active, /** 2 */ Cancelled, /** 0 */ Draft, /** 3 */ Expired, /** 4 */ Waiting } enum StatusCode { /** 1 */ Active, /** 2 */ Cancelled, /** 0 */ Draft, /** 3 */ Expired, /** 1200 */ Waiting } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Entitlement'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { IntersectionObserverSupport } from '../../support/intersection-observer.js'; import { clamp } from '../../utils/clamp.js'; import { fade } from '../../utils/fade.js'; import { fire } from '../../utils/fire.js'; import { injectScript } from '../../utils/inject-script.js'; import { DEBUG_LEVEL, log } from '../../utils/logger.js'; import { html, styles } from './onboarding-card.template.js'; const IO_POLYFILL_PATH = '/third_party/intersection-observer/intersection-observer-polyfill.js'; /* istanbul ignore next: Not testing polyfill injection x-browser */ /** * @ignore */ export async function loadIntersectionObserverPolyfillIfNeeded({ force = false, polyfillPrefix = ''}) { if (!force && await IntersectionObserverSupport.supported()) { return true; } try { await injectScript(`${polyfillPrefix}${IO_POLYFILL_PATH}`); // Force the polyfill to check every 300ms. (IntersectionObserver as any).prototype.POLL_INTERVAL = 300; log('Loaded IntersectionObserver polyfill', DEBUG_LEVEL.INFO, 'Onboarding'); return true; } catch (e) { log('Intersection Observer polyfill load failed', DEBUG_LEVEL.ERROR, 'Onboarding'); return false; } } /** * Provides a mechanism for onboarding users to your experience. Each child node * of the element is assumed to be a discrete step in the process. * * ```html * <onboarding-card width="327" height="376" mode="scroll"> * <img src="images/step1.png" width="327" height="376"> * <img src="images/step2.png" width="327" height="376"> * <img src="images/step3.png" width="327" height="376"> * </onboarding-card> * ``` * * The element can be further customized via CSS properties: * * ```css * onboarding-card { * --background: #FFF; * --borderRadius: 4px; * --color: #333; * --fontFamily: 'Arial', 'Helvetica', sans-serif; * --padding: 8px 8px 36px 8px; * --buttonBottomMargin: 8px; * --buttonSideMargin: 4px; * --buttonActiveColor: #444; * --buttonHoverColor: #666; * --buttonInactiveColor: #AAA; * --contentBorderRadius: 0px; * } * ``` */ export class OnboardingCard extends HTMLElement { /** * The name of the event fired when the final item has been reached. */ static onboardingFinishedEvent = 'onboardingfinished'; /** * The name of the event fired when the item changes. */ static itemChangedEvent = 'itemchanged'; /** * The default tag name provided to `customElement.define`. */ static defaultTagName = 'onboarding-card'; /** * @ignore * * The attributes supported by the card: * <ul> * <li>`width`: The width of the card.</li> * <li>`height`: The height of the card.</li> * <li>`mode`: The mode of the card, `scroll` or `fade`.</li> * </ul> */ static get observedAttributes() { return ['width', 'height', 'mode']; } ready: Promise<boolean>; private readonly root = this.attachShadow({ mode: 'open' }); private readonly itemsInView = new Set<Element>(); private modeInternal: 'scroll' | 'fade' = 'scroll'; private itemInternal = 0; private itemMax = 0; private widthInternal = 0; private heightInternal = 0; private observer!: IntersectionObserver; private onSlotChangeBound = this.onSlotChange.bind(this); private onContainerClickBound = this.onContainerClick.bind(this); private onButtonClickBound = this.onButtonClick.bind(this); private onIntersectionBound = this.onIntersection.bind(this); /* istanbul ignore next */ constructor({ polyfillPrefix = ''} = {}) { super(); this.ready = loadIntersectionObserverPolyfillIfNeeded({ polyfillPrefix }); } /** * Gets & sets the width of the card. */ get width() { return this.widthInternal; } set width(width: number) { if (Number.isNaN(width)) { width = 0; } this.setAttribute('width', width.toString()); } /** * Gets & sets the height of the card. */ get height() { return this.heightInternal; } set height(height: number) { if (Number.isNaN(height)) { height = 0; } this.setAttribute('height', height.toString()); } /** * Gets the current item's index. */ get item() { return this.itemInternal; } /** * Gets & sets the mode of the card. `scroll` autoscrolls between steps, * `fade` fades between steps. */ get mode() { return this.modeInternal; } set mode(mode: 'scroll' | 'fade') { this.setAttribute('mode', mode); } /** * @ignore Only public because it's a Custom Element. */ connectedCallback() { // Await the polyfill then go ahead. this.ready.then(() => { this.root.innerHTML = `<style>${styles}</style> ${html}`; const slot = this.root.querySelector('slot')!; const container = this.root.querySelector('#container')!; const buttons = this.root.querySelector('#buttons')!; slot.addEventListener('slotchange', this.onSlotChangeBound); container.addEventListener('click', this.onContainerClickBound); buttons.addEventListener('click', this.onButtonClickBound); this.setAttribute('tabindex', '0'); this.observer = new IntersectionObserver(this.onIntersectionBound, { root: container, rootMargin: '-5px', threshold: 0 }); this.updateCardDimensions(); this.observeChildren(); // Call the slot change callback manually for Safari 12; it doesn't do it // automatically for the initial element connection. this.onSlotChange(); }); } /** * @ignore Only public because it's a Custom Element. */ disconnectedCallback() { const slot = this.root.querySelector('slot')!; const container = this.root.querySelector('#container')!; const buttons = this.root.querySelector('#buttons')!; slot.removeEventListener('slotchange', this.onSlotChangeBound); container.removeEventListener('click', this.onContainerClickBound); buttons.addEventListener('click', this.onButtonClickBound); this.unobserveChildren(); this.root.innerHTML = ``; } /** * @ignore Only public because it's a Custom Element. */ attributeChangedCallback(name: string, oldValue: string, newValue: string) { switch (name) { case 'width': { const value = Number(newValue); this.widthInternal = Number.isNaN(value) ? 0 : value; break; } case 'height': { const value = Number(newValue); this.heightInternal = Number.isNaN(value) ? 0 : value; break; } case 'mode': this.modeInternal = newValue === 'fade' ? 'fade' : 'scroll'; break; } this.updateCardDimensions(); } /** * Moves to the next step. */ async next() { const from = this.itemInternal; this.itemInternal = clamp(this.itemInternal + 1, 0, this.itemMax - 1); await this.gotoItem({ from }); // The user has hit the final item in the list. if (from === this.itemInternal) { fire(OnboardingCard.onboardingFinishedEvent, this, { item: this.itemInternal }); } } /** * Jumps to a given item. Accepts an optional object with `from` and `to` * numbers indicating the indexes of the item to move from and to, * respectively. If not provided, `gotoItem` assumes that there is no `from` * and that it ought to go to the current item. */ async gotoItem({to = this.itemInternal, from = -1} = {}) { const elements = this.getSlotElements(); if (!elements[to] || (from !== -1 && !elements[from]) || from === to) { return; } if (this.mode === 'fade') { if (from !== -1) { await fade(elements[from] as HTMLElement, { from: 1, to: 0 }); // Bring the faded out element back up to 1 so that scrolling still // works as intended. (elements[from] as HTMLElement).style.opacity = '1'; } elements[to].scrollIntoView(); this.itemsInView.add(elements[to]); await fade(elements[to] as HTMLElement, { from: 0, to: 1 }); } else { elements[to].scrollIntoView({ behavior: 'smooth' }); } this.setLabel(); } private setLabel() { const elements = this.getSlotElements(); if (!elements[this.item]) { return; } this.setAttribute('aria-label', elements[this.item].getAttribute('alt') || 'No description provided'); } private onContainerClick() { this.next(); } private async onButtonClick(e: Event) { const buttons = this.root.querySelector('#buttons') as HTMLElement; let idx = Array.from(buttons.childNodes).indexOf(e.target as HTMLElement); /* istanbul ignore if */ if (idx === -1) { idx = 0; } const from = this.itemInternal; this.itemInternal = idx; await this.gotoItem({ from }); } private onIntersection(entries: IntersectionObserverEntry[]) { const elements = this.getSlotElements(); for (const entry of entries) { if (entry.isIntersecting) { this.itemsInView.add(entry.target); } else { this.itemsInView.delete(entry.target); } // Whenever the set of visible elements dips to 1 find the element. if (this.itemsInView.size !== 1) { continue; } const items = Array.from(this.itemsInView); this.itemInternal = elements.indexOf(items[0]); fire(OnboardingCard.itemChangedEvent, this, { item: this.itemInternal }); } const buttons = this.root.querySelectorAll('#buttons button'); for (const [bIdx, button] of buttons.entries()) { button.classList.toggle('active', bIdx === this.itemInternal); } } private observeChildren() { const elements = this.getSlotElements(); for (const element of elements) { this.observer.observe(element); } } private unobserveChildren() { // TODO(paullewis): Fire this on mutation events. const elements = this.getSlotElements(); for (const element of elements) { this.observer.observe(element); } } private getSlotElements() { const slot = this.root.querySelector('slot') as HTMLSlotElement; /* istanbul ignore if */ if (!slot) { return []; } const supportsAssignedElements = 'assignedElements' in slot; /* istanbul ignore else */ if (supportsAssignedElements) { return slot.assignedElements(); } else { return slot.assignedNodes() .filter((node) => node.nodeType === this.ELEMENT_NODE) as Element[]; } } private onSlotChange() { const buttons = this.root.querySelector('#buttons'); const elements = this.getSlotElements(); this.itemMax = elements.length; /* istanbul ignore if */ if (!buttons) { return; } // Create status / control buttons for each state. buttons.innerHTML = ''; for (let i = 0; i < this.itemMax; i++) { const button = document.createElement('button'); button.textContent = `${i + 1}`; buttons.appendChild(button); } this.setLabel(); } private updateCardDimensions() { const container = this.root.querySelector('#container') as HTMLElement; /* istanbul ignore if */ if (!container) { return; } container.style.width = `${this.width}px`; container.style.height = `${this.height}px`; } }
the_stack
import { ChannelBytes, ChannelCompression, ChannelKind, getChannelKindOffset, } from "../interfaces"; import {UnsupportedCompression} from "../utils/error"; /** * Decodes one or more encoded channels and combines them into an image. * @param width Width of the decoded image in pixels * @param height Height of the decoded image in pixels * @param red Encoded red channel data * @param green Encoded green channel data * @param blue Encoded blue channel data * @param alpha Encoded alpha channel data * @returns `Uint8ClampedArray` containing the pixel data of the decoded image. * Each pixel takes up 4 bytes--1 byte for red, blue, green, and alpha. */ export function generateRgba( width: number, height: number, red: ChannelBytes, green?: ChannelBytes, blue?: ChannelBytes, alpha?: ChannelBytes ): Uint8ClampedArray { const pixelCount = width * height; if (!(pixelCount > 0 && Number.isInteger(pixelCount))) { throw new Error( `Pixel count must be a positive integer, got ${pixelCount}` ); } const outputRegionSize = pixelCount * 4; // Note: This can become zero when the entire image is blank const minimumInputRegionSize = Math.max( red.data.byteLength ?? 0, blue?.data.byteLength ?? 0, green?.data.byteLength ?? 0, alpha?.data.byteLength ?? 0 ); if ( !(minimumInputRegionSize >= 0 && Number.isInteger(minimumInputRegionSize)) ) { // This may be a zero when all channels are empty // In such cases, we still need to generate a blank image throw new Error( `Input region size must be a nonnegative integer, got ${minimumInputRegionSize}` ); } /** * Heap used by the asm.js image decoder module. * This is divided into two regions: * * (start) (end) * +-----------------+----------------+ * | Output region | Input region | * +-----------------+----------------+ * * The output region holds the pixel data for the decoded image, and the input * region is used for the encoded channel data. * * For each channel, the wrapper (JS) copies the encoded channel data into the * input region. Then the image decoder (asm.js) reads and decodes the input * region, and writes the result into the output region. Once all the channels * have been decoded, the wrapper copies the output region (now containing the * decoded image) into a separate ArrayBuffer. */ const heap = new ArrayBuffer( computeHeapSize(outputRegionSize + minimumInputRegionSize) ); // In Chrome, creating a new TypedArray is much faster when the old and new // TypedArrays have the same type (e.g. Uint8Array -> Uint8Array). // Since we want to return a Uint8ClampedArray, let's optimize for it const outputRegionView = new Uint8ClampedArray(heap, 0, outputRegionSize); const inputRegionView = new Uint8Array(heap, outputRegionSize); const decoder = AsmJsImageDecoder({Int8Array, Uint8Array}, {}, heap); // If the blue and green channels are unavailable, assume that this is a // grayscale image and reuse the red channel for blue and green. // TODO: Check color mode and depth to determine grayscale-ness instead decodeChannel( decoder, inputRegionView, outputRegionView.byteOffset, red, getChannelKindOffset(ChannelKind.Red) ); decodeChannel( decoder, inputRegionView, outputRegionView.byteOffset, green ?? red, getChannelKindOffset(ChannelKind.Green) ); decodeChannel( decoder, inputRegionView, outputRegionView.byteOffset, blue ?? red, getChannelKindOffset(ChannelKind.Blue) ); if (alpha) { decodeChannel( decoder, inputRegionView, outputRegionView.byteOffset, alpha, getChannelKindOffset(ChannelKind.TransparencyMask) ); } else { setChannelValue( decoder, outputRegionView.byteOffset, outputRegionView.byteLength, 255, getChannelKindOffset(ChannelKind.TransparencyMask) ); } // Return a copy of the heap, excluding the input region return outputRegionView.slice(); } type ChannelOffset = 0 | 1 | 2 | 3; type ImageDecoderModule = ReturnType<typeof AsmJsImageDecoder>; /** * Decodes a single channel and stores the result in the heap of the * {@link decoder}. * @param decoder * @param inputRegionView Uint8Array that covers the input region of the heap * @param outputRegionOffset Offset of the output region * @param data * @param channelOffset * @param method */ function decodeChannel( decoder: ImageDecoderModule, inputRegionView: Uint8Array, outputRegionOffset: number, channelBytes: ChannelBytes, channelOffset: ChannelOffset ): void { // Copy the data into the input region (size check done by native method) try { inputRegionView.set(channelBytes.data); } catch (e) { if (e instanceof RangeError) { throw new Error( `Channel data (${channelBytes.data.byteLength} bytes) is too large for the input region (${inputRegionView.byteLength} bytes)` ); } else { throw e; } } let result: DecodeResult; switch (channelBytes.compression) { case ChannelCompression.RawData: result = decoder.decodeUncompressedChannel( inputRegionView.byteOffset, channelBytes.data.byteLength, outputRegionOffset, channelOffset ); break; case ChannelCompression.RleCompressed: result = decoder.decodeRleChannel( inputRegionView.byteOffset, channelBytes.data.byteLength, outputRegionOffset, channelOffset ); break; default: throw new UnsupportedCompression( `Unsupported compression method: ${channelBytes.compression}` ); } if (result !== DecodeResult.Success) { throw new Error(`Decode failed (cause: ${result})`); } } /** * Sets the value of a single channel of all pixels in the output image. * @param decoder * @param outputRegionOffset Offset of the output region * @param outputRegionLength Length of the output region in bytes * @param value Channel value * @param channelOffset */ function setChannelValue( decoder: ImageDecoderModule, outputRegionOffset: number, outputRegionLength: number, value: number, channelOffset: ChannelOffset ): void { if (!(Number.isInteger(value) && 0 <= value && value <= 255)) { throw new Error( `Channel value must be an integer between 0 and 255, got ${value}` ); } const result = decoder.setChannelValue( outputRegionOffset, outputRegionLength, channelOffset, value ); if (result !== DecodeResult.Success) { throw new Error(`Channel update failed (cause: ${result})`); } } /** * Computes the smallest valid size of an asm.js heap buffer that is at least as * large as {@link minSize}. * @param minSize Minimum size of the heap * @return Valid heap size */ function computeHeapSize(minSize: number) { // According to the asm.js spec, the heap size must be: // // 1. A power of 2 between 4096 (= 2^12 = 4 KiB) and 8388608 (= 2^23 = 8 MiB), // 2. ...or a multiple of 16777216 (= 2^24 = 16 MiB) // // However, Firefox does not implement the spec correctly. Its asm.js // optimizer requires a minimum heap size of 65536 (= 2^16 = 64 KiB). // (Tested on Firefox 94 ~ 95) let heapSize = 0x10_000; while (heapSize < minSize) { if (heapSize < 0x1_000_000) { heapSize <<= 1; } else { heapSize += 0x1_000_000; } } return heapSize; } /** * Return codes used by the asm.js decoder to communicate the result of decoding * a single image channel. */ const enum DecodeResult { Success = 0, } /** * asm.js module that decodes PSD image channels into ImageData-compatible pixel * data. * @param stdlib * @param foreign * @param buffer */ function AsmJsImageDecoder( stdlib: {Int8Array: typeof Int8Array; Uint8Array: typeof Uint8Array}, foreign: Record<string, never>, // Empty object buffer: ArrayBuffer ) { // Disable ESLint rules that do not make sense for asm.js code /* eslint-disable no-var */ "use asm"; // We prefer Int8Array because the PackBits algorithm distinguishes // positive and negative numbers. const heap = new stdlib.Int8Array(buffer); /** * Uint8Array-based view of the heap. This is used to directly assign values * to each channel, since it is more familiar to developers who use * Uint8ClampedArray to manage pixel data. */ const uHeap = new stdlib.Uint8Array(buffer); /** * Decodes a single uncompressed channel, reading the channel data from the * heap at {@link inputOffset} of the heap and writing the decoded result at * {@link outputOffset} of the heap. * @param inputOffset Offset of the input region in the heap * @param inputLength Length of the input region to read * @param outputOffset Offset of the output region in the heap * @param channelOffset Channel offset within each pixel * (0 = red, 1 = green, 2 = blue, 3 = alpha) */ function decodeUncompressedChannel( inputOffset: number, inputLength: number, outputOffset: number, channelOffset: ChannelOffset ): DecodeResult { inputOffset = inputOffset | 0; inputLength = inputLength | 0; outputOffset = outputOffset | 0; // @ts-expect-error There's no way to convince TypeScript that this is OK. // We can't use a type assertion here because it emits invalid asm.js code. channelOffset = channelOffset | 0; /** Offset of current input byte in the heap */ var currentInputOffset = 0; /** Offset of current output byte in the heap */ var currentOutputOffset = 0; // Variables to use for iteration var end = 0; currentInputOffset = inputOffset; // Point to the channel of the first pixel currentOutputOffset = (channelOffset + outputOffset) | 0; for ( end = (currentInputOffset + inputLength) | 0; (currentInputOffset | 0) < (end | 0); currentInputOffset = (currentInputOffset + 1) | 0 ) { heap[currentOutputOffset] = heap[currentInputOffset]; // Move to next pixel (1 pixel == 4 bytes) currentOutputOffset = (currentOutputOffset + 4) | 0; } return DecodeResult.Success; } /** * Decodes a single RLE-encoded channel, reading the channel data from the * heap at {@link inputOffset} of the heap and writing the decoded result at * {@link outputOffset} of the heap. * @param inputOffset Offset of the input region in the heap * @param inputLength Length of the input region to read * @param outputOffset Offset of the output region in the heap * @param channelOffset Channel offset within each pixel * (0 = red, 1 = green, 2 = blue, 3 = alpha) */ function decodeRleChannel( inputOffset: number, inputLength: number, outputOffset: number, channelOffset: ChannelOffset ): DecodeResult { inputOffset = inputOffset | 0; inputLength = inputLength | 0; outputOffset = outputOffset | 0; // @ts-expect-error There's no way to convince TypeScript that this is OK. // We can't use a type assertion here because it emits invalid asm.js code. channelOffset = channelOffset | 0; /** Offset of current input byte in the heap */ var currentInputOffset = 0; /** Offset of current output byte in the heap */ var currentOutputOffset = 0; /** Value of the header byte */ var header = 0; // Variables to use for iteration var i = 0; var end = 0; var repeatedByte = 0; var repeatCount = 0; currentInputOffset = inputOffset; // Point to the channel of the first pixel currentOutputOffset = (channelOffset + outputOffset) | 0; while ((currentInputOffset | 0) < ((inputOffset + inputLength) | 0)) { // Read the header byte header = heap[currentInputOffset] | 0; currentInputOffset = (currentInputOffset + 1) | 0; if ((header | 0) == -128) { // Skip byte continue; } else if ((header | 0) >= 0) { // Treat the following (header + 1) bytes as uncompressed data; // copy as-is for ( end = (currentInputOffset + header + 1) | 0; (currentInputOffset | 0) < (end | 0); currentInputOffset = (currentInputOffset + 1) | 0 ) { heap[currentOutputOffset] = heap[currentInputOffset]; // Move to next pixel (1 pixel == 4 bytes) currentOutputOffset = (currentOutputOffset + 4) | 0; } } else { // Following byte is repeated (1 - header) times repeatedByte = heap[currentInputOffset] | 0; currentInputOffset = (currentInputOffset + 1) | 0; repeatCount = (1 - header) | 0; for (i = 0; (i | 0) < (repeatCount | 0); i = (i + 1) | 0) { heap[currentOutputOffset] = repeatedByte; // Move to next pixel (1 pixel == 4 bytes) currentOutputOffset = (currentOutputOffset + 4) | 0; } } } return DecodeResult.Success; } /** * Sets a single channel of all pixels in the output to the given value. * @param outputOffset Offset of the output region in the heap * @param outputLength Length of the output region in bytes * @param channelOffset Channel offset within each pixel * (0 = red, 1 = green, 2 = blue, 3 = alpha) * @param value Value to assign to the channel. Must be between 0 and 255 * (inclusive) */ function setChannelValue( outputOffset: number, outputLength: number, channelOffset: number, value: number ): DecodeResult { outputOffset = outputOffset | 0; outputLength = outputLength | 0; channelOffset = channelOffset | 0; value = value | 0; /** Offset of current output byte in the heap */ var currentOutputOffset = 0; // Variables to use for iteration var end = 0; // Point to the channel of the first pixel currentOutputOffset = (channelOffset + outputOffset) | 0; end = (outputOffset + outputLength) | 0; while ((currentOutputOffset | 0) < (end | 0)) { uHeap[currentOutputOffset] = value | 0; // Move to next pixel (1 pixel == 4 bytes) currentOutputOffset = (currentOutputOffset + 4) | 0; } return DecodeResult.Success; } return { decodeUncompressedChannel: decodeUncompressedChannel, decodeRleChannel: decodeRleChannel, setChannelValue: setChannelValue, }; /* eslint-enable no-var */ }
the_stack
import React, { useCallback, useMemo, useState } from "react"; import ReactDOM from "react-dom"; import EditContainer from "./EditContainer"; import { VerticalTimeline, VerticalTimelineElement, } from "react-vertical-timeline-component"; import "react-vertical-timeline-component/style.min.css"; import { Checkbox, Icon, InputGroup, Label } from "@blueprintjs/core"; import { getTreeByBlockUid, getTreeByPageName, getUidsFromId, parseRoamDate, toRoamDate, toRoamDateUid, TreeNode, } from "roam-client"; import { createTagRegex, DAILY_NOTE_PAGE_REGEX, DAILY_NOTE_TAG_REGEX, DAILY_NOTE_TAG_REGEX_GLOBAL, extractTag, getRoamUrl, openBlockInSidebar, parseRoamMarked, resolveRefs, } from "../entry-helpers"; import { getSettingIntFromTree, MenuItemSelect, } from "roamjs-components"; import TagFilter from "./TagFilter"; type TimelineProps = { blockId: string }; const getText = (cur: string) => { try { return parseRoamMarked(cur); } catch { return cur; } }; const reduceChildren = (prev: string, cur: TreeNode, l: number): string => `${prev}<span>${"".padEnd(l * 2, " ")}</span>${getText( cur.text )}<br/>${cur.children.reduce((p, c) => reduceChildren(p, c, l + 1), "")}`; const getTag = (blockUid: string) => { const tree = getTreeByBlockUid(blockUid); const tagNode = tree.children.find((t) => /tag/i.test(t.text)); if (tagNode && tagNode.children.length) { return extractTag(tagNode.children[0].text); } return ""; }; const LAYOUTS = { LEFT: "1-column-left", RIGHT: "1-column-right", ALT: "2-columns", }; const getLayout = (blockUid: string) => { const tree = getTreeByBlockUid(blockUid); const layoutNode = tree.children.find((t) => /layout/i.test(t.text)); if (layoutNode && layoutNode.children.length) { return ( LAYOUTS[ layoutNode.children[0].text.toUpperCase() as keyof typeof LAYOUTS ] || "2-columns" ); } return "2-columns"; }; const getColors = (blockUid: string) => { const tree = getTreeByBlockUid(blockUid); const colorNode = tree.children.find((t) => /colors/i.test(t.text)); if (colorNode && colorNode.children.length) { return colorNode.children.map((c) => c.text); } return ["#2196f3"]; }; const getReverse = (blockUid: string) => { const tree = getTreeByBlockUid(blockUid); return tree.children.some((t) => /reverse/i.test(t.text)); }; const getCreationDate = (blockUid: string) => { const tree = getTreeByBlockUid(blockUid); return tree.children.some((t) => /creation date/i.test(t.text)); }; const getHideTags = (blockUid: string) => { const tree = getTreeByBlockUid(blockUid); return tree.children.some((t) => /clean/i.test(t.text)); }; const BooleanSetting = ({ blockUid, name, refresh, }: { blockUid: string; name: string; refresh: () => void; }) => { const regex = new RegExp(name, "i"); const [booleanSetting, setBooleanSetting] = useState(() => { const tree = getTreeByBlockUid(blockUid); return tree.children.some((t) => regex.test(t.text)); }); const onBooleanChange = useCallback( (e: React.FormEvent<HTMLInputElement>) => { const newValue = (e.target as HTMLInputElement).checked; setBooleanSetting(newValue); if (newValue) { window.roamAlphaAPI.createBlock({ location: { "parent-uid": blockUid, order: 0 }, block: { string: name }, }); } else { const uid = getTreeByBlockUid(blockUid).children.find((t) => regex.test(t.text) ).uid; window.roamAlphaAPI.deleteBlock({ block: { uid }, }); } setTimeout(refresh, 1); }, [setBooleanSetting, blockUid, refresh] ); return ( <Checkbox label={name} onChange={onBooleanChange} checked={booleanSetting} /> ); }; const Timeline: React.FunctionComponent<TimelineProps> = ({ blockId }) => { const { blockUid } = getUidsFromId(blockId); const depth = useMemo( () => getSettingIntFromTree({ tree: getTreeByPageName("roam/js/timeline"), key: "depth", defaultValue: -1, }), [] ); const getTimelineElements = useCallback(() => { const tag = getTag(blockUid); const reverse = getReverse(blockUid); const useCreationDate = getCreationDate(blockUid); const useHideTags = getHideTags(blockUid); if (tag) { const blocks = window.roamAlphaAPI.q( `[:find ?s ?pt ?u ?cd :where [?b :create/time ?cd] [?b :block/uid ?u] [?b :block/string ?s] [?p :node/title ?pt] [?b :block/page ?p] [?b :block/refs ?t] [?t :node/title "${tag}"]]` ) as string[][]; return blocks .filter( ([text, pageTitle]) => useCreationDate || DAILY_NOTE_PAGE_REGEX.test(pageTitle) || DAILY_NOTE_TAG_REGEX.test(text) ) .flatMap(([text, pageTitle, uid, creationDate]) => { const node = getTreeByBlockUid(uid); if (depth >= 0) { const trim = (n:TreeNode, level: number) => { if (level >= depth) { n.children = []; } n.children.forEach(c => trim(c, level + 1)); } trim(node, 0); } const { children } = node; const dates = useCreationDate ? [toRoamDate(new Date(creationDate))] : DAILY_NOTE_PAGE_REGEX.test(pageTitle) ? [pageTitle] : text .match(DAILY_NOTE_TAG_REGEX_GLOBAL) .map((d) => d.match(DAILY_NOTE_TAG_REGEX)?.[1]); return dates.map((date) => ({ date, uid, text: resolveRefs( getText( text .replace(createTagRegex(tag), (a) => (useHideTags ? "" : a)) .replace(DAILY_NOTE_TAG_REGEX, (a) => (useHideTags ? "" : a)) ) ).trim(), body: resolveRefs( children.reduce((prev, cur) => reduceChildren(prev, cur, 0), "") ), })); }) .sort(({ date: a }, { date: b }) => { const bDate = parseRoamDate(b).valueOf(); const aDate = parseRoamDate(a).valueOf(); return reverse ? aDate - bDate : bDate - aDate; }); } return []; }, [blockId]); const [timelineElements, setTimelineElements] = useState(getTimelineElements); const [filters, setFilters] = useState({ includes: [], excludes: [] }); const filteredElements = useMemo(() => { const validUids = filters.includes.length ? new Set() : new Set(timelineElements.map((t) => t.uid)); filters.includes.forEach((inc) => window.roamAlphaAPI .q( `[:find ?u ?pu :where [?par :block/uid ?pu] [?b :block/parents ?par] [?b :block/uid ?u] [?b :block/refs ?p] [?p :node/title "${inc}"]]` ) .map((uids) => uids.filter((u) => !!u).forEach((u) => validUids.add(u))) ); filters.excludes.forEach((exc) => window.roamAlphaAPI .q( `[:find ?u ?pu :where [?par :block/uid ?pu] [?b :block/parents ?par] [?b :block/uid ?u] [?b :block/refs ?p] [?p :node/title "${exc}"]]` ) .map((uids) => uids.filter((u) => !!u).forEach((u) => validUids.delete(u)) ) ); return timelineElements.filter((t) => validUids.has(t.uid)); }, [filters, timelineElements]); const [colors, setColors] = useState(() => getColors(blockUid)); const [layout, setLayout] = useState(() => getLayout(blockUid)); const refresh = useCallback(() => { setTimelineElements(getTimelineElements()); setColors(getColors(blockUid)); setLayout(getLayout(blockUid)); }, [ setTimelineElements, getTimelineElements, setColors, setLayout, blockUid, ]); const [tagSetting, setTagSetting] = useState(() => getTag(blockUid)); const onTagBlur = useCallback(() => { const { blockUid } = getUidsFromId(blockId); const tree = getTreeByBlockUid(blockUid); const tagNode = tree.children.find((t) => /tag/i.test(t.text)); if (tagNode && tagNode.children.length) { window.roamAlphaAPI.updateBlock({ block: { uid: tagNode.children[0].uid, string: tagSetting }, }); } else if (!tagNode) { const uid = window.roamAlphaAPI.util.generateUID(); window.roamAlphaAPI.createBlock({ location: { "parent-uid": blockUid, order: 0 }, block: { string: "tag", uid }, }); window.roamAlphaAPI.createBlock({ location: { "parent-uid": uid, order: 0 }, block: { string: tagSetting }, }); } else { window.roamAlphaAPI.createBlock({ location: { "parent-uid": tagNode.uid, order: 0 }, block: { string: tagSetting }, }); } setTimeout(refresh, 1); }, [blockId, refresh, tagSetting]); const onLayoutSelect = useCallback( (key: keyof typeof LAYOUTS) => { const { blockUid } = getUidsFromId(blockId); const tree = getTreeByBlockUid(blockUid); const layoutNode = tree.children.find((t) => /layout/i.test(t.text)); if (layoutNode && layoutNode.children.length) { window.roamAlphaAPI.updateBlock({ block: { uid: layoutNode.children[0].uid, string: key.toLowerCase() }, }); } else if (!layoutNode) { const uid = window.roamAlphaAPI.util.generateUID(); window.roamAlphaAPI.createBlock({ location: { "parent-uid": blockUid, order: 0 }, block: { string: "layout", uid }, }); window.roamAlphaAPI.createBlock({ location: { "parent-uid": uid, order: 0 }, block: { string: key.toLowerCase() }, }); } else { window.roamAlphaAPI.createBlock({ location: { "parent-uid": layoutNode.uid, order: 0 }, block: { string: key.toLowerCase() }, }); } setTimeout(refresh, 1); }, [setLayout, refresh] ); return ( <> <EditContainer refresh={refresh} blockId={blockId} containerStyleProps={{ backgroundColor: "#CCCCCC", width: "100%", minWidth: 840, }} Settings={ <> <Label> Tag <InputGroup value={tagSetting} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setTagSetting(e.target.value) } onBlur={onTagBlur} /> </Label> <BooleanSetting blockUid={blockUid} refresh={refresh} name={"Reverse"} /> <BooleanSetting blockUid={blockUid} refresh={refresh} name={"Creation Date"} /> <BooleanSetting blockUid={blockUid} refresh={refresh} name={"Clean"} /> <Label> Layout <MenuItemSelect items={Object.keys(LAYOUTS)} activeItem={Object.keys(LAYOUTS).find( (k) => LAYOUTS[k as keyof typeof LAYOUTS] === layout )} onItemSelect={onLayoutSelect} /> </Label> </> } > <VerticalTimeline // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore types doesn't support left/right layout={layout} > {filteredElements.map((t, i) => ( <VerticalTimelineElement contentStyle={{ backgroundColor: colors[i % colors.length], color: "#fff", }} contentArrowStyle={{ borderRight: `7px solid ${colors[i % colors.length]}`, }} // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore could technically take react node date={ <a href={getRoamUrl(toRoamDateUid(parseRoamDate(t.date)))}> {t.date} </a> } dateClassName={"roamjs-timeline-date"} iconStyle={{ backgroundColor: colors[i % colors.length], color: "#fff", }} icon={ <Icon icon="calendar" style={{ height: "100%", width: "100%" }} /> } key={`${t.uid}-${t.date}`} > <h3 className="vertical-timeline-element-title" dangerouslySetInnerHTML={{ __html: t.text || "Empty Block", }} /> <h4 className="vertical-timeline-element-subtitle"> <a href={getRoamUrl(t.uid)} onClick={(e) => { if (e.shiftKey) { openBlockInSidebar(t.uid); e.preventDefault(); } }} > {t.uid} </a> </h4> <p className="vertical-timeline-element-body" dangerouslySetInnerHTML={{ __html: t.body, }} /> </VerticalTimelineElement> ))} {filteredElements.length && (() => { const tag = getTag(blockUid); const tags = new Set( filteredElements.flatMap((t) => [ ...window.roamAlphaAPI.q( `[:find ?t :where [?p :node/title ?t] [?b :block/refs ?p] [?b :block/uid "${t.uid}"]]` ), ...window.roamAlphaAPI.q( `[:find ?t :where [?p :node/title ?t] [?c :block/parents ?b] [?c :block/refs ?p] [?b :block/uid "${t.uid}"]]` ), ].map((s) => s[0]) ) ); tags.delete(tag); return ( <div style={{ position: "absolute", top: 8 }}> <TagFilter blockUid={blockUid} onChange={setFilters} tags={Array.from(tags)} /> </div> ); })()} </VerticalTimeline> </EditContainer> </> ); }; export const render = ({ p, ...props }: { p: HTMLSpanElement } & TimelineProps): void => ReactDOM.render(<Timeline {...props} />, p);
the_stack
import { TypedArray } from '../types' const defaultByteLength = 1024 * 8 const charArray: string[] = [] export interface IOBufferParameters { offset?: number // Ignore the first n bytes of the ArrayBuffer } /** * Class for writing and reading binary data */ class IOBuffer { private _lastWrittenByte: number private _mark = 0 private _marks: number[] = [] private _data: DataView offset = 0 // The current offset of the buffer's pointer littleEndian = true buffer: ArrayBuffer // Reference to the internal ArrayBuffer object length: number // Byte length of the internal ArrayBuffer byteLength: number // Byte length of the internal ArrayBuffer byteOffset: number // Byte offset of the internal ArrayBuffer /** * If it's a number, it will initialize the buffer with the number as * the buffer's length. If it's undefined, it will initialize the buffer * with a default length of 8 Kb. If its an ArrayBuffer, a TypedArray, * it will create a view over the underlying ArrayBuffer. */ constructor (data: number|ArrayBuffer|TypedArray, params: IOBufferParameters = {}) { let dataIsGiven = false if (data === undefined) { data = defaultByteLength } if (typeof data === 'number') { data = new ArrayBuffer(data) } else { dataIsGiven = true } const offset = params.offset ? params.offset >>> 0 : 0 let byteLength = data.byteLength - offset let dvOffset = offset if (!(data instanceof ArrayBuffer)) { if (data.byteLength !== data.buffer.byteLength) { dvOffset = data.byteOffset + offset } data = data.buffer } if (dataIsGiven) { this._lastWrittenByte = byteLength } else { this._lastWrittenByte = 0 } this.buffer = data this.length = byteLength this.byteLength = byteLength this.byteOffset = dvOffset this._data = new DataView(this.buffer, dvOffset, byteLength) } /** * Checks if the memory allocated to the buffer is sufficient to store more bytes after the offset * @param {number} [byteLength=1] The needed memory in bytes * @return {boolean} Returns true if there is sufficient space and false otherwise */ available (byteLength: number) { if (byteLength === undefined) byteLength = 1 return (this.offset + byteLength) <= this.length } /** * Check if little-endian mode is used for reading and writing multi-byte values * @return {boolean} Returns true if little-endian mode is used, false otherwise */ isLittleEndian () { return this.littleEndian } /** * Set little-endian mode for reading and writing multi-byte values * @return {IOBuffer} */ setLittleEndian () { this.littleEndian = true return this } /** * Check if big-endian mode is used for reading and writing multi-byte values * @return {boolean} Returns true if big-endian mode is used, false otherwise */ isBigEndian () { return !this.littleEndian } /** * Switches to big-endian mode for reading and writing multi-byte values * @return {IOBuffer} */ setBigEndian () { this.littleEndian = false return this } /** * Move the pointer n bytes forward * @param {number} n * @return {IOBuffer} */ skip (n: number) { if (n === undefined) n = 1 this.offset += n return this } /** * Move the pointer to the given offset * @param {number} offset * @return {IOBuffer} */ seek (offset: number) { this.offset = offset return this } /** * Store the current pointer offset. * @see {@link IOBuffer#reset} * @return {IOBuffer} */ mark () { this._mark = this.offset return this } /** * Move the pointer back to the last pointer offset set by mark * @see {@link IOBuffer#mark} * @return {IOBuffer} */ reset () { this.offset = this._mark return this } /** * Push the current pointer offset to the mark stack * @see {@link IOBuffer#popMark} * @return {IOBuffer} */ pushMark () { this._marks.push(this.offset) return this } /** * Pop the last pointer offset from the mark stack, and set the current pointer offset to the popped value * @see {@link IOBuffer#pushMark} * @return {IOBuffer} */ popMark () { const offset = this._marks.pop() if (offset === undefined) throw new Error('Mark stack empty') this.seek(offset) return this } /** * Move the pointer offset back to 0 * @return {IOBuffer} */ rewind () { this.offset = 0 return this } /** * Make sure the buffer has sufficient memory to write a given byteLength at the current pointer offset * If the buffer's memory is insufficient, this method will create a new buffer (a copy) with a length * that is twice (byteLength + current offset) * @param {number} [byteLength = 1] * @return {IOBuffer} */ ensureAvailable (byteLength: number) { if (byteLength === undefined) byteLength = 1 if (!this.available(byteLength)) { const lengthNeeded = this.offset + byteLength const newLength = lengthNeeded * 2 const newArray = new Uint8Array(newLength) newArray.set(new Uint8Array(this.buffer)) this.buffer = newArray.buffer this.length = this.byteLength = newLength this._data = new DataView(this.buffer) } return this } /** * Read a byte and return false if the byte's value is 0, or true otherwise * Moves pointer forward * @return {boolean} */ readBoolean () { return this.readUint8() !== 0 } /** * Read a signed 8-bit integer and move pointer forward * @return {number} */ readInt8 () { return this._data.getInt8(this.offset++) } /** * Read an unsigned 8-bit integer and move pointer forward * @return {number} */ readUint8 () { return this._data.getUint8(this.offset++) } /** * Alias for {@link IOBuffer#readUint8} * @return {number} */ readByte () { return this.readUint8() } /** * Read n bytes and move pointer forward. * @param {number} n * @return {Uint8Array} */ readBytes (n: number) { if (n === undefined) n = 1 var bytes = new Uint8Array(n) for (var i = 0; i < n; i++) { bytes[i] = this.readByte() } return bytes } /** * Read a 16-bit signed integer and move pointer forward * @return {number} */ readInt16 () { var value = this._data.getInt16(this.offset, this.littleEndian) this.offset += 2 return value } /** * Read a 16-bit unsigned integer and move pointer forward * @return {number} */ readUint16 () { var value = this._data.getUint16(this.offset, this.littleEndian) this.offset += 2 return value } /** * Read a 32-bit signed integer and move pointer forward * @return {number} */ readInt32 () { var value = this._data.getInt32(this.offset, this.littleEndian) this.offset += 4 return value } /** * Read a 32-bit unsigned integer and move pointer forward * @return {number} */ readUint32 () { var value = this._data.getUint32(this.offset, this.littleEndian) this.offset += 4 return value } /** * Read a 32-bit floating number and move pointer forward * @return {number} */ readFloat32 () { var value = this._data.getFloat32(this.offset, this.littleEndian) this.offset += 4 return value } /** * Read a 64-bit floating number and move pointer forward * @return {number} */ readFloat64 () { var value = this._data.getFloat64(this.offset, this.littleEndian) this.offset += 8 return value } /** * Read 1-byte ascii character and move pointer forward * @return {string} */ readChar () { return String.fromCharCode(this.readInt8()) } /** * Read n 1-byte ascii characters and move pointer forward * @param {number} n * @return {string} */ readChars (n = 1) { charArray.length = n for (var i = 0; i < n; i++) { charArray[i] = this.readChar() } return charArray.join('') } /** * Write 0xff if the passed value is truthy, 0x00 otherwise * @param {any} value * @return {IOBuffer} */ writeBoolean (value = false) { this.writeUint8(value ? 0xff : 0x00) return this } /** * Write value as an 8-bit signed integer * @param {number} value * @return {IOBuffer} */ writeInt8 (value: number) { this.ensureAvailable(1) this._data.setInt8(this.offset++, value) this._updateLastWrittenByte() return this } /** * Write value as a 8-bit unsigned integer * @param {number} value * @return {IOBuffer} */ writeUint8 (value: number) { this.ensureAvailable(1) this._data.setUint8(this.offset++, value) this._updateLastWrittenByte() return this } /** * An alias for {@link IOBuffer#writeUint8} * @param {number} value * @return {IOBuffer} */ writeByte (value: number) { return this.writeUint8(value) } /** * Write bytes * @param {Array|Uint8Array} bytes * @return {IOBuffer} */ writeBytes (bytes: number[]|Uint8Array) { this.ensureAvailable(bytes.length) for (var i = 0; i < bytes.length; i++) { this._data.setUint8(this.offset++, bytes[i]) } this._updateLastWrittenByte() return this } /** * Write value as an 16-bit signed integer * @param {number} value * @return {IOBuffer} */ writeInt16 (value: number) { this.ensureAvailable(2) this._data.setInt16(this.offset, value, this.littleEndian) this.offset += 2 this._updateLastWrittenByte() return this } /** * Write value as a 16-bit unsigned integer * @param {number} value * @return {IOBuffer} */ writeUint16 (value: number) { this.ensureAvailable(2) this._data.setUint16(this.offset, value, this.littleEndian) this.offset += 2 this._updateLastWrittenByte() return this } /** * Write a 32-bit signed integer at the current pointer offset * @param {number} value * @return {IOBuffer} */ writeInt32 (value: number) { this.ensureAvailable(4) this._data.setInt32(this.offset, value, this.littleEndian) this.offset += 4 this._updateLastWrittenByte() return this } /** * Write a 32-bit unsigned integer at the current pointer offset * @param {number} value - The value to set * @return {IOBuffer} */ writeUint32 (value: number) { this.ensureAvailable(4) this._data.setUint32(this.offset, value, this.littleEndian) this.offset += 4 this._updateLastWrittenByte() return this } /** * Write a 32-bit floating number at the current pointer offset * @param {number} value - The value to set * @return {IOBuffer} */ writeFloat32 (value: number) { this.ensureAvailable(4) this._data.setFloat32(this.offset, value, this.littleEndian) this.offset += 4 this._updateLastWrittenByte() return this } /** * Write a 64-bit floating number at the current pointer offset * @param {number} value * @return {IOBuffer} */ writeFloat64 (value: number) { this.ensureAvailable(8) this._data.setFloat64(this.offset, value, this.littleEndian) this.offset += 8 this._updateLastWrittenByte() return this } /** * Write the charCode of the passed string's first character to the current pointer offset * @param {string} str - The character to set * @return {IOBuffer} */ writeChar (str: string) { return this.writeUint8(str.charCodeAt(0)) } /** * Write the charCodes of the passed string's characters to the current pointer offset * @param {string} str * @return {IOBuffer} */ writeChars (str: string) { for (var i = 0; i < str.length; i++) { this.writeUint8(str.charCodeAt(i)) } return this } /** * Export a Uint8Array view of the internal buffer. * The view starts at the byte offset and its length * is calculated to stop at the last written byte or the original length. * @return {Uint8Array} */ toArray () { return new Uint8Array(this.buffer, this.byteOffset, this._lastWrittenByte) } /** * Update the last written byte offset * @private */ _updateLastWrittenByte () { if (this.offset > this._lastWrittenByte) { this._lastWrittenByte = this.offset } } } export default IOBuffer
the_stack
import { ChangeDetectorRef, Component, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { combineLatest, Observable, of as observableOf, Subscription } from 'rxjs'; import { filter, map, mergeMap, scan } from 'rxjs/operators'; import { DynamicFormControlComponent, DynamicFormControlModel, DynamicFormGroupModel, DynamicFormLayoutService, DynamicFormValidationService, DynamicInputModel } from '@ng-dynamic-forms/core'; import { isEqual, isObject } from 'lodash'; import { DynamicRelationGroupModel } from './dynamic-relation-group.model'; import { FormBuilderService } from '../../../form-builder.service'; import { SubmissionFormsModel } from '../../../../../../core/config/models/config-submission-forms.model'; import { FormService } from '../../../../form.service'; import { FormComponent } from '../../../../form.component'; import { Chips } from '../../../../../chips/models/chips.model'; import { hasValue, isEmpty, isNotEmpty, isNotNull } from '../../../../../empty.util'; import { shrinkInOut } from '../../../../../animations/shrink'; import { ChipsItem } from '../../../../../chips/models/chips-item.model'; import { hasOnlyEmptyProperties } from '../../../../../object.util'; import { VocabularyService } from '../../../../../../core/submission/vocabularies/vocabulary.service'; import { FormFieldMetadataValueObject } from '../../../models/form-field-metadata-value.model'; import { environment } from '../../../../../../../environments/environment'; import { PLACEHOLDER_PARENT_METADATA } from '../../ds-dynamic-form-constants'; import { getFirstSucceededRemoteDataPayload } from '../../../../../../core/shared/operators'; import { VocabularyEntryDetail } from '../../../../../../core/submission/vocabularies/models/vocabulary-entry-detail.model'; /** * Component representing a group input field */ @Component({ selector: 'ds-dynamic-relation-group', styleUrls: ['./dynamic-relation-group.component.scss'], templateUrl: './dynamic-relation-group.component.html', animations: [shrinkInOut] }) export class DsDynamicRelationGroupComponent extends DynamicFormControlComponent implements OnDestroy, OnInit { @Input() formId: string; @Input() group: FormGroup; @Input() model: DynamicRelationGroupModel; @Output() blur: EventEmitter<any> = new EventEmitter<any>(); @Output() change: EventEmitter<any> = new EventEmitter<any>(); @Output() focus: EventEmitter<any> = new EventEmitter<any>(); public chips: Chips; public formCollapsed = observableOf(false); public formModel: DynamicFormControlModel[]; public editMode = false; private selectedChipItem: ChipsItem; private subs: Subscription[] = []; @ViewChild('formRef') private formRef: FormComponent; constructor(private vocabularyService: VocabularyService, private formBuilderService: FormBuilderService, private formService: FormService, private cdr: ChangeDetectorRef, protected layoutService: DynamicFormLayoutService, protected validationService: DynamicFormValidationService ) { super(layoutService, validationService); } ngOnInit() { const config = { rows: this.model.formConfiguration } as SubmissionFormsModel; if (!this.model.isEmpty()) { this.formCollapsed = observableOf(true); } this.model.valueChanges.subscribe((value: any[]) => { if ((isNotEmpty(value) && !(value.length === 1 && hasOnlyEmptyProperties(value[0])))) { this.collapseForm(); } else { this.expandForm(); } }); this.formId = this.formService.getUniqueId(this.model.id); this.formModel = this.formBuilderService.modelFromConfiguration( this.model.submissionId, config, this.model.scopeUUID, {}, this.model.submissionScope, this.model.readOnly); this.initChipsFromModelValue(); } isMandatoryFieldEmpty() { let res = true; this.formModel.forEach((row) => { const modelRow = row as DynamicFormGroupModel; modelRow.group.forEach((model: DynamicInputModel) => { if (model.name === this.model.mandatoryField) { res = model.value == null; return; } }); }); return res; } onBlur(event) { this.blur.emit(); } onChipSelected(event) { this.expandForm(); this.selectedChipItem = this.chips.getChipByIndex(event); this.formModel.forEach((row) => { const modelRow = row as DynamicFormGroupModel; modelRow.group.forEach((model: DynamicInputModel) => { const value = (this.selectedChipItem.item[model.name] === PLACEHOLDER_PARENT_METADATA || this.selectedChipItem.item[model.name].value === PLACEHOLDER_PARENT_METADATA) ? null : this.selectedChipItem.item[model.name]; const nextValue = (this.formBuilderService.isInputModel(model) && isNotNull(value) && (typeof value !== 'string')) ? value.value : value; model.value = nextValue; }); }); this.editMode = true; } onFocus(event) { this.focus.emit(event); } collapseForm() { this.formCollapsed = observableOf(true); this.clear(); } expandForm() { this.formCollapsed = observableOf(false); } clear() { if (this.editMode) { this.selectedChipItem.editMode = false; this.selectedChipItem = null; this.editMode = false; } this.resetForm(); if (!this.model.isEmpty()) { this.formCollapsed = observableOf(true); } } save() { if (this.editMode) { this.modifyChip(); } else { this.addToChips(); } } delete() { this.chips.remove(this.selectedChipItem); this.clear(); } ngOnDestroy(): void { this.subs .filter((sub) => hasValue(sub)) .forEach((sub) => sub.unsubscribe()); } private addToChips() { if (!this.formRef.formGroup.valid) { this.formService.validateAllFormFields(this.formRef.formGroup); return; } // Item to add if (!this.isMandatoryFieldEmpty()) { const item = this.buildChipItem(); this.chips.add(item); this.resetForm(); } } private modifyChip() { if (!this.formRef.formGroup.valid) { this.formService.validateAllFormFields(this.formRef.formGroup); return; } if (!this.isMandatoryFieldEmpty()) { const item = this.buildChipItem(); this.chips.update(this.selectedChipItem.id, item); this.resetForm(); this.cdr.detectChanges(); } } private buildChipItem() { const item = Object.create({}); this.formModel.forEach((row) => { const modelRow = row as DynamicFormGroupModel; modelRow.group.forEach((control: DynamicInputModel) => { item[control.name] = control.value || PLACEHOLDER_PARENT_METADATA; }); }); return item; } private initChipsFromModelValue() { let initChipsValue$: Observable<any[]>; if (this.model.isEmpty()) { this.initChips([]); } else { initChipsValue$ = observableOf(this.model.value as any[]); // If authority this.subs.push(initChipsValue$.pipe( mergeMap((valueModel) => { const returnList: Observable<any>[] = []; valueModel.forEach((valueObj) => { const returnObj = Object.keys(valueObj).map((fieldName) => { let return$: Observable<any>; if (isObject(valueObj[fieldName]) && valueObj[fieldName].hasAuthority() && isNotEmpty(valueObj[fieldName].authority)) { const fieldId = fieldName.replace(/\./g, '_'); const model = this.formBuilderService.findById(fieldId, this.formModel); return$ = this.vocabularyService.findEntryDetailById( valueObj[fieldName].authority, (model as any).vocabularyOptions.name ).pipe( getFirstSucceededRemoteDataPayload(), map((entryDetail: VocabularyEntryDetail) => Object.assign( new FormFieldMetadataValueObject(), valueObj[fieldName], { otherInformation: entryDetail.otherInformation }) )); } else { return$ = observableOf(valueObj[fieldName]); } return return$.pipe(map((entry) => ({ [fieldName]: entry }))); }); returnList.push(combineLatest(returnObj)); }); return returnList; }), mergeMap((valueListObj: Observable<any>, index: number) => { return valueListObj.pipe( map((valueObj: any) => ({ index: index, value: valueObj.reduce( (acc: any, value: any) => Object.assign({}, acc, value) ) }) ) ); }), scan((acc: any[], valueObj: any) => { if (acc.length === 0) { acc.push(valueObj.value); } else { acc.splice(valueObj.index, 0, valueObj.value); } return acc; }, []), filter((modelValues: any[]) => (this.model.value as any[]).length === modelValues.length) ).subscribe((modelValue) => { this.model.value = modelValue; this.initChips(modelValue); this.cdr.markForCheck(); })); } } private initChips(initChipsValue) { this.chips = new Chips( initChipsValue, 'value', this.model.mandatoryField, environment.submission.icons.metadata); this.subs.push( this.chips.chipsItems .subscribe(() => { const items = this.chips.getChipsItems(); // Does not emit change if model value is equal to the current value if (!isEqual(items, this.model.value)) { if (!(isEmpty(items) && this.model.isEmpty())) { this.model.value = items; this.change.emit(); } } }), ); } private resetForm() { if (this.formRef) { this.formService.resetForm(this.formRef.formGroup, this.formModel, this.formId); } } }
the_stack
import { IBoxPlotData, IAdvancedBoxPlotData, round } from '../internal'; import { NumberColumn, IBoxPlotColumn, INumberColumn, isBoxPlotColumn, Column, IDataRow, isNumberColumn, isMapAbleColumn, IOrderedGroup, } from '../model'; import { BOX_PLOT, CANVAS_HEIGHT, DOT, cssClass } from '../styles'; import { colorOf } from './impose'; import { IRenderContext, ERenderMode, ICellRendererFactory, IImposer, ICellRenderer, IGroupCellRenderer, ISummaryRenderer, } from './interfaces'; import { renderMissingCanvas } from './missing'; import { tasksAll } from '../provider'; const BOXPLOT = `<div title=""> <div class="${cssClass('boxplot-whisker')}"> <div class="${cssClass('boxplot-box')}"></div> <div class="${cssClass('boxplot-median')}"></div> <div class="${cssClass('boxplot-mean')}"></div> </div> </div>`; const MAPPED_BOXPLOT = `<div title=""> <div class="${cssClass('boxplot-whisker')}"> <div class="${cssClass('boxplot-box')}"></div> <div class="${cssClass('boxplot-median')}"></div> <div class="${cssClass('boxplot-mean')}"></div> </div> <span class="${cssClass('mapping-hint')}"></span><span class="${cssClass('mapping-hint')}"></span> </div>`; /** @internal */ export function computeLabel(col: INumberColumn, v: IBoxPlotData | IAdvancedBoxPlotData) { if (v == null) { return ''; } const f = col.getNumberFormat(); const mean = (v as IAdvancedBoxPlotData).mean != null ? `mean = ${f((v as IAdvancedBoxPlotData).mean)} (dashed line)\n` : ''; return `min = ${f(v.min)}\nq1 = ${f(v.q1)}\nmedian = ${f(v.median)}\n${mean}q3 = ${f(v.q3)}\nmax = ${f(v.max)}`; } export default class BoxplotCellRenderer implements ICellRendererFactory { readonly title: string = 'Box Plot'; canRender(col: Column, mode: ERenderMode): boolean { return (isBoxPlotColumn(col) && mode === ERenderMode.CELL) || (isNumberColumn(col) && mode !== ERenderMode.CELL); } create(col: IBoxPlotColumn, context: IRenderContext, imposer?: IImposer): ICellRenderer { const sortMethod = col.getSortMethod() as keyof IBoxPlotData; const sortedByMe = col.isSortedByMe().asc !== undefined; const width = context.colWidth(col); return { template: BOXPLOT, update: (n: HTMLElement, d: IDataRow) => { const data = col.getBoxPlotData(d); n.classList.toggle(cssClass('missing'), !data); if (!data) { return; } const label = col.getRawBoxPlotData(d)!; renderDOMBoxPlot(col, n, data!, label, sortedByMe ? sortMethod : '', colorOf(col, d, imposer)); }, render: (ctx: CanvasRenderingContext2D, d: IDataRow) => { if (renderMissingCanvas(ctx, col, d, width)) { return; } // Rectangle const data = col.getBoxPlotData(d); if (!data) { return; } const scaled = { min: data.min * width, median: data.median * width, mean: (data as IAdvancedBoxPlotData).mean != null ? (data as IAdvancedBoxPlotData).mean * width : undefined, q1: data.q1 * width, q3: data.q3 * width, max: data.max * width, outlier: data.outlier ? data.outlier.map((d) => d * width) : undefined, whiskerLow: data.whiskerLow != null ? data.whiskerLow * width : undefined, whiskerHigh: data.whiskerHigh != null ? data.whiskerHigh * width : undefined, }; renderBoxPlot(ctx, scaled, sortedByMe ? sortMethod : '', colorOf(col, d, imposer), CANVAS_HEIGHT, 0); }, }; } createGroup(col: INumberColumn, context: IRenderContext, imposer?: IImposer): IGroupCellRenderer { const sort = col instanceof NumberColumn && col.isGroupSortedByMe().asc !== undefined ? col.getSortMethod() : ''; return { template: BOXPLOT, update: (n: HTMLElement, group: IOrderedGroup) => { return tasksAll([ context.tasks.groupBoxPlotStats(col, group, false), context.tasks.groupBoxPlotStats(col, group, true), ]).then((data) => { if (typeof data === 'symbol') { return; } // render const isMissing = data == null || data[0] == null || data[0].group.count === 0 || data[0].group.count === data[0].group.missing; n.classList.toggle(cssClass('missing'), isMissing); if (isMissing) { return; } renderDOMBoxPlot(col, n, data[0].group, data[1].group, sort, colorOf(col, null, imposer)); }); }, }; } createSummary( col: INumberColumn, context: IRenderContext, _interactive: boolean, imposer?: IImposer ): ISummaryRenderer { return { template: isMapAbleColumn(col) ? MAPPED_BOXPLOT : BOXPLOT, update: (n: HTMLElement) => { return tasksAll([ context.tasks.summaryBoxPlotStats(col, false), context.tasks.summaryBoxPlotStats(col, true), ]).then((data) => { if (typeof data === 'symbol') { return; } const isMissing = data == null || data[0] == null || data[0].summary.count === 0 || data[0].summary.count === data[0].summary.missing; n.classList.toggle(cssClass('missing'), isMissing); if (isMissing) { return; } const mappedSummary = data[0].summary; const rawSummary = data[1].summary; const sort = col instanceof NumberColumn && col.isGroupSortedByMe().asc !== undefined ? col.getSortMethod() : ''; if (isMapAbleColumn(col)) { const range = col.getRange(); Array.from(n.getElementsByTagName('span')).forEach((d: HTMLElement, i) => (d.textContent = range[i])); } renderDOMBoxPlot(col, n, mappedSummary, rawSummary, sort, colorOf(col, null, imposer), isMapAbleColumn(col)); }); }, }; } } function renderDOMBoxPlot( col: INumberColumn, n: HTMLElement, data: IBoxPlotData | IAdvancedBoxPlotData, label: IBoxPlotData | IAdvancedBoxPlotData, sort: string, color: string | null, hasRange = false ) { n.title = computeLabel(col, label); const whiskers = n.firstElementChild as HTMLElement; const box = whiskers.firstElementChild as HTMLElement; const median = box.nextElementSibling as HTMLElement; const mean = whiskers.lastElementChild as HTMLElement; const leftWhisker = data.whiskerLow != null ? data.whiskerLow : Math.max(data.q1 - 1.5 * (data.q3 - data.q1), data.min); const rightWhisker = data.whiskerHigh != null ? data.whiskerHigh : Math.min(data.q3 + 1.5 * (data.q3 - data.q1), data.max); whiskers.style.left = `${round(leftWhisker * 100, 2)}%`; const range = rightWhisker - leftWhisker; whiskers.style.width = `${round(range * 100, 2)}%`; //relative within the whiskers box.style.left = `${round(((data.q1 - leftWhisker) / range) * 100, 2)}%`; box.style.width = `${round(((data.q3 - data.q1) / range) * 100, 2)}%`; box.style.backgroundColor = color; //relative within the whiskers median.style.left = `${round(((data.median - leftWhisker) / range) * 100, 2)}%`; if ((data as IAdvancedBoxPlotData).mean != null) { mean.style.left = `${round((((data as IAdvancedBoxPlotData).mean - leftWhisker) / range) * 100, 2)}%`; mean.style.display = null; } else { mean.style.display = 'none'; } // match lengths const outliers = Array.from(n.children).slice(1, hasRange ? -2 : undefined) as HTMLElement[]; const numOutliers = data.outlier ? data.outlier.length : 0; outliers.splice(numOutliers, outliers.length - numOutliers).forEach((v) => v.remove()); whiskers.dataset.sort = sort; if (!data.outlier || numOutliers === 0) { return; } for (let i = outliers.length; i < numOutliers; ++i) { const p = n.ownerDocument!.createElement('div'); p.classList.add(cssClass('boxplot-outlier')); outliers.unshift(p); whiskers.insertAdjacentElement('afterend', p); } data.outlier.forEach((v, i) => { delete outliers[i].dataset.sort; outliers[i].style.left = `${round(v * 100, 2)}%`; }); if (sort === 'min' && data.outlier[0] <= leftWhisker) { // first outliers is the min whiskers.dataset.sort = ''; outliers[0].dataset.sort = 'min'; if (outliers.length > 1) { // append at the end of the DOM to be on top outliers[outliers.length - 1].insertAdjacentElement('afterend', outliers[0]); } } else if (sort === 'max' && data.outlier[outliers.length - 1] >= rightWhisker) { // last outlier is the max whiskers.dataset.sort = ''; outliers[outliers.length - 1].dataset.sort = 'max'; } } function renderBoxPlot( ctx: CanvasRenderingContext2D, box: IBoxPlotData, sort: string, color: string | null, height: number, topPadding: number ) { const left = box.whiskerLow != null ? box.whiskerLow : Math.max(box.q1 - 1.5 * (box.q3 - box.q1), box.min); const right = box.whiskerHigh != null ? box.whiskerHigh : Math.min(box.q3 + 1.5 * (box.q3 - box.q1), box.max); ctx.fillStyle = color || BOX_PLOT.box; ctx.strokeStyle = BOX_PLOT.stroke; ctx.beginPath(); ctx.rect(box.q1, 0, box.q3 - box.q1, height); ctx.fill(); ctx.stroke(); //Line const bottomPos = height - topPadding; const middlePos = height / 2; ctx.beginPath(); ctx.moveTo(left, middlePos); ctx.lineTo(box.q1, middlePos); ctx.moveTo(left, topPadding); ctx.lineTo(left, bottomPos); ctx.moveTo(box.median, 0); ctx.lineTo(box.median, height); ctx.moveTo(box.q3, middlePos); ctx.lineTo(right, middlePos); ctx.moveTo(right, topPadding); ctx.lineTo(right, bottomPos); ctx.stroke(); ctx.fill(); if (sort !== '') { ctx.strokeStyle = BOX_PLOT.sort; ctx.beginPath(); ctx.moveTo(box[sort as keyof IBoxPlotData] as number, topPadding); ctx.lineTo(box[sort as keyof IBoxPlotData] as number, height - topPadding); ctx.stroke(); ctx.fill(); } if (!box.outlier) { return; } ctx.fillStyle = BOX_PLOT.outlier; box.outlier.forEach((v) => { // currently dots with 3px ctx.fillRect(Math.max(v - DOT.size / 2, 0), middlePos - DOT.size / 2, DOT.size, DOT.size); }); }
the_stack
import { CompilationData } from '../template/compiler-types'; import { CompilationError, ResolvedScript, } from '../template/language/language-types'; /** * The partial transaction context which is shared between all of the inputs in * a transaction. */ export interface TransactionContextSharedCommon { /** * A time or block height at which the transaction is considered valid (and * can be added to the block chain). This allows signers to create time-locked * transactions which may only become valid in the future. */ readonly locktime: number; /** * A.K.A. the serialization for `hashPrevouts` * * The signing serialization of all input outpoints. (See BIP143 or Bitcoin * Cash's Replay Protected Sighash spec for details.) */ readonly transactionOutpoints: Uint8Array; /* * A.K.A. the serialization for `hashOutputs` with `SIGHASH_ALL` * * The signing serialization of output amounts and locking scripts. (See * BIP143 or Bitcoin Cash's Replay Protected Sighash spec for details.) */ readonly transactionOutputs: Uint8Array; /* * A.K.A. the serialization for `hashSequence` * * The signing serialization of all input sequence numbers. (See BIP143 or * Bitcoin Cash's Replay Protected Sighash spec for details.) */ readonly transactionSequenceNumbers: Uint8Array; readonly version: number; } /** * The complete transaction context in which a single transaction input exists. */ export interface TransactionContextCommon extends TransactionContextSharedCommon { /* * A.K.A. the serialization for `hashOutputs` with `SIGHASH_SINGLE` * * The signing serialization of the output at the same index as this input. If * this input's index is larger than the total number of outputs (such that * there is no corresponding output), this should be `undefined`. (See BIP143 * or Bitcoin Cash's Replay Protected Sighash spec for details.) */ readonly correspondingOutput?: Uint8Array; /** * The index (within the previous transaction) of the outpoint being spent by * this input. */ readonly outpointIndex: number; /** * The hash/ID of the transaction from which the outpoint being spent by this * input originated. */ readonly outpointTransactionHash: Uint8Array; /** * The 8-byte `Uint64LE`-encoded value of the outpoint in satoshis (see * `bigIntToBinUint64LE`). */ readonly outputValue: Uint8Array; /** * The `sequenceNumber` associated with the input being validated. See * `Input.sequenceNumber` for details. */ readonly sequenceNumber: number; } /** * Data type representing a Transaction Input. */ export interface Input<Bytecode = Uint8Array, HashRepresentation = Uint8Array> { /** * The index of the output in the transaction from which this input is spent. * * @remarks * An "outpoint" is a reference (A.K.A. "pointer") to a specific output in a * previous transaction. */ outpointIndex: number; /** * The hash of the raw transaction from which this input is spent in * big-endian byte order. This is the byte order typically seen in block * explorers and user interfaces (as opposed to little-endian byte order, * which is used in standard P2P network messages). * * A.K.A. `Transaction ID` * * @remarks * An "outpoint" is a reference (A.K.A. "pointer") to a specific output in a * previous transaction. * * Encoded raw bitcoin transactions serialize this value in little-endian byte * order. However, it is more common to use big-endian byte order when * displaying transaction hashes. (In part because the SHA-256 specification * defines its output as big-endian, so this byte order is output by most * cryptographic libraries.) */ outpointTransactionHash: HashRepresentation; /** * The positive, 32-bit unsigned integer used as the "sequence number" for * this input. * * A sequence number is a complex bitfield which can encode several properties * about an input: * - **sequence age support** – whether or not the input can use * `OP_CHECKSEQUENCEVERIFY`, and the minimum number of blocks or length of * time which has passed since this input's source transaction was mined (up * to approximately 1 year). * - **locktime support** – whether or not the input can use * `OP_CHECKLOCKTIMEVERIFY` * * **Sequence Age Support** * * Sequence number age is enforced by mining consensus – a transaction is * invalid until it has "aged" such that all outputs referenced by its * age-enabled inputs are at least as old as claimed by their respective * sequence numbers. * * This allows sequence numbers to function as a "relative locktime" for each * input: a `lockingBytecode` can use the `OP_CHECKSEQUENCEVERIFY` operation * to verify that the funds being spent have been "locked" for a minimum * required amount of time (or block count). This can be used in protocols * which require a reliable "proof-of-publication", like escrow, time-delayed * withdrawals, and various payment channel protocols. * * Sequence age support is enabled unless the "disable bit" – the most * significant bit – is set (i.e. the sequence number is less than * `(1 << 31) >>> 0`/`0b10000000000000000000000000000000`/`2147483648`). * * If sequence age is enabled, the "type bit" – the most significant bit in * the second-most significant byte * (`1 << 22`/`0b1000000000000000000000`/`2097152`) – indicates the unit type * of the specified age: * - if set, the age is in units of `512` seconds (using Median Time-Past) * - if not set, the age is a number of blocks * * The least significant 16 bits specify the age (i.e. * `age = sequenceNumber & 0x0000ffff`). This makes the maximum age either * `65535` blocks (about 1.25 years) or `33553920` seconds (about 1.06 years). * * **Locktime Support** * * Locktime support is disabled for an input if the sequence number is exactly * `0xffffffff` (`4294967295`). Because this value requires the "disable bit" * to be set, disabling locktime support also disables sequence age support. * * With locktime support disabled, if either `OP_CHECKLOCKTIMEVERIFY` or * `OP_CHECKSEQUENCEVERIFY` are encountered during the validation of * `unlockingBytecode`, an error is produced, and the transaction is invalid. * * @remarks * The term "sequence number" was the name given to this field in the Satoshi * implementation of the bitcoin transaction format. The field was originally * intended for use in a multi-party signing protocol where parties updated * the "sequence number" to indicate to miners that this input should replace * a previously-signed input in an existing, not-yet-mined transaction. The * original use-case was not completed and relied on behavior which can not be * enforced by mining consensus, so the field was mostly-unused until it was * repurposed by BIP68 in block `419328`. See BIP68, BIP112, and BIP113 for * details. */ sequenceNumber: number; /** * The bytecode used to unlock a transaction output. To spend an output, * unlocking bytecode must be included in a transaction input which – when * evaluated in the authentication virtual machine with the locking bytecode – * completes in valid state. * * A.K.A. `scriptSig` or "unlocking script" */ unlockingBytecode: Bytecode; } /** * Data type representing a Transaction Output. * * @typeParam Bytecode - the type of `lockingBytecode` - this can be configured * to allow for defining compilation directives * @typeParam Amount - the type of `satoshis` */ export interface Output<Bytecode = Uint8Array, Amount = Uint8Array> { /** * The bytecode used to encumber this transaction output. To spend the output, * unlocking bytecode must be included in a transaction input which – when * evaluated before the locking bytecode – completes in a valid state. * * A.K.A. `scriptPubKey` or "locking script" */ readonly lockingBytecode: Bytecode; /** * The 8-byte `Uint64LE`-encoded value of the output in satoshis, the smallest * unit of bitcoin. * * There are 100 satoshis in a bit, and 100,000,000 satoshis in a bitcoin. * * This value could be defined using a `number`, as `Number.MAX_SAFE_INTEGER` * (`9007199254740991`) is about 4 times larger than the maximum number of * satoshis which should ever exist. I.e. even if all satoshis were * consolidated into a single output, the transaction spending this output * could still be defined with a numeric `satoshis` value. * * However, because the encoded output format for version 1 and 2 transactions * (used in both transaction encoding and signing serialization) uses a 64-bit * unsigned, little-endian integer to serialize `satoshis`, this property is * encoded in the same format, allowing it to cover the full possible range. * * This is useful for encoding values using schemes for fractional satoshis * (for which no finalized specification yet exists) or for encoding * intentionally excessive values. For example, `invalidSatoshis` * (`0xffffffffffffffff` - the maximum uint64 value) is a clearly impossible * `satoshis` value for version 1 and 2 transactions. As such, this value can * safely by used by transaction signing and verification implementations to * ensure that an otherwise properly-signed transaction can never be included * n the blockchain, e.g. for transaction size estimation or off-chain Bitauth * signatures. * * To convert this value to and from a `BigInt` use `bigIntToBinUint64LE` and * `binToBigIntUint64LE`, respectively. */ readonly satoshis: Amount; } /** * The maximum uint64 value – an impossibly large, intentionally invalid value * for `satoshis`. See `Transaction.satoshis` for details. */ // prettier-ignore // eslint-disable-next-line @typescript-eslint/no-magic-numbers export const invalidSatoshis = Uint8Array.from([255, 255, 255, 255, 255, 255, 255, 255]); /** * Data type representing a transaction. */ export interface Transaction<InputType = Input, OutputType = Output> { /** * An array of inputs included in this transaction. * * Input order is critical to signing serializations, and reordering inputs * may invalidate transactions. */ inputs: InputType[]; /** * The locktime at which this transaction is considered valid – a positive * integer from `0` to a maximum of `4294967295`. * * Locktime can be provided as either a timestamp or a block height. Values * less than `500000000` are understood to be a block height (the current * block number in the chain, beginning from block `0`). Values greater than * or equal to `500000000` are understood to be a UNIX timestamp. * * For validating timestamp values, the median timestamp of the last 11 blocks * (Median Time-Past) is used. The precise behavior is defined in BIP113. * * If the `sequenceNumber` of every transaction input is set to `0xffffffff` * (`4294967295`), locktime is disabled, and the transaction may be added to a * block even if the specified locktime has not yet been reached. When * locktime is disabled, if an `OP_CHECKLOCKTIMEVERIFY` operation is * encountered during the verification of any input, an error is produced, and * the transaction is invalid. * * @remarks * There is a subtle difference in how `locktime` is disabled for a * transaction and how it is "disabled" for a single input: `locktime` is only * disabled for a transaction if every input has a sequence number of * `0xffffffff`; however, within each input, if the sequence number is set to * `0xffffffff`, locktime is disabled for that input (and * `OP_CHECKLOCKTIMEVERIFY` operations will error if encountered). * * This difference is a minor virtual machine optimization – it allows inputs * to be properly validated without requiring the virtual machine to check the * sequence number of every other input (only that of the current input). * * This is inconsequential for valid transactions, since any transaction which * disables `locktime` must have disabled locktime for all of its inputs; * `OP_CHECKLOCKTIMEVERIFY` is always properly enforced. However, because an * input can individually "disable locktime" without the full transaction * *actually disabling locktime*, it is possible that a carefully-crafted * transaction may fail to verify because "locktime is disabled" for the input * – even if locktime is actually enforced on the transaction level. */ locktime: number; /** * An array of outputs included in this transaction. * * Output order is critical to signing serializations, and reordering outputs * may invalidate transactions. */ outputs: OutputType[]; /** * The version of this transaction – a positive integer from `0` to a maximum * of `4294967295`. Since BIP68, most transactions use a version of `2`. */ version: number; } export interface CompilationDirectiveLocking< CompilerType, CompilationDataType > { /** * The `Compiler` with which to generate bytecode. */ compiler: CompilerType; /** * The `CompilationData` required to compile the specified script. */ data?: CompilationDataType; /** * The script ID to compile. */ script: string; } export interface CompilationDirectiveUnlocking< CompilerType, CompilationDataType > extends CompilationDirectiveLocking<CompilerType, CompilationDataType> { /** * The `satoshis` value of the `Output` being spent by this input. Required * for use in signing serializations. */ satoshis: Output['satoshis']; } export interface CompilationDirectiveUnlockingEstimate< CompilerType, CompilationDataType > extends CompilationDirectiveUnlocking<CompilerType, CompilationDataType> { /** * The scenario ID which can be used to estimate the final size of this * unlocking script. This is required when using fee estimation. */ estimate: string; } /** * An input which may optionally use a `CompilationDirectiveUnlocking` as its * `unlockingBytecode` property. During compilation, the final `lockingBytecode` * will be generated from this directive. * * If `RequireEstimate` is `true`, all input directives must include an * `estimate` scenario ID. See `estimateTransaction` for details. */ export type InputTemplate< CompilerType, RequireEstimate = false, CompilationDataType = CompilationData<never> > = Input< | (RequireEstimate extends true ? CompilationDirectiveUnlockingEstimate<CompilerType, CompilationDataType> : CompilationDirectiveUnlocking<CompilerType, CompilationDataType>) | Uint8Array >; /** * An output which may optionally use a `CompilationDirectiveLocking` as its * `lockingBytecode` property. During compilation, the final `lockingBytecode` * will be generated from this directive. * * If `EnableFeeEstimation` is `true`, the `satoshis` value may also be * `undefined` (as estimated transactions always set output values to * `invalidSatoshis`). */ export type OutputTemplate< CompilerType, EnableFeeEstimation = false, CompilationDataType = CompilationData<never> > = Output< CompilationDirectiveLocking<CompilerType, CompilationDataType> | Uint8Array, EnableFeeEstimation extends true ? Uint8Array | undefined : Uint8Array >; /** * A `Transaction` which may optionally use compilation directives in place of * `lockingBytecode` and `unlockingBytecode` instances. During transaction * generation, these directives will be generated from these directives. * * If `EnableFeeEstimation` is `true`, all input directives must include an * `estimate` scenario ID, and the `satoshis` value of each output may also be * `undefined` (as estimated transactions always set output values to * `invalidSatoshis`). */ export type TransactionTemplate< CompilerType, EnableFeeEstimation = false, CompilationDataType = CompilationData<never> > = Transaction< InputTemplate<CompilerType, EnableFeeEstimation, CompilationDataType>, OutputTemplate<CompilerType, EnableFeeEstimation, CompilationDataType> >; /** * A transaction template where all output amounts are provided (i.e. the values * of each "change" output has been decided). To estimate the final transaction * size given a transaction template (and from it, the required transaction * fee), see `estimateTransaction`. */ export type TransactionTemplateFixed<CompilerType> = TransactionTemplate< CompilerType >; /** * A transaction template which enables fee estimation. The template must * include an `inputSatoshis` value (the total satoshi value of all * transaction inputs); all unlocking compilation directives must provide an * `estimate` scenario ID which is used to estimate the size of the resulting * unlocking bytecode; and the `satoshis` value of outputs is optional (all * satoshi values will be set to `impossibleSatoshis` in the estimated * transaction). */ export type TransactionTemplateEstimated<CompilerType> = TransactionTemplate< CompilerType, true > & { /** * The total satoshi value of all transaction inputs. This is required when * using fee estimation, and is used to calculate the appropriate value of * change outputs (outputs with `satoshis` set to `undefined`). */ inputSatoshis: number; }; /** * An error resulting from unsuccessful bytecode generation. Includes the * generation type (`locking` or `unlocking`), and the output or input index */ export interface BytecodeGenerationErrorBase { /** * The type of bytecode that was being generated when this error occurred. */ type: 'locking' | 'unlocking'; /** * The input or output index for which this bytecode was being generated. (To ) */ index: number; /** * The stage of generation at which this error occurred – the `outputs` stage * must complete before the `inputs` can begin. */ // stage: 'outputs' | 'inputs'; /** * If the error occurred after the `parse` stage, the resolved script is * provided for analysis or processing (e.g. `getResolvedBytecode`). */ resolved?: ResolvedScript; /** * The compilation errors which occurred while generating this bytecode. */ errors: CompilationError[]; } export interface BytecodeGenerationErrorLocking extends BytecodeGenerationErrorBase { type: 'locking'; } export interface BytecodeGenerationErrorUnlocking extends BytecodeGenerationErrorBase { type: 'unlocking'; } export interface BytecodeGenerationCompletionBase { /** * If `output`, this bytecode was generated for the output at `index` (a * `lockingBytecode`). If `input`, the bytecode was generated for the input at * `index` (an `unlockingBytecode`). */ type: 'output' | 'input'; /** * The index of the input or output for which this bytecode was generated. */ index: number; } export interface BytecodeGenerationCompletionInput extends BytecodeGenerationCompletionBase { type: 'input'; /** * The successfully generated Input. */ input: Input; } export interface BytecodeGenerationCompletionOutput extends BytecodeGenerationCompletionBase { type: 'output'; /** * The successfully generated Output. */ output: Output; } /** * A successfully generated `lockingBytecode` (for an output) or * `unlockingBytecode` (for an input). Because this bytecode generation was * successful, the associated compilation directive in the transaction template * can be replaced with this result for subsequent compilations. For example, if * most inputs were successfully compiled, but some inputs require keys held by * another entity, the transaction template can be updated such that only the * final inputs contain compilation directives. */ export type BytecodeGenerationCompletion = | BytecodeGenerationCompletionOutput | BytecodeGenerationCompletionInput; export interface TransactionGenerationSuccess { success: true; transaction: Transaction; } export type TransactionGenerationError = | { success: false; completions: BytecodeGenerationCompletionOutput[]; errors: BytecodeGenerationErrorLocking[]; /** * Error(s) occurred at the `output` stage of compilation, so the `input` * stage never began. */ stage: 'outputs'; } | { success: false; completions: BytecodeGenerationCompletionInput[]; errors: BytecodeGenerationErrorUnlocking[]; /** * Error(s) occurred at the `input` stage of compilation, meaning the * `output` stage completed successfully. */ stage: 'inputs'; }; export type TransactionGenerationAttempt = | TransactionGenerationSuccess | TransactionGenerationError;
the_stack
import { PromiseFsClient } from 'isomorphic-git'; import path from 'path'; import Stat from './stat'; import { SystemError } from './system-error'; interface FSFile { readonly type: 'file'; readonly ino: number; readonly mtimeMs: number; readonly name: string; readonly path: string; contents: string; } interface FSLink { readonly type: 'symlink'; readonly ino: number; readonly mtimeMs: number; readonly name: string; readonly path: string; readonly linkTo: string; } interface FSDir { readonly type: 'dir'; readonly ino: number; readonly mtimeMs: number; readonly name: string; readonly path: string; readonly children: (FSFile | FSDir | FSLink)[]; } type FSEntry = FSDir | FSFile | FSLink; export class MemClient { __fs: FSEntry; __ino: 0; static createClient(): PromiseFsClient { return { promises: new MemClient(), }; } constructor() { this.__ino = 0; this.__fs = { type: 'dir', path: path.normalize('/'), name: '', children: [], ino: this.__ino, mtimeMs: Date.now(), }; } async tree(baseDir = '/') { baseDir = path.normalize(baseDir); const next = async (dir: string, toPrint: string) => { const entry = this._find(dir); if (!entry) { return toPrint; } const indent = new Array((dir.match(/\//g) || []).length).join('| '); if (entry.type === 'dir') { if (entry.path !== baseDir) { toPrint += `${indent}${entry.name}/\n`; } for (const name of await this.readdir(dir)) { toPrint = await next(path.join(dir, name), toPrint); } } else { toPrint += `${indent}${entry.name}\n`; } return toPrint; }; console.log(await next(baseDir, '')); } async readFile( filePath: string, options: BufferEncoding | { encoding?: BufferEncoding } = {}, ) { filePath = path.normalize(filePath); if (typeof options === 'string') { options = { encoding: options, }; } const encoding = options ? options.encoding : null; const entry = this._assertFile(filePath); const raw = Buffer.from(entry.contents, 'base64'); if (encoding) { return raw.toString(encoding); } else { return raw; } } async writeFile( filePath: string, data: Buffer | string, options: BufferEncoding | { encoding?: BufferEncoding; flag?: string } = {}, ) { filePath = path.normalize(filePath); if (typeof options === 'string') { options = { encoding: options, }; } const flag = options && options.flag ? options.flag : 'w'; const encoding = options && options.encoding ? options.encoding : 'utf8'; // Make sure file doesn't exist for "x" flags if (flag[1] === 'x') { await this._assertDoesNotExist(filePath); } const dirEntry: FSDir = this._assertDir(path.dirname(filePath)); let file: FSEntry | null = this._find(filePath); if (file) { file = this._assertFileEntry(file); } else { const name = path.basename(filePath); file = { name, type: 'file', ino: this.__ino++, mtimeMs: Date.now(), contents: '', path: filePath, }; dirEntry.children.push(file); } const dataBuff: Buffer = data instanceof Buffer ? data : Buffer.from(data, encoding); let newContents = Buffer.alloc(0); if (flag[0] === 'w') { newContents = dataBuff; } else if (flag[0] === 'a') { const contentsBuff: Buffer = Buffer.from(file.contents, 'base64'); newContents = Buffer.concat([contentsBuff, dataBuff]); } else { throw new SystemError({ code: 'EBADF', errno: -9, message: 'EBADF: bad file descriptor, write', path: filePath, syscall: 'write', }); } file.contents = newContents.toString('base64'); return Promise.resolve(); } async unlink(filePath: string) { filePath = path.normalize(filePath); this._remove(this._assertFile(filePath)); } async readdir(basePath: string) { basePath = path.normalize(basePath); const entry = this._assertDir(basePath); const names = entry.children.map(c => c.name); names.sort(); return names; } async mkdir(dirPath: string, options?: { recursive?: boolean }) { dirPath = path.normalize(dirPath); const doRecursive = (options || {}).recursive || false; // If not recursive, ensure parent exists if (!doRecursive) { this._assertDir(path.dirname(dirPath)); } const pathSegments = dirPath.split(path.sep).filter(s => s !== ''); // Recurse over all sub paths, ensure they are all directories, // create them if they don't exist let currentPath = '/'; for (const pathSegment of pathSegments) { const dirEntry = this._assertDir(currentPath); const nextPath = path.join(currentPath, pathSegment); // Create dir if it doesn't exist yet if (!dirEntry.children.find(child => child.name === pathSegment)) { dirEntry.children.push({ type: 'dir', ino: this.__ino++, mtimeMs: Date.now(), name: pathSegment, path: nextPath, children: [], }); } currentPath = nextPath; } } async rmdir(dirPath: string) { dirPath = path.normalize(dirPath); const dirEntry = this._assertDir(dirPath); if (dirEntry.children.length > 0) { throw new SystemError({ code: 'ENOTEMPTY', errno: -66, message: `ENOTEMPTY: directory not empty, rmdir '${dirPath}'`, path: dirPath, syscall: 'rmdir', }); } this._remove(dirEntry); } async stat(filePath: string) { filePath = path.normalize(filePath); return this._statEntry(this._assertExists(filePath)); } async lstat(filePath: string) { filePath = path.normalize(filePath); const linkEntry = this._assertExists(filePath); return this._statEntry(this._resolveLinks(linkEntry)); } async readlink(filePath: string) { filePath = path.normalize(filePath); const linkEntry = this._assertSymlink(filePath); return linkEntry.linkTo; } async symlink(target: string, filePath: string) { filePath = path.normalize(filePath); // Make sure we don't already have one there // TODO: Check what to do in this case (might be wrong) this._assertDoesNotExist(filePath); this._assertExists(target); const parentEntry = this._assertDir(path.dirname(filePath)); parentEntry.children.push({ type: 'symlink', ino: this.__ino++, mtimeMs: Date.now(), name: path.basename(filePath), path: filePath, linkTo: target, }); } _statEntry(entry: FSEntry) { return new Stat({ type: entry.type, mode: 0o777, // @ts-expect-error -- TSCONVERSION size: entry.contents ? entry.contents.length : 0, ino: entry.ino, mtimeMs: entry.mtimeMs, }); } _find(filePath: string) { filePath = path.normalize(filePath); let current = this.__fs; // Ignore empty and current directory '.' segments const pathSegments = filePath.split(path.sep).filter(s => s !== '' && s !== '.'); for (const expectedName of pathSegments) { // @ts-expect-error -- TSCONVERSION const e = (current.children || []).find(c => c.name === expectedName); if (!e) { return null; } current = e; } // It's the root return current; } _assertDoesNotExist(filePath: string) { const entry = this._find(filePath); if (entry) { throw new SystemError({ code: 'EEXIST', errno: -17, message: `EEXIST: file already exists, open '${filePath}'`, path: filePath, syscall: 'open', }); } } _assertExists(filePath: string) { const entry = this._find(filePath); if (!entry) { throw new SystemError({ code: 'ENOENT', errno: -2, message: `ENOENT: no such file or directory, scandir '${filePath}'`, path: filePath, syscall: 'scandir', }); } return entry; } _assertDirEntry(entry: FSEntry) { if (entry.type !== 'dir') { throw new SystemError({ code: 'ENOTDIR', errno: -20, message: `ENOTDIR: not a directory, scandir '${entry.path}'`, path: entry.path, syscall: 'scandir', }); } return entry; } _assertDir(filePath: string) { const entry = this._assertExists(filePath); return this._assertDirEntry(entry); } _assertSymlinkEntry(entry: FSEntry) { if (entry.type !== 'symlink') { throw new SystemError({ code: 'ENOTDIR', errno: -20, message: `ENOTDIR: not a symlink, scandir '${entry.path}'`, path: entry.path, syscall: 'scandir', }); } return entry; } _assertSymlink(filePath: string) { const entry = this._assertExists(filePath); return this._assertSymlinkEntry(entry); } _resolveLinks(entry: FSEntry): FSFile | FSDir { if (entry.type === 'symlink') { const other = this._find(entry.linkTo); if (!other) { // Should never happen throw new Error('Failed to resolve link'); } return this._resolveLinks(other); } return entry; } _assertFileEntry(entry: FSEntry) { entry = this._resolveLinks(entry); if (entry.type === 'dir') { throw new SystemError({ code: 'EISDIR', errno: -21, message: `EISDIR: illegal operation on a directory '${entry.path}'`, path: entry.path, syscall: 'open', }); } return entry; } _assertFile(filePath: string) { const entry = this._assertExists(filePath); return this._assertFileEntry(entry); } _remove(entry: FSEntry) { const parentEntry = this._assertDir(path.dirname(entry.path)); const index = parentEntry.children.findIndex(c => c === entry); if (index < 0) { // Should never happen so w/e return; } parentEntry.children.splice(index, 1); } }
the_stack
import * as vsc from 'vscode'; import { Disposable, disposeAll } from './dispose'; import { WebviewCollection } from './util'; interface SQLiteEdit { readonly data: Uint8Array; } interface SQLiteDocumentDelegate { getFileData(): Promise<Uint8Array>; } class SQLiteDocument extends Disposable implements vsc.CustomDocument { static async create( uri: vsc.Uri, backupId: string | undefined, delegate: SQLiteDocumentDelegate, ): Promise<SQLiteDocument | PromiseLike<SQLiteDocument>> { // If we have a backup, read that. Otherwise read the resource from the workspace const dataFile = typeof backupId === 'string' ? vsc.Uri.parse(backupId) : uri; const fileData = await SQLiteDocument.readFile(dataFile); return new SQLiteDocument(uri, fileData, delegate); } private static async readFile(uri: vsc.Uri): Promise<Uint8Array> { if (uri.scheme === 'untitled') { return new Uint8Array(); } return vsc.workspace.fs.readFile(uri); } private readonly _uri: vsc.Uri; private _documentData: Uint8Array; private _edits: Array<SQLiteEdit> = []; private _savedEdits: Array<SQLiteEdit> = []; private readonly _delegate: SQLiteDocumentDelegate; private constructor( uri: vsc.Uri, initialContent: Uint8Array, delegate: SQLiteDocumentDelegate ) { super(); this._uri = uri; this._documentData = initialContent; this._delegate = delegate; } public get uri() { return this._uri; } private pathRegExp = /(?<dirname>.*)\/(?<filename>(?<basename>.*)(?<extname>\.[^.]+))$/ public get uriParts() { const { dirname, filename, basename, extname } = this._uri.toString().match(this.pathRegExp)?.groups ?? {} return { dirname, filename, basename, extname }; } public get documentData(): Uint8Array { return this._documentData; } private readonly _onDidDispose = this._register(new vsc.EventEmitter<void>()); /** * Fired when the document is disposed of. */ public readonly onDidDispose = this._onDidDispose.event; private readonly _onDidChangeDocument = this._register(new vsc.EventEmitter<{ readonly content?: Uint8Array; readonly edits: readonly SQLiteEdit[]; }>()); /** * Fired to notify webviews that the document has changed. */ public readonly onDidChangeContent = this._onDidChangeDocument.event; private readonly _onDidChange = this._register(new vsc.EventEmitter<{ readonly label: string, undo(): void, redo(): void, }>()); /** * Fired to tell VS Code that an edit has occurred in the document. * * This updates the document's dirty indicator. */ public readonly onDidChange = this._onDidChange.event; /** * Called by VS Code when there are no more references to the document. * * This happens when all editors for it have been closed. */ dispose(): void { this._onDidDispose.fire(); super.dispose(); } /** * Called when the user edits the document in a webview. * * This fires an event to notify VS Code that the document has been edited. */ makeEdit(edit: SQLiteEdit) { this._edits.push(edit); this._onDidChange.fire({ label: 'Stroke', undo: async () => { this._edits.pop(); this._onDidChangeDocument.fire({ edits: this._edits, }); }, redo: async () => { this._edits.push(edit); this._onDidChangeDocument.fire({ edits: this._edits, }); } }); } /** * Called by VS Code when the user saves the document. */ async save(cancellation: vsc.CancellationToken): Promise<void> { await this.saveAs(this.uri, cancellation); this._savedEdits = Array.from(this._edits); } /** * Called by VS Code when the user saves the document to a new location. */ async saveAs(targetResource: vsc.Uri, cancellation: vsc.CancellationToken): Promise<void> { const fileData = await this._delegate.getFileData(); if (cancellation.isCancellationRequested) { return; } await vsc.workspace.fs.writeFile(targetResource, fileData); } /** * Called by VS Code when the user calls `revert` on a document. */ async revert(_cancellation: vsc.CancellationToken): Promise<void> { const diskContent = await SQLiteDocument.readFile(this.uri); this._documentData = diskContent; this._edits = this._savedEdits; this._onDidChangeDocument.fire({ content: diskContent, edits: this._edits, }); } async refresh(_cancellation?: vsc.CancellationToken): Promise<void> { const diskContent = await SQLiteDocument.readFile(this.uri); this._documentData = diskContent; this._edits = []; this._onDidChangeDocument.fire({ content: diskContent, edits: [], }); } /** * Called by VS Code to backup the edited document. * * These backups are used to implement hot exit. */ async backup(destination: vsc.Uri, cancellation: vsc.CancellationToken): Promise<vsc.CustomDocumentBackup> { await this.saveAs(destination, cancellation); return { id: destination.toString(), delete: async () => { try { await vsc.workspace.fs.delete(destination); } catch { // noop } } }; } } const $default = 'default-src'; const $script = 'script-src'; const $style = 'style-src'; const $img = 'img-src'; const $font = 'font-src'; const $child = 'child-src'; const $self = "'self'"; const $vscode = 'vscode-resource: qwtel.vscode-unpkg.net'; // FIXME: find way to avoid hard-coding web extension domain const $data = 'data:' const $blob = 'blob:' const $inlineStyle = "'unsafe-inline'"; const $unsafeEval = "'unsafe-eval'"; const buildCSP = (cspObj: Record<string, string[]>) => Object.entries(cspObj).map(([k, vs]) => `${k} ${vs.join(' ')};`).join(' '); class SQLiteEditorProvider implements vsc.CustomEditorProvider<SQLiteDocument> { private readonly webviews = new WebviewCollection(); constructor(private readonly _context: vsc.ExtensionContext) {} //#region CustomEditorProvider async openCustomDocument( uri: vsc.Uri, openContext: { backupId?: string }, _token: vsc.CancellationToken ): Promise<SQLiteDocument> { const document: SQLiteDocument = await SQLiteDocument.create(uri, openContext.backupId, { getFileData: async () => { const webviewsForDocument = [...this.webviews.get(document.uri)]; if (!webviewsForDocument.length) { throw new Error('Could not find webview to save for'); } const panel = webviewsForDocument[0]; const response = await this.postMessageWithResponse<number[]>(panel, 'getFileData', {}); return new Uint8Array(response); } }); const listeners: vsc.Disposable[] = []; listeners.push(document.onDidChange(e => { // Tell VS Code that the document has been edited by the use. this._onDidChangeCustomDocument.fire({ document, ...e, }); })); listeners.push(document.onDidChangeContent(e => { // Update all webviews when the document changes // NOTE: per configuration there can only be one webivew per uri, so transfering the buffer is ok for (const webviewPanel of this.webviews.get(document.uri)) { const { filename } = document.uriParts; const { buffer, byteOffset, byteLength } = document.documentData const value = { buffer, byteOffset, byteLength }; // HACK: need to send uint8array disassembled... this.postMessage(webviewPanel, 'update', { filename, value, editable: false, }, [buffer]); } })); document.onDidDispose(() => disposeAll(listeners)); return document; } async resolveCustomEditor( document: SQLiteDocument, webviewPanel: vsc.WebviewPanel, token: vsc.CancellationToken ): Promise<void> { // Add the webview to our internal set of active webviews this.webviews.add(document.uri, webviewPanel); // Setup initial content for the webview webviewPanel.webview.options = { enableScripts: true, }; webviewPanel.webview.html = await this.getHtmlForWebview(webviewPanel.webview); webviewPanel.webview.onDidReceiveMessage(e => this.onMessage(document, e)); // Wait for the webview to be properly ready before we init webviewPanel.webview.onDidReceiveMessage(e => { if (e.type === 'ready' && this.webviews.has(document.uri)) { if (document.uri.scheme === 'untitled') { this.postMessage(webviewPanel, 'init', { filename: 'untitled', untitled: true, editable: false, }); } else { // const editable = vscode.workspace.fs.isWritableFileSystem(document.uri.scheme); const editable = false const { buffer, byteOffset, byteLength } = document.documentData const value = { buffer, byteOffset, byteLength }; // HACK: need to send uint8array disassembled... // HACK: Making a copy to deal with byteoffset. // Maybe transfer original uint8array instead!? // const value = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength); const { filename } = document.uriParts; this.postMessage(webviewPanel, 'init', { filename, value, editable, }, [buffer]); } } }); } private readonly _onDidChangeCustomDocument = new vsc.EventEmitter<vsc.CustomDocumentEditEvent<SQLiteDocument>>(); public readonly onDidChangeCustomDocument = this._onDidChangeCustomDocument.event; public saveCustomDocument(document: SQLiteDocument, cancellation: vsc.CancellationToken): Thenable<void> { return document.save(cancellation); } public saveCustomDocumentAs(document: SQLiteDocument, destination: vsc.Uri, cancellation: vsc.CancellationToken): Thenable<void> { return document.saveAs(destination, cancellation); } public revertCustomDocument(document: SQLiteDocument, cancellation: vsc.CancellationToken): Thenable<void> { return document.revert(cancellation); } public backupCustomDocument(document: SQLiteDocument, context: vsc.CustomDocumentBackupContext, cancellation: vsc.CancellationToken): Thenable<vsc.CustomDocumentBackup> { return document.backup(context.destination, cancellation); } //#endregion private async getHtmlForWebview(webview: vsc.Webview): Promise<string> { const publicUri = vsc.Uri.joinPath(this._context.extensionUri, 'sqlite-viewer-app', 'public'); const codiconsUri = vsc.Uri.joinPath(this._context.extensionUri, 'node_modules', '@vscode/codicons', 'dist', 'codicon.css'); const html = new TextDecoder().decode(await vsc.workspace.fs.readFile( vsc.Uri.joinPath(publicUri, 'vscode.html') )); const PUBLIC_URL = webview.asWebviewUri( vsc.Uri.joinPath(this._context.extensionUri, 'sqlite-viewer-app', 'public') ).toString(); const csp = { [$default]: [$self, $vscode], [$script]: [$self, $vscode, $unsafeEval], // HACK: Needed for WebAssembly in Web Extension. Needless to say, it makes the whole CSP useless... [$style]: [$self, $vscode, $inlineStyle], [$img]: [$self, $vscode, $data], [$font]: [$self, $vscode], [$child]: [$blob], }; const prepHtml = html .replaceAll('%PUBLIC_URL%', PUBLIC_URL) .replaceAll('%REACT_APP_CSP%', buildCSP(csp)) .replace('<!--HEAD-->', ` <link rel="stylesheet" href="${webview.asWebviewUri(vsc.Uri.joinPath(publicUri, 'bundle.css'))}"/> <link rel="stylesheet" href="${webview.asWebviewUri(codiconsUri)}"/> `) .replace('<!--BODY-->', ` <script src="${webview.asWebviewUri(vsc.Uri.joinPath(publicUri, 'bundle.js'))}"></script> `) return prepHtml; } private _requestId = 1; private readonly _callbacks = new Map<number, (response: any) => void>(); private postMessageWithResponse<R = unknown>(panel: vsc.WebviewPanel, type: string, body: any): Promise<R> { const requestId = this._requestId++; const p = new Promise<R>(resolve => this._callbacks.set(requestId, resolve)); panel.webview.postMessage({ type, requestId, body }); return p; } private postMessage(panel: vsc.WebviewPanel, type: string, body: any, transfer?: any[]): void { // @ts-ignore panel.webview.postMessage({ type, body }, transfer); } private async onMessage(document: SQLiteDocument, message: any) { switch (message.type) { case 'refresh': if (document.uri.scheme !== 'untitled') { document.refresh() } return; case 'blob': const { data, download, metaKey } = message; const { dirname } = document.uriParts; const dlUri = vsc.Uri.parse(`${dirname}/${download}`); await vsc.workspace.fs.writeFile(dlUri, data); if (!metaKey) await vsc.commands.executeCommand('vscode.open', dlUri); return; case 'response': { const callback = this._callbacks.get(message.requestId); callback?.(message.body); return; } } } } const registerOptions = { webviewOptions: { // TODO: serialize state!? retainContextWhenHidden: true, }, supportsMultipleEditorsPerDocument: false, } export class SQLiteEditorDefaultProvider extends SQLiteEditorProvider { static viewType = 'sqlite-viewer.view'; public static register(context: vsc.ExtensionContext): vsc.Disposable { return vsc.window.registerCustomEditorProvider( SQLiteEditorDefaultProvider.viewType, new SQLiteEditorDefaultProvider(context), registerOptions); } } export class SQLiteEditorOptionProvider extends SQLiteEditorProvider { static viewType = 'sqlite-viewer.option'; public static register(context: vsc.ExtensionContext): vsc.Disposable { return vsc.window.registerCustomEditorProvider( SQLiteEditorOptionProvider.viewType, new SQLiteEditorOptionProvider(context), registerOptions); } }
the_stack
// IMPORTANT // This file was generated by https://github.com/Maxim-Mazurok/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Maxim-Mazurok/google-api-typings-generator // Generated from: https://firestore.googleapis.com/\$discovery/rest?version=v1 // Revision: 20200405 /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Cloud Firestore API v1 */ function load(name: 'firestore', version: 'v1'): PromiseLike<void>; function load(name: 'firestore', version: 'v1', callback: () => any): void; export namespace firestore { interface ArrayValue { /** Values in the array. */ values?: Value[]; } interface BatchGetDocumentsRequest { /** * The names of the documents to retrieve. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * The request will fail if any of the document is not a child resource of the * given `database`. Duplicate names will be elided. */ documents?: string[]; /** * The fields to return. If not set, returns all fields. * * If a document has a field that is not present in this mask, that field will * not be returned in the response. */ mask?: DocumentMask; /** * Starts a new transaction and reads the documents. * Defaults to a read-only transaction. * The new transaction ID will be returned as the first response in the * stream. */ newTransaction?: TransactionOptions; /** * Reads documents as they were at the given time. * This may not be older than 270 seconds. */ readTime?: string; /** Reads documents in a transaction. */ transaction?: string; } interface BatchGetDocumentsResponse { /** A document that was requested. */ found?: Document; /** * A document name that was requested but does not exist. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ missing?: string; /** * The time at which the document was read. * This may be monotically increasing, in this case the previous documents in * the result stream are guaranteed not to have changed between their * read_time and this one. */ readTime?: string; /** * The transaction that was started as part of this request. * Will only be set in the first response, and only if * BatchGetDocumentsRequest.new_transaction was set in the request. */ transaction?: string; } interface BeginTransactionRequest { /** * The options for the transaction. * Defaults to a read-write transaction. */ options?: TransactionOptions; } interface BeginTransactionResponse { /** The transaction that was started. */ transaction?: string; } interface CollectionSelector { /** * When false, selects only collections that are immediate children of * the `parent` specified in the containing `RunQueryRequest`. * When true, selects all descendant collections. */ allDescendants?: boolean; /** * The collection ID. * When set, selects only collections with this ID. */ collectionId?: string; } interface CommitRequest { /** If set, applies all writes in this transaction, and commits it. */ transaction?: string; /** * The writes to apply. * * Always executed atomically and in order. */ writes?: Write[]; } interface CommitResponse { /** * The time at which the commit occurred. Any read with an equal or greater * `read_time` is guaranteed to see the effects of the commit. */ commitTime?: string; /** * The result of applying the writes. * * This i-th write result corresponds to the i-th write in the * request. */ writeResults?: WriteResult[]; } interface CompositeFilter { /** * The list of filters to combine. * Must contain at least one filter. */ filters?: Filter[]; /** The operator for combining multiple filters. */ op?: string; } interface Cursor { /** * If the position is just before or just after the given values, relative * to the sort order defined by the query. */ before?: boolean; /** * The values that represent a position, in the order they appear in * the order by clause of a query. * * Can contain fewer values than specified in the order by clause. */ values?: Value[]; } interface Document { /** * Output only. The time at which the document was created. * * This value increases monotonically when a document is deleted then * recreated. It can also be compared to values from other documents and * the `read_time` of a query. */ createTime?: string; /** * The document's fields. * * The map keys represent field names. * * A simple field name contains only characters `a` to `z`, `A` to `Z`, * `0` to `9`, or `_`, and must not start with `0` to `9`. For example, * `foo_bar_17`. * * Field names matching the regular expression `__.&#42;__` are reserved. Reserved * field names are forbidden except in certain documented contexts. The map * keys, represented as UTF-8, must not exceed 1,500 bytes and cannot be * empty. * * Field paths may be used in other contexts to refer to structured fields * defined here. For `map_value`, the field path is represented by the simple * or quoted field names of the containing fields, delimited by `.`. For * example, the structured field * `"foo" : { map_value: { "x&y" : { string_value: "hello" }}}` would be * represented by the field path `foo.x&y`. * * Within a field path, a quoted field name starts and ends with `` ` `` and * may contain any character. Some characters, including `` ` ``, must be * escaped using a `\`. For example, `` `x&y` `` represents `x&y` and * `` `bak\`tik` `` represents `` bak`tik ``. */ fields?: Record<string, Value>; /** * The resource name of the document, for example * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ name?: string; /** * Output only. The time at which the document was last changed. * * This value is initially set to the `create_time` then increases * monotonically with each change to the document. It can also be * compared to values from other documents and the `read_time` of a query. */ updateTime?: string; } interface DocumentChange { /** * The new state of the Document. * * If `mask` is set, contains only fields that were updated or added. */ document?: Document; /** A set of target IDs for targets that no longer match this document. */ removedTargetIds?: number[]; /** A set of target IDs of targets that match this document. */ targetIds?: number[]; } interface DocumentDelete { /** The resource name of the Document that was deleted. */ document?: string; /** * The read timestamp at which the delete was observed. * * Greater or equal to the `commit_time` of the delete. */ readTime?: string; /** A set of target IDs for targets that previously matched this entity. */ removedTargetIds?: number[]; } interface DocumentMask { /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ fieldPaths?: string[]; } interface DocumentRemove { /** The resource name of the Document that has gone out of view. */ document?: string; /** * The read timestamp at which the remove was observed. * * Greater or equal to the `commit_time` of the change/delete/remove. */ readTime?: string; /** A set of target IDs for targets that previously matched this document. */ removedTargetIds?: number[]; } interface DocumentsTarget { /** * The names of the documents to retrieve. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * The request will fail if any of the document is not a child resource of * the given `database`. Duplicate names will be elided. */ documents?: string[]; } interface DocumentTransform { /** The name of the document to transform. */ document?: string; /** * The list of transformations to apply to the fields of the document, in * order. * This must not be empty. */ fieldTransforms?: FieldTransform[]; } // eslint-disable-next-line @typescript-eslint/no-empty-interface interface Empty {} interface ExistenceFilter { /** * The total count of documents that match target_id. * * If different from the count of documents in the client that match, the * client must manually determine which documents no longer match the target. */ count?: number; /** The target ID to which this filter applies. */ targetId?: number; } interface FieldFilter { /** The field to filter by. */ field?: FieldReference; /** The operator to filter by. */ op?: string; /** The value to compare to. */ value?: Value; } interface FieldReference { fieldPath?: string; } interface FieldTransform { /** * Append the given elements in order if they are not already present in * the current field value. * If the field is not an array, or if the field does not yet exist, it is * first set to the empty array. * * Equivalent numbers of different types (e.g. 3L and 3.0) are * considered equal when checking if a value is missing. * NaN is equal to NaN, and Null is equal to Null. * If the input contains multiple equivalent values, only the first will * be considered. * * The corresponding transform_result will be the null value. */ appendMissingElements?: ArrayValue; /** * The path of the field. See Document.fields for the field path syntax * reference. */ fieldPath?: string; /** * Adds the given value to the field's current value. * * This must be an integer or a double value. * If the field is not an integer or double, or if the field does not yet * exist, the transformation will set the field to the given value. * If either of the given value or the current field value are doubles, * both values will be interpreted as doubles. Double arithmetic and * representation of double values follow IEEE 754 semantics. * If there is positive/negative integer overflow, the field is resolved * to the largest magnitude positive/negative integer. */ increment?: Value; /** * Sets the field to the maximum of its current value and the given value. * * This must be an integer or a double value. * If the field is not an integer or double, or if the field does not yet * exist, the transformation will set the field to the given value. * If a maximum operation is applied where the field and the input value * are of mixed types (that is - one is an integer and one is a double) * the field takes on the type of the larger operand. If the operands are * equivalent (e.g. 3 and 3.0), the field does not change. * 0, 0.0, and -0.0 are all zero. The maximum of a zero stored value and * zero input value is always the stored value. * The maximum of any numeric value x and NaN is NaN. */ maximum?: Value; /** * Sets the field to the minimum of its current value and the given value. * * This must be an integer or a double value. * If the field is not an integer or double, or if the field does not yet * exist, the transformation will set the field to the input value. * If a minimum operation is applied where the field and the input value * are of mixed types (that is - one is an integer and one is a double) * the field takes on the type of the smaller operand. If the operands are * equivalent (e.g. 3 and 3.0), the field does not change. * 0, 0.0, and -0.0 are all zero. The minimum of a zero stored value and * zero input value is always the stored value. * The minimum of any numeric value x and NaN is NaN. */ minimum?: Value; /** * Remove all of the given elements from the array in the field. * If the field is not an array, or if the field does not yet exist, it is * set to the empty array. * * Equivalent numbers of the different types (e.g. 3L and 3.0) are * considered equal when deciding whether an element should be removed. * NaN is equal to NaN, and Null is equal to Null. * This will remove all equivalent values if there are duplicates. * * The corresponding transform_result will be the null value. */ removeAllFromArray?: ArrayValue; /** Sets the field to the given server value. */ setToServerValue?: string; } interface Filter { /** A composite filter. */ compositeFilter?: CompositeFilter; /** A filter on a document field. */ fieldFilter?: FieldFilter; /** A filter that takes exactly one argument. */ unaryFilter?: UnaryFilter; } interface GoogleFirestoreAdminV1ExportDocumentsMetadata { /** Which collection ids are being exported. */ collectionIds?: string[]; /** * The time this operation completed. Will be unset if operation still in * progress. */ endTime?: string; /** The state of the export operation. */ operationState?: string; /** Where the entities are being exported to. */ outputUriPrefix?: string; /** The progress, in bytes, of this operation. */ progressBytes?: GoogleFirestoreAdminV1Progress; /** The progress, in documents, of this operation. */ progressDocuments?: GoogleFirestoreAdminV1Progress; /** The time this operation started. */ startTime?: string; } interface GoogleFirestoreAdminV1ExportDocumentsRequest { /** Which collection ids to export. Unspecified means all collections. */ collectionIds?: string[]; /** * The output URI. Currently only supports Google Cloud Storage URIs of the * form: `gs://BUCKET_NAME[/NAMESPACE_PATH]`, where `BUCKET_NAME` is the name * of the Google Cloud Storage bucket and `NAMESPACE_PATH` is an optional * Google Cloud Storage namespace path. When * choosing a name, be sure to consider Google Cloud Storage naming * guidelines: https://cloud.google.com/storage/docs/naming. * If the URI is a bucket (without a namespace path), a prefix will be * generated based on the start time. */ outputUriPrefix?: string; } interface GoogleFirestoreAdminV1ExportDocumentsResponse { /** * Location of the output files. This can be used to begin an import * into Cloud Firestore (this project or another project) after the operation * completes successfully. */ outputUriPrefix?: string; } interface GoogleFirestoreAdminV1Field { /** * The index configuration for this field. If unset, field indexing will * revert to the configuration defined by the `ancestor_field`. To * explicitly remove all indexes for this field, specify an index config * with an empty list of indexes. */ indexConfig?: GoogleFirestoreAdminV1IndexConfig; /** * A field name of the form * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_path}` * * A field path may be a simple field name, e.g. `address` or a path to fields * within map_value , e.g. `address.city`, * or a special field path. The only valid special field is `&#42;`, which * represents any field. * * Field paths may be quoted using ` (backtick). The only character that needs * to be escaped within a quoted field path is the backtick character itself, * escaped using a backslash. Special characters in field paths that * must be quoted include: `&#42;`, `.`, * ``` (backtick), `[`, `]`, as well as any ascii symbolic characters. * * Examples: * (Note: Comments here are written in markdown syntax, so there is an * additional layer of backticks to represent a code block) * `\`address.city\`` represents a field named `address.city`, not the map key * `city` in the field `address`. * `\`&#42;\`` represents a field named `&#42;`, not any field. * * A special `Field` contains the default indexing settings for all fields. * This field's resource name is: * `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/&#42;` * Indexes defined on this `Field` will be applied to all fields which do not * have their own `Field` index configuration. */ name?: string; } interface GoogleFirestoreAdminV1FieldOperationMetadata { /** * The time this operation completed. Will be unset if operation still in * progress. */ endTime?: string; /** * The field resource that this operation is acting on. For example: * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_path}` */ field?: string; /** * A list of IndexConfigDelta, which describe the intent of this * operation. */ indexConfigDeltas?: GoogleFirestoreAdminV1IndexConfigDelta[]; /** The progress, in bytes, of this operation. */ progressBytes?: GoogleFirestoreAdminV1Progress; /** The progress, in documents, of this operation. */ progressDocuments?: GoogleFirestoreAdminV1Progress; /** The time this operation started. */ startTime?: string; /** The state of the operation. */ state?: string; } interface GoogleFirestoreAdminV1ImportDocumentsMetadata { /** Which collection ids are being imported. */ collectionIds?: string[]; /** * The time this operation completed. Will be unset if operation still in * progress. */ endTime?: string; /** The location of the documents being imported. */ inputUriPrefix?: string; /** The state of the import operation. */ operationState?: string; /** The progress, in bytes, of this operation. */ progressBytes?: GoogleFirestoreAdminV1Progress; /** The progress, in documents, of this operation. */ progressDocuments?: GoogleFirestoreAdminV1Progress; /** The time this operation started. */ startTime?: string; } interface GoogleFirestoreAdminV1ImportDocumentsRequest { /** * Which collection ids to import. Unspecified means all collections included * in the import. */ collectionIds?: string[]; /** * Location of the exported files. * This must match the output_uri_prefix of an ExportDocumentsResponse from * an export that has completed successfully. * See: * google.firestore.admin.v1.ExportDocumentsResponse.output_uri_prefix. */ inputUriPrefix?: string; } interface GoogleFirestoreAdminV1Index { /** * The fields supported by this index. * * For composite indexes, this is always 2 or more fields. * The last field entry is always for the field path `__name__`. If, on * creation, `__name__` was not specified as the last field, it will be added * automatically with the same direction as that of the last field defined. If * the final field in a composite index is not directional, the `__name__` * will be ordered ASCENDING (unless explicitly specified). * * For single field indexes, this will always be exactly one entry with a * field path equal to the field path of the associated field. */ fields?: GoogleFirestoreAdminV1IndexField[]; /** * Output only. A server defined name for this index. * The form of this name for composite indexes will be: * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{composite_index_id}` * For single field indexes, this field will be empty. */ name?: string; /** * Indexes with a collection query scope specified allow queries * against a collection that is the child of a specific document, specified at * query time, and that has the same collection id. * * Indexes with a collection group query scope specified allow queries against * all collections descended from a specific document, specified at query * time, and that have the same collection id as this index. */ queryScope?: string; /** Output only. The serving state of the index. */ state?: string; } interface GoogleFirestoreAdminV1IndexConfig { /** * Output only. Specifies the resource name of the `Field` from which this field's * index configuration is set (when `uses_ancestor_config` is true), * or from which it &#42;would&#42; be set if this field had no index configuration * (when `uses_ancestor_config` is false). */ ancestorField?: string; /** The indexes supported for this field. */ indexes?: GoogleFirestoreAdminV1Index[]; /** * Output only * When true, the `Field`'s index configuration is in the process of being * reverted. Once complete, the index config will transition to the same * state as the field specified by `ancestor_field`, at which point * `uses_ancestor_config` will be `true` and `reverting` will be `false`. */ reverting?: boolean; /** * Output only. When true, the `Field`'s index configuration is set from the * configuration specified by the `ancestor_field`. * When false, the `Field`'s index configuration is defined explicitly. */ usesAncestorConfig?: boolean; } interface GoogleFirestoreAdminV1IndexConfigDelta { /** Specifies how the index is changing. */ changeType?: string; /** The index being changed. */ index?: GoogleFirestoreAdminV1Index; } interface GoogleFirestoreAdminV1IndexField { /** Indicates that this field supports operations on `array_value`s. */ arrayConfig?: string; /** * Can be __name__. * For single field indexes, this must match the name of the field or may * be omitted. */ fieldPath?: string; /** * Indicates that this field supports ordering by the specified order or * comparing using =, <, <=, >, >=. */ order?: string; } interface GoogleFirestoreAdminV1IndexOperationMetadata { /** * The time this operation completed. Will be unset if operation still in * progress. */ endTime?: string; /** * The index resource that this operation is acting on. For example: * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` */ index?: string; /** The progress, in bytes, of this operation. */ progressBytes?: GoogleFirestoreAdminV1Progress; /** The progress, in documents, of this operation. */ progressDocuments?: GoogleFirestoreAdminV1Progress; /** The time this operation started. */ startTime?: string; /** The state of the operation. */ state?: string; } interface GoogleFirestoreAdminV1ListFieldsResponse { /** The requested fields. */ fields?: GoogleFirestoreAdminV1Field[]; /** * A page token that may be used to request another page of results. If blank, * this is the last page. */ nextPageToken?: string; } interface GoogleFirestoreAdminV1ListIndexesResponse { /** The requested indexes. */ indexes?: GoogleFirestoreAdminV1Index[]; /** * A page token that may be used to request another page of results. If blank, * this is the last page. */ nextPageToken?: string; } // eslint-disable-next-line @typescript-eslint/no-empty-interface interface GoogleFirestoreAdminV1LocationMetadata {} interface GoogleFirestoreAdminV1Progress { /** The amount of work completed. */ completedWork?: string; /** The amount of work estimated. */ estimatedWork?: string; } // eslint-disable-next-line @typescript-eslint/no-empty-interface interface GoogleLongrunningCancelOperationRequest {} interface GoogleLongrunningListOperationsResponse { /** The standard List next-page token. */ nextPageToken?: string; /** A list of operations that matches the specified filter in the request. */ operations?: GoogleLongrunningOperation[]; } interface GoogleLongrunningOperation { /** * If the value is `false`, it means the operation is still in progress. * If `true`, the operation is completed, and either `error` or `response` is * available. */ done?: boolean; /** The error result of the operation in case of failure or cancellation. */ error?: Status; /** * Service-specific metadata associated with the operation. It typically * contains progress information and common metadata such as create time. * Some services might not provide such metadata. Any method that returns a * long-running operation should document the metadata type, if any. */ metadata?: Record<string, any>; /** * The server-assigned name, which is only unique within the same service that * originally returns it. If you use the default HTTP mapping, the * `name` should be a resource name ending with `operations/{unique_id}`. */ name?: string; /** * The normal response of the operation in case of success. If the original * method returns no data on success, such as `Delete`, the response is * `google.protobuf.Empty`. If the original method is standard * `Get`/`Create`/`Update`, the response should be the resource. For other * methods, the response should have the type `XxxResponse`, where `Xxx` * is the original method name. For example, if the original method name * is `TakeSnapshot()`, the inferred response type is * `TakeSnapshotResponse`. */ response?: Record<string, any>; } interface LatLng { /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */ latitude?: number; /** The longitude in degrees. It must be in the range [-180.0, +180.0]. */ longitude?: number; } interface ListCollectionIdsRequest { /** The maximum number of results to return. */ pageSize?: number; /** * A page token. Must be a value from * ListCollectionIdsResponse. */ pageToken?: string; } interface ListCollectionIdsResponse { /** The collection ids. */ collectionIds?: string[]; /** A page token that may be used to continue the list. */ nextPageToken?: string; } interface ListDocumentsResponse { /** The Documents found. */ documents?: Document[]; /** The next page token. */ nextPageToken?: string; } interface ListenRequest { /** A target to add to this stream. */ addTarget?: Target; /** Labels associated with this target change. */ labels?: Record<string, string>; /** The ID of a target to remove from this stream. */ removeTarget?: number; } interface ListenResponse { /** A Document has changed. */ documentChange?: DocumentChange; /** A Document has been deleted. */ documentDelete?: DocumentDelete; /** * A Document has been removed from a target (because it is no longer * relevant to that target). */ documentRemove?: DocumentRemove; /** * A filter to apply to the set of documents previously returned for the * given target. * * Returned when documents may have been removed from the given target, but * the exact documents are unknown. */ filter?: ExistenceFilter; /** Targets have changed. */ targetChange?: TargetChange; } interface ListLocationsResponse { /** A list of locations that matches the specified filter in the request. */ locations?: Location[]; /** The standard List next-page token. */ nextPageToken?: string; } interface Location { /** * The friendly name for this location, typically a nearby city name. * For example, "Tokyo". */ displayName?: string; /** * Cross-service attributes for the location. For example * * {"cloud.googleapis.com/region": "us-east1"} */ labels?: Record<string, string>; /** The canonical id for this location. For example: `"us-east1"`. */ locationId?: string; /** * Service-specific metadata. For example the available capacity at the given * location. */ metadata?: Record<string, any>; /** * Resource name for the location, which may vary between implementations. * For example: `"projects/example-project/locations/us-east1"` */ name?: string; } interface MapValue { /** * The map's fields. * * The map keys represent field names. Field names matching the regular * expression `__.&#42;__` are reserved. Reserved field names are forbidden except * in certain documented contexts. The map keys, represented as UTF-8, must * not exceed 1,500 bytes and cannot be empty. */ fields?: Record<string, Value>; } interface Order { /** The direction to order by. Defaults to `ASCENDING`. */ direction?: string; /** The field to order by. */ field?: FieldReference; } interface Precondition { /** * When set to `true`, the target document must exist. * When set to `false`, the target document must not exist. */ exists?: boolean; /** * When set, the target document must exist and have been last updated at * that time. */ updateTime?: string; } interface Projection { /** * The fields to return. * * If empty, all fields are returned. To only return the name * of the document, use `['__name__']`. */ fields?: FieldReference[]; } interface QueryTarget { /** * The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` */ parent?: string; /** A structured query. */ structuredQuery?: StructuredQuery; } interface ReadOnly { /** * Reads documents at the given time. * This may not be older than 60 seconds. */ readTime?: string; } interface ReadWrite { /** An optional transaction to retry. */ retryTransaction?: string; } interface RollbackRequest { /** Required. The transaction to roll back. */ transaction?: string; } interface RunQueryRequest { /** * Starts a new transaction and reads the documents. * Defaults to a read-only transaction. * The new transaction ID will be returned as the first response in the * stream. */ newTransaction?: TransactionOptions; /** * Reads documents as they were at the given time. * This may not be older than 270 seconds. */ readTime?: string; /** A structured query. */ structuredQuery?: StructuredQuery; /** Reads documents in a transaction. */ transaction?: string; } interface RunQueryResponse { /** * A query result. * Not set when reporting partial progress. */ document?: Document; /** * The time at which the document was read. This may be monotonically * increasing; in this case, the previous documents in the result stream are * guaranteed not to have changed between their `read_time` and this one. * * If the query returns no results, a response with `read_time` and no * `document` will be sent, and this represents the time at which the query * was run. */ readTime?: string; /** * The number of results that have been skipped due to an offset between * the last response and the current response. */ skippedResults?: number; /** * The transaction that was started as part of this request. * Can only be set in the first response, and only if * RunQueryRequest.new_transaction was set in the request. * If set, no other fields will be set in this response. */ transaction?: string; } interface Status { /** The status code, which should be an enum value of google.rpc.Code. */ code?: number; /** * A list of messages that carry the error details. There is a common set of * message types for APIs to use. */ details?: Array<Record<string, any>>; /** * A developer-facing error message, which should be in English. Any * user-facing error message should be localized and sent in the * google.rpc.Status.details field, or localized by the client. */ message?: string; } interface StructuredQuery { /** A end point for the query results. */ endAt?: Cursor; /** The collections to query. */ from?: CollectionSelector[]; /** * The maximum number of results to return. * * Applies after all other constraints. * Must be >= 0 if specified. */ limit?: number; /** * The number of results to skip. * * Applies before limit, but after all other constraints. Must be >= 0 if * specified. */ offset?: number; /** * The order to apply to the query results. * * Firestore guarantees a stable ordering through the following rules: * * &#42; Any field required to appear in `order_by`, that is not already * specified in `order_by`, is appended to the order in field name order * by default. * &#42; If an order on `__name__` is not specified, it is appended by default. * * Fields are appended with the same sort direction as the last order * specified, or 'ASCENDING' if no order was specified. For example: * * &#42; `SELECT &#42; FROM Foo ORDER BY A` becomes * `SELECT &#42; FROM Foo ORDER BY A, __name__` * &#42; `SELECT &#42; FROM Foo ORDER BY A DESC` becomes * `SELECT &#42; FROM Foo ORDER BY A DESC, __name__ DESC` * &#42; `SELECT &#42; FROM Foo WHERE A > 1` becomes * `SELECT &#42; FROM Foo WHERE A > 1 ORDER BY A, __name__` */ orderBy?: Order[]; /** The projection to return. */ select?: Projection; /** A starting point for the query results. */ startAt?: Cursor; /** The filter to apply. */ where?: Filter; } interface Target { /** A target specified by a set of document names. */ documents?: DocumentsTarget; /** If the target should be removed once it is current and consistent. */ once?: boolean; /** A target specified by a query. */ query?: QueryTarget; /** * Start listening after a specific `read_time`. * * The client must know the state of matching documents at this time. */ readTime?: string; /** * A resume token from a prior TargetChange for an identical target. * * Using a resume token with a different target is unsupported and may fail. */ resumeToken?: string; /** * The target ID that identifies the target on the stream. Must be a positive * number and non-zero. */ targetId?: number; } interface TargetChange { /** The error that resulted in this change, if applicable. */ cause?: Status; /** * The consistent `read_time` for the given `target_ids` (omitted when the * target_ids are not at a consistent snapshot). * * The stream is guaranteed to send a `read_time` with `target_ids` empty * whenever the entire stream reaches a new consistent snapshot. ADD, * CURRENT, and RESET messages are guaranteed to (eventually) result in a * new consistent snapshot (while NO_CHANGE and REMOVE messages are not). * * For a given stream, `read_time` is guaranteed to be monotonically * increasing. */ readTime?: string; /** * A token that can be used to resume the stream for the given `target_ids`, * or all targets if `target_ids` is empty. * * Not set on every target change. */ resumeToken?: string; /** The type of change that occurred. */ targetChangeType?: string; /** * The target IDs of targets that have changed. * * If empty, the change applies to all targets. * * The order of the target IDs is not defined. */ targetIds?: number[]; } interface TransactionOptions { /** The transaction can only be used for read operations. */ readOnly?: ReadOnly; /** The transaction can be used for both read and write operations. */ readWrite?: ReadWrite; } interface UnaryFilter { /** The field to which to apply the operator. */ field?: FieldReference; /** The unary operator to apply. */ op?: string; } interface Value { /** * An array value. * * Cannot directly contain another array value, though can contain an * map which contains another array. */ arrayValue?: ArrayValue; /** A boolean value. */ booleanValue?: boolean; /** * A bytes value. * * Must not exceed 1 MiB - 89 bytes. * Only the first 1,500 bytes are considered by queries. */ bytesValue?: string; /** A double value. */ doubleValue?: number; /** A geo point value representing a point on the surface of Earth. */ geoPointValue?: LatLng; /** An integer value. */ integerValue?: string; /** A map value. */ mapValue?: MapValue; /** A null value. */ nullValue?: null; /** * A reference to a document. For example: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ referenceValue?: string; /** * A string value. * * The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes. * Only the first 1,500 bytes of the UTF-8 representation are considered by * queries. */ stringValue?: string; /** * A timestamp value. * * Precise only to microseconds. When stored, any additional precision is * rounded down. */ timestampValue?: string; } interface Write { /** * An optional precondition on the document. * * The write will fail if this is set and not met by the target document. */ currentDocument?: Precondition; /** * A document name to delete. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ delete?: string; /** Applies a transformation to a document. */ transform?: DocumentTransform; /** A document to write. */ update?: Document; /** * The fields to update in this write. * * This field can be set only when the operation is `update`. * If the mask is not set for an `update` and the document exists, any * existing data will be overwritten. * If the mask is set and the document on the server has fields not covered by * the mask, they are left unchanged. * Fields referenced in the mask, but not present in the input document, are * deleted from the document on the server. * The field paths in this mask must not contain a reserved field name. */ updateMask?: DocumentMask; /** * The transforms to perform after update. * * This field can be set only when the operation is `update`. If present, this * write is equivalent to performing `update` and `transform` to the same * document atomically and in order. */ updateTransforms?: FieldTransform[]; } interface WriteRequest { /** Labels associated with this write request. */ labels?: Record<string, string>; /** * The ID of the write stream to resume. * This may only be set in the first message. When left empty, a new write * stream will be created. */ streamId?: string; /** * A stream token that was previously sent by the server. * * The client should set this field to the token from the most recent * WriteResponse it has received. This acknowledges that the client has * received responses up to this token. After sending this token, earlier * tokens may not be used anymore. * * The server may close the stream if there are too many unacknowledged * responses. * * Leave this field unset when creating a new stream. To resume a stream at * a specific point, set this field and the `stream_id` field. * * Leave this field unset when creating a new stream. */ streamToken?: string; /** * The writes to apply. * * Always executed atomically and in order. * This must be empty on the first request. * This may be empty on the last request. * This must not be empty on all other requests. */ writes?: Write[]; } interface WriteResponse { /** * The time at which the commit occurred. Any read with an equal or greater * `read_time` is guaranteed to see the effects of the write. */ commitTime?: string; /** * The ID of the stream. * Only set on the first message, when a new stream was created. */ streamId?: string; /** * A token that represents the position of this response in the stream. * This can be used by a client to resume the stream at this point. * * This field is always set. */ streamToken?: string; /** * The result of applying the writes. * * This i-th write result corresponds to the i-th write in the * request. */ writeResults?: WriteResult[]; } interface WriteResult { /** * The results of applying each DocumentTransform.FieldTransform, in the * same order. */ transformResults?: Value[]; /** * The last update time of the document after applying the write. Not set * after a `delete`. * * If the write did not actually change the document, this will be the * previous update_time. */ updateTime?: string; } interface FieldsResource { /** Gets the metadata and configuration for a Field. */ get(request?: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * Required. A name of the form * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_id}` */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }): Request<GoogleFirestoreAdminV1Field>; /** * Lists the field configuration and metadata for this database. * * Currently, FirestoreAdmin.ListFields only supports listing fields * that have been explicitly overridden. To issue this query, call * FirestoreAdmin.ListFields with the filter set to * `indexConfig.usesAncestorConfig:false`. */ list(request?: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** * The filter to apply to list results. Currently, * FirestoreAdmin.ListFields only supports listing fields * that have been explicitly overridden. To issue this query, call * FirestoreAdmin.ListFields with the filter set to * `indexConfig.usesAncestorConfig:false`. */ 'filter'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** The number of results to return. */ 'pageSize'?: number; /** * A page token, returned from a previous call to * FirestoreAdmin.ListFields, that may be used to get the next * page of results. */ 'pageToken'?: string; /** * Required. A parent name of the form * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` */ 'parent': string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }): Request<GoogleFirestoreAdminV1ListFieldsResponse>; /** * Updates a field configuration. Currently, field updates apply only to * single field index configuration. However, calls to * FirestoreAdmin.UpdateField should provide a field mask to avoid * changing any configuration that the caller isn't aware of. The field mask * should be specified as: `{ paths: "index_config" }`. * * This call returns a google.longrunning.Operation which may be used to * track the status of the field update. The metadata for * the operation will be the type FieldOperationMetadata. * * To configure the default field settings for the database, use * the special `Field` with resource name: * `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/&#42;`. */ patch(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * A field name of the form * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_path}` * * A field path may be a simple field name, e.g. `address` or a path to fields * within map_value , e.g. `address.city`, * or a special field path. The only valid special field is `&#42;`, which * represents any field. * * Field paths may be quoted using ` (backtick). The only character that needs * to be escaped within a quoted field path is the backtick character itself, * escaped using a backslash. Special characters in field paths that * must be quoted include: `&#42;`, `.`, * ``` (backtick), `[`, `]`, as well as any ascii symbolic characters. * * Examples: * (Note: Comments here are written in markdown syntax, so there is an * additional layer of backticks to represent a code block) * `\`address.city\`` represents a field named `address.city`, not the map key * `city` in the field `address`. * `\`&#42;\`` represents a field named `&#42;`, not any field. * * A special `Field` contains the default indexing settings for all fields. * This field's resource name is: * `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/&#42;` * Indexes defined on this `Field` will be applied to all fields which do not * have their own `Field` index configuration. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** * A mask, relative to the field. If specified, only configuration specified * by this field_mask will be updated in the field. */ 'updateMask'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': GoogleFirestoreAdminV1Field; }): Request<GoogleLongrunningOperation>; patch( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * A field name of the form * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/fields/{field_path}` * * A field path may be a simple field name, e.g. `address` or a path to fields * within map_value , e.g. `address.city`, * or a special field path. The only valid special field is `&#42;`, which * represents any field. * * Field paths may be quoted using ` (backtick). The only character that needs * to be escaped within a quoted field path is the backtick character itself, * escaped using a backslash. Special characters in field paths that * must be quoted include: `&#42;`, `.`, * ``` (backtick), `[`, `]`, as well as any ascii symbolic characters. * * Examples: * (Note: Comments here are written in markdown syntax, so there is an * additional layer of backticks to represent a code block) * `\`address.city\`` represents a field named `address.city`, not the map key * `city` in the field `address`. * `\`&#42;\`` represents a field named `&#42;`, not any field. * * A special `Field` contains the default indexing settings for all fields. * This field's resource name is: * `projects/{project_id}/databases/{database_id}/collectionGroups/__default__/fields/&#42;` * Indexes defined on this `Field` will be applied to all fields which do not * have their own `Field` index configuration. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** * A mask, relative to the field. If specified, only configuration specified * by this field_mask will be updated in the field. */ 'updateMask'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: GoogleFirestoreAdminV1Field ): Request<GoogleLongrunningOperation>; } // tslint:disable-next-line:interface-name interface IndexesResource { /** * Creates a composite index. This returns a google.longrunning.Operation * which may be used to track the status of the creation. The metadata for * the operation will be the type IndexOperationMetadata. */ create(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** * Required. A parent name of the form * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` */ 'parent': string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': GoogleFirestoreAdminV1Index; }): Request<GoogleLongrunningOperation>; create( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** * Required. A parent name of the form * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` */ 'parent': string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: GoogleFirestoreAdminV1Index ): Request<GoogleLongrunningOperation>; /** Deletes a composite index. */ delete(request?: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * Required. A name of the form * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }): Request<{}>; /** Gets a composite index. */ get(request?: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * Required. A name of the form * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}/indexes/{index_id}` */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }): Request<GoogleFirestoreAdminV1Index>; /** Lists composite indexes. */ list(request?: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** The filter to apply to list results. */ 'filter'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** The number of results to return. */ 'pageSize'?: number; /** * A page token, returned from a previous call to * FirestoreAdmin.ListIndexes, that may be used to get the next * page of results. */ 'pageToken'?: string; /** * Required. A parent name of the form * `projects/{project_id}/databases/{database_id}/collectionGroups/{collection_id}` */ 'parent': string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }): Request<GoogleFirestoreAdminV1ListIndexesResponse>; } interface CollectionGroupsResource { fields: FieldsResource; indexes: IndexesResource; } interface DocumentsResource { /** * Gets multiple documents. * * Documents returned by this method are not guaranteed to be returned in the * same order that they were requested. */ batchGet(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ 'database': string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': BatchGetDocumentsRequest; }): Request<BatchGetDocumentsResponse>; batchGet( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ 'database': string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: BatchGetDocumentsRequest ): Request<BatchGetDocumentsResponse>; /** Starts a new transaction. */ beginTransaction(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ 'database': string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': BeginTransactionRequest; }): Request<BeginTransactionResponse>; beginTransaction( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ 'database': string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: BeginTransactionRequest ): Request<BeginTransactionResponse>; /** Commits a transaction, while optionally updating documents. */ commit(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ 'database': string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': CommitRequest; }): Request<CommitResponse>; commit( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ 'database': string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: CommitRequest ): Request<CommitResponse>; /** Creates a new document. */ createDocument(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`. */ 'collectionId': string; /** * The client-assigned document ID to use for this document. * * Optional. If not specified, an ID will be assigned by the service. */ 'documentId'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ 'mask.fieldPaths'?: string | string[]; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** * Required. The parent resource. For example: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` */ 'parent': string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': Document; }): Request<Document>; createDocument( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Required. The collection ID, relative to `parent`, to list. For example: `chatrooms`. */ 'collectionId': string; /** * The client-assigned document ID to use for this document. * * Optional. If not specified, an ID will be assigned by the service. */ 'documentId'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ 'mask.fieldPaths'?: string | string[]; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** * Required. The parent resource. For example: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` */ 'parent': string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: Document ): Request<Document>; /** Deletes a document. */ delete(request?: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * When set to `true`, the target document must exist. * When set to `false`, the target document must not exist. */ 'currentDocument.exists'?: boolean; /** * When set, the target document must exist and have been last updated at * that time. */ 'currentDocument.updateTime'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * Required. The resource name of the Document to delete. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }): Request<{}>; /** Gets a single document. */ get(request?: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ 'mask.fieldPaths'?: string | string[]; /** * Required. The resource name of the Document to get. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** * Reads the version of the document at the given time. * This may not be older than 270 seconds. */ 'readTime'?: string; /** Reads the document in a transaction. */ 'transaction'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }): Request<Document>; /** Lists documents. */ list(request?: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * Required. The collection ID, relative to `parent`, to list. For example: `chatrooms` * or `messages`. */ 'collectionId': string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ 'mask.fieldPaths'?: string | string[]; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** The order to sort results by. For example: `priority desc, name`. */ 'orderBy'?: string; /** The maximum number of documents to return. */ 'pageSize'?: number; /** The `next_page_token` value returned from a previous List request, if any. */ 'pageToken'?: string; /** * Required. The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` */ 'parent': string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** * Reads documents as they were at the given time. * This may not be older than 270 seconds. */ 'readTime'?: string; /** * If the list should show missing documents. A missing document is a * document that does not exist but has sub-documents. These documents will * be returned with a key but will not have fields, Document.create_time, * or Document.update_time set. * * Requests with `show_missing` may not specify `where` or * `order_by`. */ 'showMissing'?: boolean; /** Reads documents in a transaction. */ 'transaction'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }): Request<ListDocumentsResponse>; /** Lists all the collection IDs underneath a document. */ listCollectionIds(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** * Required. The parent document. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` */ 'parent': string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': ListCollectionIdsRequest; }): Request<ListCollectionIdsResponse>; listCollectionIds( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** * Required. The parent document. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` */ 'parent': string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: ListCollectionIdsRequest ): Request<ListCollectionIdsResponse>; /** Listens to changes. */ listen(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ 'database': string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': ListenRequest; }): Request<ListenResponse>; listen( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ 'database': string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: ListenRequest ): Request<ListenResponse>; /** Updates or inserts a document. */ patch(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * When set to `true`, the target document must exist. * When set to `false`, the target document must not exist. */ 'currentDocument.exists'?: boolean; /** * When set, the target document must exist and have been last updated at * that time. */ 'currentDocument.updateTime'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ 'mask.fieldPaths'?: string | string[]; /** * The resource name of the document, for example * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ 'updateMask.fieldPaths'?: string | string[]; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': Document; }): Request<Document>; patch( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * When set to `true`, the target document must exist. * When set to `false`, the target document must not exist. */ 'currentDocument.exists'?: boolean; /** * When set, the target document must exist and have been last updated at * that time. */ 'currentDocument.updateTime'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ 'mask.fieldPaths'?: string | string[]; /** * The resource name of the document, for example * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ 'updateMask.fieldPaths'?: string | string[]; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: Document ): Request<Document>; /** Rolls back a transaction. */ rollback(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ 'database': string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': RollbackRequest; }): Request<{}>; rollback( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ 'database': string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: RollbackRequest ): Request<{}>; /** Runs a query. */ runQuery(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** * Required. The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` */ 'parent': string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': RunQueryRequest; }): Request<RunQueryResponse>; runQuery( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** * Required. The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` */ 'parent': string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: RunQueryRequest ): Request<RunQueryResponse>; /** Streams batches of document updates and deletes, in order. */ write(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. * This is only required in the first message. */ 'database': string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': WriteRequest; }): Request<WriteResponse>; write( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** * Required. The database name. In the format: * `projects/{project_id}/databases/{database_id}`. * This is only required in the first message. */ 'database': string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: WriteRequest ): Request<WriteResponse>; } interface OperationsResource { /** * Starts asynchronous cancellation on a long-running operation. The server * makes a best effort to cancel the operation, but success is not * guaranteed. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. Clients can use * Operations.GetOperation or * other methods to check whether the cancellation succeeded or whether the * operation completed despite cancellation. On successful cancellation, * the operation is not deleted; instead, it becomes an operation with * an Operation.error value with a google.rpc.Status.code of 1, * corresponding to `Code.CANCELLED`. */ cancel(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** The name of the operation resource to be cancelled. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': GoogleLongrunningCancelOperationRequest; }): Request<{}>; cancel( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** The name of the operation resource to be cancelled. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: GoogleLongrunningCancelOperationRequest ): Request<{}>; /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the * operation. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. */ delete(request?: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** The name of the operation resource to be deleted. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }): Request<{}>; /** * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. */ get(request?: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** The name of the operation resource. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }): Request<GoogleLongrunningOperation>; /** * Lists operations that match the specified filter in the request. If the * server doesn't support this method, it returns `UNIMPLEMENTED`. * * NOTE: the `name` binding allows API services to override the binding * to use different resource name schemes, such as `users/&#42;/operations`. To * override the binding, API services can add a binding such as * `"/v1/{name=users/&#42;}/operations"` to their service configuration. * For backwards compatibility, the default name includes the operations * collection id, however overriding users must ensure the name binding * is the parent resource, without the operations collection id. */ list(request?: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** The standard list filter. */ 'filter'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** The name of the operation's parent resource. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** The standard list page size. */ 'pageSize'?: number; /** The standard list page token. */ 'pageToken'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }): Request<GoogleLongrunningListOperationsResponse>; } interface DatabasesResource { /** * Exports a copy of all or a subset of documents from Google Cloud Firestore * to another storage system, such as Google Cloud Storage. Recent updates to * documents may not be reflected in the export. The export occurs in the * background and its progress can be monitored and managed via the * Operation resource that is created. The output of an export may only be * used once the associated operation is done. If an export operation is * cancelled before completion it may leave partial data behind in Google * Cloud Storage. */ exportDocuments(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * Required. Database to export. Should be of the form: * `projects/{project_id}/databases/{database_id}`. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': GoogleFirestoreAdminV1ExportDocumentsRequest; }): Request<GoogleLongrunningOperation>; exportDocuments( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * Required. Database to export. Should be of the form: * `projects/{project_id}/databases/{database_id}`. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: GoogleFirestoreAdminV1ExportDocumentsRequest ): Request<GoogleLongrunningOperation>; /** * Imports documents into Google Cloud Firestore. Existing documents with the * same name are overwritten. The import occurs in the background and its * progress can be monitored and managed via the Operation resource that is * created. If an ImportDocuments operation is cancelled, it is possible * that a subset of the data has already been imported to Cloud Firestore. */ importDocuments(request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * Required. Database to import into. Should be of the form: * `projects/{project_id}/databases/{database_id}`. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; /** Request body */ 'resource': GoogleFirestoreAdminV1ImportDocumentsRequest; }): Request<GoogleLongrunningOperation>; importDocuments( request: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** * Required. Database to import into. Should be of the form: * `projects/{project_id}/databases/{database_id}`. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }, body: GoogleFirestoreAdminV1ImportDocumentsRequest ): Request<GoogleLongrunningOperation>; collectionGroups: CollectionGroupsResource; documents: DocumentsResource; operations: OperationsResource; } interface LocationsResource { /** Gets information about a location. */ get(request?: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** Resource name for the location. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }): Request<Location>; /** Lists information about the supported locations for this service. */ list(request?: { /** V1 error format. */ '$.xgafv'?: string; /** OAuth access token. */ 'access_token'?: string; /** Data format for response. */ 'alt'?: string; /** JSONP */ 'callback'?: string; /** Selector specifying which fields to include in a partial response. */ 'fields'?: string; /** The standard list filter. */ 'filter'?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ 'key'?: string; /** The resource that owns the locations collection, if applicable. */ 'name': string; /** OAuth 2.0 token for the current user. */ 'oauth_token'?: string; /** The standard list page size. */ 'pageSize'?: number; /** The standard list page token. */ 'pageToken'?: string; /** Returns response with indentations and line breaks. */ 'prettyPrint'?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ 'quotaUser'?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ 'upload_protocol'?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ 'uploadType'?: string; }): Request<ListLocationsResponse>; } interface ProjectsResource { databases: DatabasesResource; locations: LocationsResource; } const projects: ProjectsResource; } }
the_stack
///////////////////////////// /// ECMAScript APIs ///////////////////////////// declare const NaN: number; declare const Infinity: number; declare function eval(x: string): any; declare function parseInt(s: string, radix?: number): number; declare function parseFloat(string: string): number; declare function isNaN(number: number): boolean; declare function isFinite(number: number): boolean; declare function decodeURI(encodedURI: string): string; declare function decodeURIComponent(encodedURIComponent: string): string; declare function encodeURI(uri: string): string; declare function encodeURIComponent(uriComponent: string): string; interface PropertyDescriptor { configurable?: boolean; enumerable?: boolean; value?: any; writable?: boolean; get?(): any; set?(v: any): void; } interface PropertyDescriptorMap { [s: string]: PropertyDescriptor; } interface Object { constructor: Function; toString(): string; toLocaleString(): string; valueOf(): Object; hasOwnProperty(v: string): boolean; isPrototypeOf(v: Object): boolean; propertyIsEnumerable(v: string): boolean; } interface ObjectConstructor { new(value?: any): Object; (): any; (value: any): any; readonly prototype: Object; getPrototypeOf(o: any): any; getOwnPropertyDescriptor(o: any, p: string): PropertyDescriptor | undefined; getOwnPropertyNames(o: any): string[]; create(o: object | null): any; create(o: object | null, properties: PropertyDescriptorMap & ThisType<any>): any; defineProperty(o: any, p: string, attributes: PropertyDescriptor & ThisType<any>): any; defineProperties(o: any, properties: PropertyDescriptorMap & ThisType<any>): any; seal<T>(o: T): T; freeze<T>(a: T[]): ReadonlyArray<T>; freeze<T extends Function>(f: T): T; freeze<T>(o: T): Readonly<T>; preventExtensions<T>(o: T): T; isSealed(o: any): boolean; isFrozen(o: any): boolean; isExtensible(o: any): boolean; keys(o: {}): string[]; } declare const Object: ObjectConstructor; interface Function { apply(this: Function, thisArg: any, argArray?: any): any; call(this: Function, thisArg: any, ...argArray: any[]): any; bind(this: Function, thisArg: any, ...argArray: any[]): any; toString(): string; prototype: any; readonly length: number; // Non-standard extensions arguments: any; caller: Function; } interface FunctionConstructor { new(...args: string[]): Function; (...args: string[]): Function; readonly prototype: Function; } declare const Function: FunctionConstructor; interface IArguments { [index: number]: any; length: number; callee: Function; } interface String { toString(): string; charAt(pos: number): string; charCodeAt(index: number): number; concat(...strings: string[]): string; indexOf(searchString: string, position?: number): number; lastIndexOf(searchString: string, position?: number): number; localeCompare(that: string): number; match(regexp: string | RegExp): RegExpMatchArray | null; replace(searchValue: string | RegExp, replaceValue: string): string; replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string; search(regexp: string | RegExp): number; slice(start?: number, end?: number): string; split(separator: string | RegExp, limit?: number): string[]; substring(start: number, end?: number): string; toLowerCase(): string; toLocaleLowerCase(): string; toUpperCase(): string; toLocaleUpperCase(): string; trim(): string; readonly length: number; // IE extensions substr(from: number, length?: number): string; valueOf(): string; readonly [index: number]: string; } interface StringConstructor { new(value?: any): String; (value?: any): string; readonly prototype: String; fromCharCode(...codes: number[]): string; } declare const String: StringConstructor; interface Boolean { valueOf(): boolean; } interface BooleanConstructor { new(value?: any): Boolean; (value?: any): boolean; readonly prototype: Boolean; } declare const Boolean: BooleanConstructor; interface Number { toString(radix?: number): string; toFixed(fractionDigits?: number): string; toExponential(fractionDigits?: number): string; toPrecision(precision?: number): string; valueOf(): number; } interface NumberConstructor { new(value?: any): Number; (value?: any): number; readonly prototype: Number; readonly MAX_VALUE: number; readonly MIN_VALUE: number; readonly NaN: number; readonly NEGATIVE_INFINITY: number; readonly POSITIVE_INFINITY: number; } declare const Number: NumberConstructor; interface TemplateStringsArray extends ReadonlyArray<string> { readonly raw: ReadonlyArray<string>; } interface Math { readonly E: number; readonly LN10: number; readonly LN2: number; readonly LOG2E: number; readonly LOG10E: number; readonly PI: number; readonly SQRT1_2: number; readonly SQRT2: number; abs(x: number): number; acos(x: number): number; asin(x: number): number; atan(x: number): number; atan2(y: number, x: number): number; ceil(x: number): number; cos(x: number): number; exp(x: number): number; floor(x: number): number; log(x: number): number; max(...values: number[]): number; min(...values: number[]): number; pow(x: number, y: number): number; random(): number; round(x: number): number; sin(x: number): number; sqrt(x: number): number; tan(x: number): number; } declare const Math: Math; interface Date { toString(): string; toDateString(): string; toTimeString(): string; toLocaleString(): string; toLocaleDateString(): string; toLocaleTimeString(): string; valueOf(): number; getTime(): number; getFullYear(): number; getUTCFullYear(): number; getMonth(): number; getUTCMonth(): number; getDate(): number; getUTCDate(): number; getDay(): number; getUTCDay(): number; getHours(): number; getUTCHours(): number; getMinutes(): number; getUTCMinutes(): number; getSeconds(): number; getUTCSeconds(): number; getMilliseconds(): number; getUTCMilliseconds(): number; getTimezoneOffset(): number; setTime(time: number): number; setMilliseconds(ms: number): number; setUTCMilliseconds(ms: number): number; setSeconds(sec: number, ms?: number): number; setUTCSeconds(sec: number, ms?: number): number; setMinutes(min: number, sec?: number, ms?: number): number; setUTCMinutes(min: number, sec?: number, ms?: number): number; setHours(hours: number, min?: number, sec?: number, ms?: number): number; setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; setDate(date: number): number; setUTCDate(date: number): number; setMonth(month: number, date?: number): number; setUTCMonth(month: number, date?: number): number; setFullYear(year: number, month?: number, date?: number): number; setUTCFullYear(year: number, month?: number, date?: number): number; toUTCString(): string; toISOString(): string; toJSON(key?: any): string; } interface DateConstructor { new(): Date; new(value: number): Date; new(value: string): Date; new(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): Date; (): string; readonly prototype: Date; parse(s: string): number; UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; now(): number; } declare const Date: DateConstructor; interface RegExpMatchArray extends Array<string> { index?: number; input?: string; } interface RegExpExecArray extends Array<string> { index: number; input: string; } interface RegExp { exec(string: string): RegExpExecArray | null; test(string: string): boolean; readonly source: string; readonly global: boolean; readonly ignoreCase: boolean; readonly multiline: boolean; lastIndex: number; // Non-standard extensions compile(): this; } interface RegExpConstructor { new(pattern: RegExp | string): RegExp; new(pattern: string, flags?: string): RegExp; (pattern: RegExp | string): RegExp; (pattern: string, flags?: string): RegExp; readonly prototype: RegExp; // Non-standard extensions $1: string; $2: string; $3: string; $4: string; $5: string; $6: string; $7: string; $8: string; $9: string; lastMatch: string; } declare const RegExp: RegExpConstructor; interface Error { name: string; message: string; stack?: string; } interface ErrorConstructor { new(message?: string): Error; (message?: string): Error; readonly prototype: Error; } declare const Error: ErrorConstructor; interface EvalError extends Error { } interface EvalErrorConstructor { new(message?: string): EvalError; (message?: string): EvalError; readonly prototype: EvalError; } declare const EvalError: EvalErrorConstructor; interface RangeError extends Error { } interface RangeErrorConstructor { new(message?: string): RangeError; (message?: string): RangeError; readonly prototype: RangeError; } declare const RangeError: RangeErrorConstructor; interface ReferenceError extends Error { } interface ReferenceErrorConstructor { new(message?: string): ReferenceError; (message?: string): ReferenceError; readonly prototype: ReferenceError; } declare const ReferenceError: ReferenceErrorConstructor; interface SyntaxError extends Error { } interface SyntaxErrorConstructor { new(message?: string): SyntaxError; (message?: string): SyntaxError; readonly prototype: SyntaxError; } declare const SyntaxError: SyntaxErrorConstructor; interface TypeError extends Error { } interface TypeErrorConstructor { new(message?: string): TypeError; (message?: string): TypeError; readonly prototype: TypeError; } declare const TypeError: TypeErrorConstructor; interface URIError extends Error { } interface URIErrorConstructor { new(message?: string): URIError; (message?: string): URIError; readonly prototype: URIError; } declare const URIError: URIErrorConstructor; interface JSON { parse(text: string, reviver?: (key: any, value: any) => any): any; stringify(value: any, replacer?: (key: string, value: any) => any, space?: string | number): string; stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string; } declare const JSON: JSON; ///////////////////////////// /// ECMAScript Array API (specially handled by compiler) ///////////////////////////// interface ReadonlyArray<T> { readonly length: number; toString(): string; toLocaleString(): string; concat(...items: ReadonlyArray<T>[]): T[]; concat(...items: (T | ReadonlyArray<T>)[]): T[]; join(separator?: string): string; slice(start?: number, end?: number): T[]; indexOf(searchElement: T, fromIndex?: number): number; lastIndexOf(searchElement: T, fromIndex?: number): number; every(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg?: any): boolean; some(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => boolean, thisArg?: any): boolean; forEach(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => void, thisArg?: any): void; map<U>(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => U, thisArg?: any): U[]; filter<S extends T>(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => value is S, thisArg?: any): S[]; filter(callbackfn: (value: T, index: number, array: ReadonlyArray<T>) => any, thisArg?: any): T[]; reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray<T>) => T): T; reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray<T>) => T, initialValue: T): T; reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray<T>) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray<T>) => T): T; reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: ReadonlyArray<T>) => T, initialValue: T): T; reduceRight<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: ReadonlyArray<T>) => U, initialValue: U): U; readonly [n: number]: T; } interface Array<T> { length: number; toString(): string; toLocaleString(): string; push(...items: T[]): number; pop(): T | undefined; concat(...items: ReadonlyArray<T>[]): T[]; concat(...items: (T | ReadonlyArray<T>)[]): T[]; join(separator?: string): string; reverse(): T[]; shift(): T | undefined; slice(start?: number, end?: number): T[]; sort(compareFn?: (a: T, b: T) => number): this; splice(start: number, deleteCount?: number): T[]; splice(start: number, deleteCount: number, ...items: T[]): T[]; unshift(...items: T[]): number; indexOf(searchElement: T, fromIndex?: number): number; lastIndexOf(searchElement: T, fromIndex?: number): number; every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; filter<S extends T>(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[]; filter(callbackfn: (value: T, index: number, array: T[]) => any, thisArg?: any): T[]; reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T; reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T; reduceRight<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; [n: number]: T; } interface ArrayConstructor { new(arrayLength?: number): any[]; new <T>(arrayLength: number): T[]; new <T>(...items: T[]): T[]; (arrayLength?: number): any[]; <T>(arrayLength: number): T[]; <T>(...items: T[]): T[]; isArray(arg: any): arg is Array<any>; readonly prototype: Array<any>; } declare const Array: ArrayConstructor; interface TypedPropertyDescriptor<T> { enumerable?: boolean; configurable?: boolean; writable?: boolean; value?: T; get?: () => T; set?: (value: T) => void; } declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void; declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void; declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void; declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void; declare type PromiseConstructorLike = new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void) => PromiseLike<T>; interface PromiseLike<T> { then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2>; } interface Promise<T> { then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>; catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>; } interface ArrayLike<T> { readonly length: number; readonly [n: number]: T; } type Partial<T> = { [P in keyof T]?: T[P]; }; type Readonly<T> = { readonly [P in keyof T]: T[P]; }; type Pick<T, K extends keyof T> = { [P in K]: T[P]; }; type Record<K extends string, T> = { [P in K]: T; }; interface ThisType<T> { } interface ArrayBuffer { readonly byteLength: number; slice(begin: number, end?: number): ArrayBuffer; } interface ArrayBufferTypes { ArrayBuffer: ArrayBuffer; } type ArrayBufferLike = ArrayBufferTypes[keyof ArrayBufferTypes]; interface ArrayBufferConstructor { readonly prototype: ArrayBuffer; new(byteLength: number): ArrayBuffer; isView(arg: any): arg is ArrayBufferView; } declare const ArrayBuffer: ArrayBufferConstructor; interface ArrayBufferView { buffer: ArrayBufferLike; byteLength: number; byteOffset: number; } interface DataView { readonly buffer: ArrayBuffer; readonly byteLength: number; readonly byteOffset: number; getFloat32(byteOffset: number, littleEndian?: boolean): number; getFloat64(byteOffset: number, littleEndian?: boolean): number; getInt8(byteOffset: number): number; getInt16(byteOffset: number, littleEndian?: boolean): number; getInt32(byteOffset: number, littleEndian?: boolean): number; getUint8(byteOffset: number): number; getUint16(byteOffset: number, littleEndian?: boolean): number; getUint32(byteOffset: number, littleEndian?: boolean): number; setFloat32(byteOffset: number, value: number, littleEndian?: boolean): void; setFloat64(byteOffset: number, value: number, littleEndian?: boolean): void; setInt8(byteOffset: number, value: number): void; setInt16(byteOffset: number, value: number, littleEndian?: boolean): void; setInt32(byteOffset: number, value: number, littleEndian?: boolean): void; setUint8(byteOffset: number, value: number): void; setUint16(byteOffset: number, value: number, littleEndian?: boolean): void; setUint32(byteOffset: number, value: number, littleEndian?: boolean): void; } interface DataViewConstructor { new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } declare const DataView: DataViewConstructor; interface Int8Array { readonly BYTES_PER_ELEMENT: number; readonly buffer: ArrayBufferLike; readonly byteLength: number; readonly byteOffset: number; copyWithin(target: number, start: number, end?: number): this; every(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; fill(value: number, start?: number, end?: number): this; filter(callbackfn: (value: number, index: number, array: Int8Array) => any, thisArg?: any): Int8Array; find(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number | undefined; findIndex(predicate: (value: number, index: number, obj: Int8Array) => boolean, thisArg?: any): number; forEach(callbackfn: (value: number, index: number, array: Int8Array) => void, thisArg?: any): void; indexOf(searchElement: number, fromIndex?: number): number; join(separator?: string): string; lastIndexOf(searchElement: number, fromIndex?: number): number; readonly length: number; map(callbackfn: (value: number, index: number, array: Int8Array) => number, thisArg?: any): Int8Array; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number): number; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int8Array) => number, initialValue: number): number; reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int8Array) => U, initialValue: U): U; reverse(): Int8Array; set(array: ArrayLike<number>, offset?: number): void; slice(start?: number, end?: number): Int8Array; some(callbackfn: (value: number, index: number, array: Int8Array) => boolean, thisArg?: any): boolean; sort(compareFn?: (a: number, b: number) => number): this; subarray(begin: number, end?: number): Int8Array; toLocaleString(): string; toString(): string; [index: number]: number; } interface Int8ArrayConstructor { readonly prototype: Int8Array; new(length: number): Int8Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Int8Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int8Array; readonly BYTES_PER_ELEMENT: number; of(...items: number[]): Int8Array; from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array; } declare const Int8Array: Int8ArrayConstructor; interface Uint8Array { readonly BYTES_PER_ELEMENT: number; readonly buffer: ArrayBufferLike; readonly byteLength: number; readonly byteOffset: number; copyWithin(target: number, start: number, end?: number): this; every(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; fill(value: number, start?: number, end?: number): this; filter(callbackfn: (value: number, index: number, array: Uint8Array) => any, thisArg?: any): Uint8Array; find(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number | undefined; findIndex(predicate: (value: number, index: number, obj: Uint8Array) => boolean, thisArg?: any): number; forEach(callbackfn: (value: number, index: number, array: Uint8Array) => void, thisArg?: any): void; indexOf(searchElement: number, fromIndex?: number): number; join(separator?: string): string; lastIndexOf(searchElement: number, fromIndex?: number): number; readonly length: number; map(callbackfn: (value: number, index: number, array: Uint8Array) => number, thisArg?: any): Uint8Array; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number): number; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8Array) => number, initialValue: number): number; reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8Array) => U, initialValue: U): U; reverse(): Uint8Array; set(array: ArrayLike<number>, offset?: number): void; slice(start?: number, end?: number): Uint8Array; some(callbackfn: (value: number, index: number, array: Uint8Array) => boolean, thisArg?: any): boolean; sort(compareFn?: (a: number, b: number) => number): this; subarray(begin: number, end?: number): Uint8Array; toLocaleString(): string; toString(): string; [index: number]: number; } interface Uint8ArrayConstructor { readonly prototype: Uint8Array; new(length: number): Uint8Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Uint8Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8Array; readonly BYTES_PER_ELEMENT: number; of(...items: number[]): Uint8Array; from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array; } declare const Uint8Array: Uint8ArrayConstructor; interface Uint8ClampedArray { readonly BYTES_PER_ELEMENT: number; readonly buffer: ArrayBufferLike; readonly byteLength: number; readonly byteOffset: number; copyWithin(target: number, start: number, end?: number): this; every(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; fill(value: number, start?: number, end?: number): this; filter(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => any, thisArg?: any): Uint8ClampedArray; find(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number | undefined; findIndex(predicate: (value: number, index: number, obj: Uint8ClampedArray) => boolean, thisArg?: any): number; forEach(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => void, thisArg?: any): void; indexOf(searchElement: number, fromIndex?: number): number; join(separator?: string): string; lastIndexOf(searchElement: number, fromIndex?: number): number; readonly length: number; map(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => number, thisArg?: any): Uint8ClampedArray; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number): number; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => number, initialValue: number): number; reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint8ClampedArray) => U, initialValue: U): U; reverse(): Uint8ClampedArray; set(array: ArrayLike<number>, offset?: number): void; slice(start?: number, end?: number): Uint8ClampedArray; some(callbackfn: (value: number, index: number, array: Uint8ClampedArray) => boolean, thisArg?: any): boolean; sort(compareFn?: (a: number, b: number) => number): this; subarray(begin: number, end?: number): Uint8ClampedArray; toLocaleString(): string; toString(): string; [index: number]: number; } interface Uint8ClampedArrayConstructor { readonly prototype: Uint8ClampedArray; new(length: number): Uint8ClampedArray; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Uint8ClampedArray; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint8ClampedArray; readonly BYTES_PER_ELEMENT: number; of(...items: number[]): Uint8ClampedArray; from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray; } declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; interface Int16Array { readonly BYTES_PER_ELEMENT: number; readonly buffer: ArrayBufferLike; readonly byteLength: number; readonly byteOffset: number; copyWithin(target: number, start: number, end?: number): this; every(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; fill(value: number, start?: number, end?: number): this; filter(callbackfn: (value: number, index: number, array: Int16Array) => any, thisArg?: any): Int16Array; find(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number | undefined; findIndex(predicate: (value: number, index: number, obj: Int16Array) => boolean, thisArg?: any): number; forEach(callbackfn: (value: number, index: number, array: Int16Array) => void, thisArg?: any): void; indexOf(searchElement: number, fromIndex?: number): number; join(separator?: string): string; lastIndexOf(searchElement: number, fromIndex?: number): number; readonly length: number; map(callbackfn: (value: number, index: number, array: Int16Array) => number, thisArg?: any): Int16Array; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number): number; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int16Array) => number, initialValue: number): number; reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int16Array) => U, initialValue: U): U; reverse(): Int16Array; set(array: ArrayLike<number>, offset?: number): void; slice(start?: number, end?: number): Int16Array; some(callbackfn: (value: number, index: number, array: Int16Array) => boolean, thisArg?: any): boolean; sort(compareFn?: (a: number, b: number) => number): this; subarray(begin: number, end?: number): Int16Array; toLocaleString(): string; toString(): string; [index: number]: number; } interface Int16ArrayConstructor { readonly prototype: Int16Array; new(length: number): Int16Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Int16Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int16Array; readonly BYTES_PER_ELEMENT: number; of(...items: number[]): Int16Array; from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array; } declare const Int16Array: Int16ArrayConstructor; interface Uint16Array { readonly BYTES_PER_ELEMENT: number; readonly buffer: ArrayBufferLike; readonly byteLength: number; readonly byteOffset: number; copyWithin(target: number, start: number, end?: number): this; every(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; fill(value: number, start?: number, end?: number): this; filter(callbackfn: (value: number, index: number, array: Uint16Array) => any, thisArg?: any): Uint16Array; find(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number | undefined; findIndex(predicate: (value: number, index: number, obj: Uint16Array) => boolean, thisArg?: any): number; forEach(callbackfn: (value: number, index: number, array: Uint16Array) => void, thisArg?: any): void; indexOf(searchElement: number, fromIndex?: number): number; join(separator?: string): string; lastIndexOf(searchElement: number, fromIndex?: number): number; readonly length: number; map(callbackfn: (value: number, index: number, array: Uint16Array) => number, thisArg?: any): Uint16Array; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number): number; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint16Array) => number, initialValue: number): number; reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint16Array) => U, initialValue: U): U; reverse(): Uint16Array; set(array: ArrayLike<number>, offset?: number): void; slice(start?: number, end?: number): Uint16Array; some(callbackfn: (value: number, index: number, array: Uint16Array) => boolean, thisArg?: any): boolean; sort(compareFn?: (a: number, b: number) => number): this; subarray(begin: number, end?: number): Uint16Array; toLocaleString(): string; toString(): string; [index: number]: number; } interface Uint16ArrayConstructor { readonly prototype: Uint16Array; new(length: number): Uint16Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Uint16Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint16Array; readonly BYTES_PER_ELEMENT: number; of(...items: number[]): Uint16Array; from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array; } declare const Uint16Array: Uint16ArrayConstructor; interface Int32Array { readonly BYTES_PER_ELEMENT: number; readonly buffer: ArrayBufferLike; readonly byteLength: number; readonly byteOffset: number; copyWithin(target: number, start: number, end?: number): this; every(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; fill(value: number, start?: number, end?: number): this; filter(callbackfn: (value: number, index: number, array: Int32Array) => any, thisArg?: any): Int32Array; find(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number | undefined; findIndex(predicate: (value: number, index: number, obj: Int32Array) => boolean, thisArg?: any): number; forEach(callbackfn: (value: number, index: number, array: Int32Array) => void, thisArg?: any): void; indexOf(searchElement: number, fromIndex?: number): number; join(separator?: string): string; lastIndexOf(searchElement: number, fromIndex?: number): number; readonly length: number; map(callbackfn: (value: number, index: number, array: Int32Array) => number, thisArg?: any): Int32Array; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number): number; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Int32Array) => number, initialValue: number): number; reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Int32Array) => U, initialValue: U): U; reverse(): Int32Array; set(array: ArrayLike<number>, offset?: number): void; slice(start?: number, end?: number): Int32Array; some(callbackfn: (value: number, index: number, array: Int32Array) => boolean, thisArg?: any): boolean; sort(compareFn?: (a: number, b: number) => number): this; subarray(begin: number, end?: number): Int32Array; toLocaleString(): string; toString(): string; [index: number]: number; } interface Int32ArrayConstructor { readonly prototype: Int32Array; new(length: number): Int32Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Int32Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Int32Array; readonly BYTES_PER_ELEMENT: number; of(...items: number[]): Int32Array; from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array; } declare const Int32Array: Int32ArrayConstructor; interface Uint32Array { readonly BYTES_PER_ELEMENT: number; readonly buffer: ArrayBufferLike; readonly byteLength: number; readonly byteOffset: number; copyWithin(target: number, start: number, end?: number): this; every(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; fill(value: number, start?: number, end?: number): this; filter(callbackfn: (value: number, index: number, array: Uint32Array) => any, thisArg?: any): Uint32Array; find(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number | undefined; findIndex(predicate: (value: number, index: number, obj: Uint32Array) => boolean, thisArg?: any): number; forEach(callbackfn: (value: number, index: number, array: Uint32Array) => void, thisArg?: any): void; indexOf(searchElement: number, fromIndex?: number): number; join(separator?: string): string; lastIndexOf(searchElement: number, fromIndex?: number): number; readonly length: number; map(callbackfn: (value: number, index: number, array: Uint32Array) => number, thisArg?: any): Uint32Array; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number): number; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Uint32Array) => number, initialValue: number): number; reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Uint32Array) => U, initialValue: U): U; reverse(): Uint32Array; set(array: ArrayLike<number>, offset?: number): void; slice(start?: number, end?: number): Uint32Array; some(callbackfn: (value: number, index: number, array: Uint32Array) => boolean, thisArg?: any): boolean; sort(compareFn?: (a: number, b: number) => number): this; subarray(begin: number, end?: number): Uint32Array; toLocaleString(): string; toString(): string; [index: number]: number; } interface Uint32ArrayConstructor { readonly prototype: Uint32Array; new(length: number): Uint32Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Uint32Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Uint32Array; readonly BYTES_PER_ELEMENT: number; of(...items: number[]): Uint32Array; from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array; } declare const Uint32Array: Uint32ArrayConstructor; interface Float32Array { readonly BYTES_PER_ELEMENT: number; readonly buffer: ArrayBufferLike; readonly byteLength: number; readonly byteOffset: number; copyWithin(target: number, start: number, end?: number): this; every(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; fill(value: number, start?: number, end?: number): this; filter(callbackfn: (value: number, index: number, array: Float32Array) => any, thisArg?: any): Float32Array; find(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number | undefined; findIndex(predicate: (value: number, index: number, obj: Float32Array) => boolean, thisArg?: any): number; forEach(callbackfn: (value: number, index: number, array: Float32Array) => void, thisArg?: any): void; indexOf(searchElement: number, fromIndex?: number): number; join(separator?: string): string; lastIndexOf(searchElement: number, fromIndex?: number): number; readonly length: number; map(callbackfn: (value: number, index: number, array: Float32Array) => number, thisArg?: any): Float32Array; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number): number; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float32Array) => number, initialValue: number): number; reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float32Array) => U, initialValue: U): U; reverse(): Float32Array; set(array: ArrayLike<number>, offset?: number): void; slice(start?: number, end?: number): Float32Array; some(callbackfn: (value: number, index: number, array: Float32Array) => boolean, thisArg?: any): boolean; sort(compareFn?: (a: number, b: number) => number): this; subarray(begin: number, end?: number): Float32Array; toLocaleString(): string; toString(): string; [index: number]: number; } interface Float32ArrayConstructor { readonly prototype: Float32Array; new(length: number): Float32Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Float32Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float32Array; readonly BYTES_PER_ELEMENT: number; of(...items: number[]): Float32Array; from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array; } declare const Float32Array: Float32ArrayConstructor; interface Float64Array { readonly BYTES_PER_ELEMENT: number; readonly buffer: ArrayBufferLike; readonly byteLength: number; readonly byteOffset: number; copyWithin(target: number, start: number, end?: number): this; every(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; fill(value: number, start?: number, end?: number): this; filter(callbackfn: (value: number, index: number, array: Float64Array) => any, thisArg?: any): Float64Array; find(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number | undefined; findIndex(predicate: (value: number, index: number, obj: Float64Array) => boolean, thisArg?: any): number; forEach(callbackfn: (value: number, index: number, array: Float64Array) => void, thisArg?: any): void; indexOf(searchElement: number, fromIndex?: number): number; join(separator?: string): string; lastIndexOf(searchElement: number, fromIndex?: number): number; readonly length: number; map(callbackfn: (value: number, index: number, array: Float64Array) => number, thisArg?: any): Float64Array; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; reduce<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number): number; reduceRight(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: Float64Array) => number, initialValue: number): number; reduceRight<U>(callbackfn: (previousValue: U, currentValue: number, currentIndex: number, array: Float64Array) => U, initialValue: U): U; reverse(): Float64Array; set(array: ArrayLike<number>, offset?: number): void; slice(start?: number, end?: number): Float64Array; some(callbackfn: (value: number, index: number, array: Float64Array) => boolean, thisArg?: any): boolean; sort(compareFn?: (a: number, b: number) => number): this; subarray(begin: number, end?: number): Float64Array; toLocaleString(): string; toString(): string; [index: number]: number; } interface Float64ArrayConstructor { readonly prototype: Float64Array; new(length: number): Float64Array; new(arrayOrArrayBuffer: ArrayLike<number> | ArrayBufferLike): Float64Array; new(buffer: ArrayBufferLike, byteOffset: number, length?: number): Float64Array; readonly BYTES_PER_ELEMENT: number; of(...items: number[]): Float64Array; from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array; } declare const Float64Array: Float64ArrayConstructor;
the_stack
import { TextEditor, Grammar } from "atom"; import * as path from "path"; import { promises } from "fs"; const { readFile } = promises; import type { HydrogenCellType } from "./hydrogen"; import { remote } from "electron"; const { dialog } = remote; import { fromJS } from "@nteract/commutable"; import type { Notebook, JSONObject, Cell } from "@nteract/commutable"; import store from "./store"; import { getCommentStartString } from "./code-manager"; import { importResult, convertMarkdownToOutput } from "./result"; const linesep = process.platform === "win32" ? "\r\n" : "\n"; /** * Determines if the provided uri is a valid file for Hydrogen to import. Then * it loads the notebook. * * @param {String} uri - Uri of the file to open. */ export function ipynbOpener(uri: string) { if ( path.extname(uri).toLowerCase() === ".ipynb" && atom.config.get("Hydrogen.importNotebookURI") === true ) { return _loadNotebook( uri, atom.config.get("Hydrogen.importNotebookResults") ); } } /** * Determines if the provided event is trying to open a valid file for Hydrogen * to import. Otherwise it will ask the user to chose a valid file for Hydrogen * to import. Then it loads the notebook. * * @param {Event} event - Atom Event from clicking in a treeview. */ export function importNotebook(event?: CustomEvent) { // Use selected filepath if called from tree-view context menu const filenameFromTreeView = event.target.dataset?.path; if (filenameFromTreeView && path.extname(filenameFromTreeView) === ".ipynb") { return _loadNotebook( filenameFromTreeView, atom.config.get("Hydrogen.importNotebookResults") ); } dialog.showOpenDialog( { properties: ["openFile"], filters: [ { name: "Notebooks", extensions: ["ipynb"], }, ], }, (filenames: Array<string> | null | undefined) => { if (!filenames) { atom.notifications.addError("No filenames selected"); return; } const filename = filenames[0]; if (path.extname(filename) !== ".ipynb") { atom.notifications.addError("Selected file must have extension .ipynb"); return; } _loadNotebook( filename, atom.config.get("Hydrogen.importNotebookResults") ); } ); } /** * Reads the given notebook file and coverts it to a text editor format with * Hydrogen cell breakpoints. Optionally after opening the notebook, it will * also load the previous results and display them. * * @param {String} filename - Path of the file. * @param {Boolean} importResults - Decides whether to display previous results */ export async function _loadNotebook( filename: string, importResults: boolean = false ) { let data; let nb; try { data = JSON.parse(await readFile(filename, { encoding: "utf-8" })); if (data.nbformat < 3) { atom.notifications.addError("Only notebook version 4 is fully supported"); return; } else if (data.nbformat == 3) { atom.notifications.addWarning( "Only notebook version 4 is fully supported" ); } nb = fromJS(data); } catch (err) { if (err.name === "SyntaxError") { atom.notifications.addError("Error not a valid notebook", { detail: err.stack, }); } else { atom.notifications.addError("Error reading file", { detail: err, }); } return; } const editor = await atom.workspace.open(); const grammar = getGrammarForNotebook(nb); if (!grammar) { return; } atom.grammars.assignLanguageMode(editor.getBuffer(), grammar.scopeName); const commentStartString = getCommentStartString(editor); if (!commentStartString) { atom.notifications.addError("No comment symbol defined in root scope"); return; } const nbCells = []; const sources = []; const resultRows = []; let previousBreakpoint = -1; nb.cellOrder.forEach((value) => { const cell = nb.cellMap.get(value).toJS(); nbCells.push(cell); const hyCell = toHydrogenCodeBlock(cell, `${commentStartString} `); resultRows.push(previousBreakpoint + hyCell.code.trim().split("\n").length); previousBreakpoint += hyCell.row; sources.push(hyCell.code); }); editor.setText(sources.join(linesep)); if (importResults) { importNotebookResults(editor, nbCells, resultRows); } } /** * Tries to determine the Atom Grammar of a notebook. Default is Python. * * @param {Notebook} nb - The Notebook to determine the Atom Grammar of. * @returns {Grammar} - The grammar of the notebook. */ function getGrammarForNotebook(nb: Notebook) { const metaData = nb.metadata; const { kernelspec, // Offical nbformat v4 language_info, // Offical nbformat v4 kernel_info, // Sometimes used in nbformat v3 language, // Sometimes used in nbformat v3 } = typeof metaData.toJS === "function" ? metaData.toJS() : metaData; // TODO fix toJS const kernel = kernelspec ? kernelspec : kernel_info; const lang = language_info ? language_info : language ? { name: language, } : null; if (!kernel && !lang) { atom.notifications.addWarning( "No language metadata in notebook; assuming Python" ); return atom.grammars.grammarForScopeName("source.python"); } let matchedGrammar = null; if (lang) { // lang.name should be required matchedGrammar = getGrammarForLanguageName(lang.name); if (matchedGrammar) { return matchedGrammar; } // lang.file_extension is not required, but if lang.name retrieves no match, // this is the next best thing. if (lang.file_extension) { matchedGrammar = getGrammarForFileExtension(lang.file_extension); } if (matchedGrammar) { return matchedGrammar; } } if (kernel) { // kernel.language is not required, but its often more accurate than name matchedGrammar = getGrammarForLanguageName(kernel.language); if (matchedGrammar) { return matchedGrammar; } // kernel.name should be required, but is often a kernel name, so its hard // to match effciently matchedGrammar = getGrammarForKernelspecName(kernel.name); if (matchedGrammar) { return matchedGrammar; } } atom.notifications.addWarning("Unable to determine correct language grammar"); return atom.grammars.grammarForScopeName("source.python"); } /** * Tries to find a matching Atom Grammar from a language name * * @param {String} name - The language name to find a grammar for. * @returns {Grammar} - The matching Atom Grammar. */ function getGrammarForLanguageName(name: string) { if (!name) { return null; } const formattedName = name.toLowerCase().replace(" ", "-"); const scopeName = `source.${formattedName}`; const grammars = atom.grammars.getGrammars(); for (const g of grammars) { if ( g && ((g.name && g.name.toLowerCase() == name.toLowerCase()) || g.scopeName == scopeName) ) { return g; } } return null; } /** * Tries to find a matching Atom Grammar from a file extensions * * @param {String} ext - The file extension to find a grammar for. * @returns {Grammar} - The matching Atom Grammar. */ function getGrammarForFileExtension(ext: string): Grammar | null | undefined { if (!ext) { return null; } ext = ext.startsWith(".") ? ext.slice(1) : ext; const grammars = atom.grammars.getGrammars(); return grammars.find((grammar) => { return grammar.fileTypes.includes(ext); }); } /** * Tries to find a matching Atom Grammar from KernelspecMetadata name * * @param {String} name - The KernelspecMetadata name to find a grammar for. * @returns {Grammar} - The matching Atom Grammar. */ function getGrammarForKernelspecName(name: string): Grammar | null | undefined { // Check if there exists an Atom grammar named source.${name} const grammar = getGrammarForLanguageName(name); if (grammar) { return grammar; } // Otherwise attempt manual matching from kernelspec name to Atom scope const crosswalk = { python2: "source.python", python3: "source.python", bash: "source.shell", javascript: "source.js", ir: "source.r", }; if (crosswalk[name]) { return atom.grammars.grammarForScopeName(crosswalk[name]); } } /** * Converts notebook cells to Hydrogen code blocks. * * @param {Cell} cell - Notebook cell to convert * @param {String} commentStartString - The comment syntax of the code language. * @returns {Object} - A Hydrogen Code Block. */ function toHydrogenCodeBlock( cell: Cell, commentStartString: string ): { cellType: HydrogenCellType; code: string; row: number; } { const cellType = cell.cell_type === "markdown" ? "markdown" : "codecell"; const cellHeader = getCellHeader(commentStartString, cellType); let source = cell.source; let cellLength; if (cellType === "markdown") { source = source.split("\n"); source[0] = commentStartString + source[0]; cellLength = source.length; source = source.join(linesep + commentStartString); } else { cellLength = source.split("\n").length; } return { cellType, code: cellHeader + linesep + source, row: cellLength + 1, // plus 1 for the header }; } /** * Creates a Hydrogen cell header * * @param {String} commentStartString - The comment syntax of the code language. * @param {String} keyword - The keyword relating to the cell type. * @returns {String} - A Hydrogen Cell Header. */ function getCellHeader( commentStartString: string, keyword: string | null | undefined ) { const marker = `${commentStartString}%% `; return keyword ? marker + keyword : marker; } /** * Displays previous cell results inline of the provided editor. nbCells and * resultRows should be the same length. * * @param {TextEditor} editor - The editor to display the results in. * @param {Cell[]} nbCells - The original notebook cells. * @param {Number[]} resultRows - The rows to display the results on. */ function importNotebookResults( editor: TextEditor, nbCells: Array<Cell>, resultRows: Array<number> ) { if (nbCells.length != resultRows.length) { return; } let markers = store.markersMapping.get(editor.id); markers = markers ? markers : store.newMarkerStore(editor.id); let cellNumber = 0; for (const cell of nbCells) { const row = resultRows[cellNumber]; switch (cell.cell_type) { case "code": if (cell.outputs.length > 0) { importResult( { editor, markers, }, { outputs: cell.outputs, row, } ); } break; case "markdown": importResult( { editor, markers, }, { outputs: [convertMarkdownToOutput(cell.source)], row, } ); break; } cellNumber++; } }
the_stack
import { CanvasContext } from "@tarojs/taro"; import { IText, IIMage, ILine, IBlock } from '../types'; export interface IDrawRadiusRectData { x: number; y: number; w: number; h: number; r: number; } export interface IDrawOptions { ctx: CanvasContext; toPx: (rpx: number, int?: boolean, factor?: number) => number; toRpx: (px: number, int?: boolean, factor?: number) => number; } /** * @description 绘制圆角矩形 * @param { object } drawData - 绘制数据 * @param { number } drawData.x - 左上角x坐标 * @param { number } drawData.y - 左上角y坐标 * @param { number } drawData.w - 矩形的宽 * @param { number } drawData.h - 矩形的高 * @param { number } drawData.r - 圆角半径 */ export function _drawRadiusRect(drawData: IDrawRadiusRectData, drawOptions: IDrawOptions) { const { x, y, w, h, r } = drawData; const { ctx, toPx, // toRpx, } = drawOptions; const br = r / 2; ctx.beginPath(); ctx.moveTo(toPx(x + br), toPx(y)); // 移动到左上角的点 ctx.lineTo(toPx(x + w - br), toPx(y)); ctx.arc(toPx(x + w - br), toPx(y + br), toPx(br), 2 * Math.PI * (3 / 4), 2 * Math.PI * (4 / 4)) ctx.lineTo(toPx(x + w), toPx(y + h - br)); ctx.arc(toPx(x + w - br), toPx(y + h - br), toPx(br), 0, 2 * Math.PI * (1 / 4)) ctx.lineTo(toPx(x + br), toPx(y + h)); ctx.arc(toPx(x + br), toPx(y + h - br), toPx(br), 2 * Math.PI * (1 / 4), 2 * Math.PI * (2 / 4)) ctx.lineTo(toPx(x), toPx(y + br)); ctx.arc(toPx(x + br), toPx(y + br), toPx(br), 2 * Math.PI * (2 / 4), 2 * Math.PI * (3 / 4)) } /** * @description 计算文本长度 * @param { Array | Object } text 数组 或者 对象 */ export function _getTextWidth(_text: IText | IText[], drawOptions: IDrawOptions): number { const { ctx, toPx, toRpx } = drawOptions; let texts: IText[] = []; if (Array.isArray(_text)) { texts = _text; } else { texts.push(_text); } let width = 0; texts.forEach(({ fontSize, text, marginLeft = 0, marginRight = 0 }) => { ctx.setFontSize(toPx(fontSize)); let _textWidth = 0; if (typeof text === 'object') { _textWidth = ctx.measureText(text.text).width + text.marginLeft + text.marginRight; } else { _textWidth = ctx.measureText(text).width; } width += _textWidth + marginLeft + marginRight; }) return toRpx(width); } /** * @description 渲染一段文字 * @param { object } drawData - 绘制数据 * @param { number } drawData.x - x坐标 rpx * @param { number } drawData.y - y坐标 rpx * @param { number } drawData.fontSize - 文字大小 rpx * @param { number } [drawData.color] - 颜色 * @param { string } [drawData.baseLine] - 基线对齐方式 top| middle|bottom * @param { string } [drawData.textAlign='left'] - 对齐方式 left|center|right * @param { string } drawData.text - 当Object类型时,参数为 text 字段的参数,marginLeft、marginRight这两个字段可用 * @param { number } [drawData.opacity=1] - 1为不透明,0为透明 * @param { string } [drawData.textDecoration='none'] * @param { number } [drawData.width] - 文字宽度 没有指定为画布宽度 * @param { number } [drawData.lineNum=1] - 根据宽度换行,最多的行数 * @param { number } [drawData.lineHeight=0] - 行高 * @param { string } [drawData.fontWeight='normal'] - 'bold' 加粗字体,目前小程序不支持 100 - 900 加粗 * @param { string } [drawData.fontStyle='normal'] - 'italic' 倾斜字体 * @param { string } [drawData.fontFamily="sans-serif"] - 小程序默认字体为 'sans-serif', 请输入小程序支持的字体 */ interface IDrawSingleTextData extends IText { } export function _drawSingleText(drawData: IDrawSingleTextData, drawOptions: IDrawOptions) { let { x, y, fontSize, color, baseLine, textAlign = 'left', text, opacity = 1, textDecoration = 'none', width = 0, lineNum = 1, lineHeight = 0, fontWeight = 'normal', fontStyle = 'normal', fontFamily = "sans-serif" } = drawData; const { ctx, toPx } = drawOptions; ctx.save(); ctx.beginPath(); ctx.font = fontStyle + " " + fontWeight + " " + toPx(fontSize, true) + "px " + fontFamily ctx.setGlobalAlpha(opacity); // ctx.setFontSize(toPx(fontSize)); if (typeof text === 'object') { text = text.text } color && ctx.setFillStyle(color); baseLine && ctx.setTextBaseline(baseLine); ctx.setTextAlign(textAlign); let textWidth = (ctx.measureText(text as string).width); const textArr: string[] = []; let drawWidth = toPx(width); if (width && textWidth > drawWidth) { // 文本宽度 大于 渲染宽度 let fillText = ''; let line = 1; for (let i = 0; i <= (text as string).length - 1; i++) { // 将文字转为数组,一行文字一个元素 fillText = fillText + text[i]; if ((ctx.measureText(fillText).width) >= drawWidth) { if (line === lineNum) { if (i !== (text as string).length - 1) { fillText = fillText.substring(0, fillText.length - 1) + '...'; } } if (line <= lineNum) { textArr.push(fillText); } fillText = ''; line++; } else { if (line <= lineNum) { if (i === (text as string).length - 1) { textArr.push(fillText); } } } } textWidth = width; } else { textArr.push(text as string); } textArr.forEach((item, index) => { ctx.fillText(item, toPx(x), toPx(y + (lineHeight || fontSize) * index)); }) ctx.restore(); // textDecoration if (textDecoration !== 'none') { let lineY = y; if (textDecoration === 'line-through') { // 目前只支持贯穿线 lineY = y; // 小程序画布baseLine偏移阈值 let threshold = 5; // 根据baseLine的不同对贯穿线的Y坐标做相应调整 switch (baseLine) { case 'top': lineY += fontSize / 2 + threshold; break; case 'middle': break; case 'bottom': lineY -= fontSize / 2 + threshold; break; default: lineY -= fontSize / 2 - threshold; break; } } ctx.save(); ctx.moveTo(toPx(x), toPx(lineY)); ctx.lineTo(toPx(x) + toPx(textWidth), toPx(lineY)); color && ctx.setStrokeStyle(color); ctx.stroke(); ctx.restore(); } return textWidth; } /** * 渲染文字 * @param { object } params - 绘制数据 * @param { number } params.x - x坐标 rpx * @param { number } params.y - y坐标 rpx * @param { number } params.fontSize - 文字大小 rpx * @param { number } [params.color] - 颜色 * @param { string } [params.baseLine] - 基线对齐方式 top| middle|bottom * @param { string } [params.textAlign='left'] - 对齐方式 left|center|right * @param { string } params.text - 当Object类型时,参数为 text 字段的参数,marginLeft、marginRight这两个字段可用 * @param { number } [params.opacity=1] - 1为不透明,0为透明 * @param { string } [params.textDecoration='none'] * @param { number } [params.width] - 文字宽度 没有指定为画布宽度 * @param { number } [params.lineNum=1] - 根据宽度换行,最多的行数 * @param { number } [params.lineHeight=0] - 行高 * @param { string } [params.fontWeight='normal'] - 'bold' 加粗字体,目前小程序不支持 100 - 900 加粗 * @param { string } [params.fontStyle='normal'] - 'italic' 倾斜字体 * @param { string } [params.fontFamily="sans-serif"] - 小程序默认字体为 'sans-serif', 请输入小程序支持的字体 */ export function drawText(params: IText, drawOptions: IDrawOptions) { // const { ctx, toPx, toRpx } = drawOptions; const { x, y, text, baseLine, // fontSize, // color, // textAlign, // opacity = 1, // width, // lineNum, // lineHeight } = params; if (Array.isArray(text)) { let preText = { x, y, baseLine }; text.forEach(item => { preText.x += item.marginLeft || 0; const textWidth = _drawSingleText(Object.assign(item, { ...preText, }), drawOptions); preText.x += textWidth + (item.marginRight || 0); // 下一段字的 x 轴为上一段字 x + 上一段字宽度 }) } else { _drawSingleText(params, drawOptions); } } export interface IDrawImageData extends IIMage { imgPath: string; w: number; h: number; sx: number; sy: number; sw: number; sh: number; } /** * @description 渲染图片 * @param { object } data * @param { number } x - 图像的左上角在目标 canvas 上 x 轴的位置 * @param { number } y - 图像的左上角在目标 canvas 上 y 轴的位置 * @param { number } w - 在目标画布上绘制图像的宽度,允许对绘制的图像进行缩放 * @param { number } h - 在目标画布上绘制图像的高度,允许对绘制的图像进行缩放 * @param { number } sx - 源图像的矩形选择框的左上角 x 坐标 * @param { number } sy - 源图像的矩形选择框的左上角 y 坐标 * @param { number } sw - 源图像的矩形选择框的宽度 * @param { number } sh - 源图像的矩形选择框的高度 * @param { number } [borderRadius=0] - 圆角 * @param { number } [borderWidth=0] - 边框 */ export function drawImage(data: IDrawImageData, drawOptions: IDrawOptions) { const { ctx, toPx } = drawOptions; const { imgPath, x, y, w, h, sx, sy, sw, sh, borderRadius = 0, borderWidth = 0, borderColor } = data; ctx.save(); if (borderRadius > 0) { let drawData = { x, y, w, h, r: borderRadius }; _drawRadiusRect(drawData, drawOptions); ctx.strokeStyle = 'rgba(255,255,255,0)'; ctx.stroke(); ctx.clip(); ctx.drawImage(imgPath, toPx(sx), toPx(sy), toPx(sw), toPx(sh), toPx(x), toPx(y), toPx(w), toPx(h)); if (borderWidth > 0) { borderColor && ctx.setStrokeStyle(borderColor); ctx.setLineWidth(toPx(borderWidth)); ctx.stroke(); } } else { ctx.drawImage(imgPath, toPx(sx), toPx(sy), toPx(sw), toPx(sh), toPx(x), toPx(y), toPx(w), toPx(h)); } ctx.restore(); } /** * @description 渲染线 * @param { number } startX - 起始坐标 * @param { number } startY - 起始坐标 * @param { number } endX - 终结坐标 * @param { number } endY - 终结坐标 * @param { number } width - 线的宽度 * @param { string } [color] - 线的颜色 */ export function drawLine(drawData: ILine, drawOptions: IDrawOptions) { const { startX, startY, endX, endY, color, width } = drawData; const { ctx, toPx } = drawOptions; ctx.save(); ctx.beginPath(); color && ctx.setStrokeStyle(color); ctx.setLineWidth(toPx(width)); ctx.moveTo(toPx(startX), toPx(startY)); ctx.lineTo(toPx(endX), toPx(endY)); ctx.stroke(); ctx.closePath(); ctx.restore(); } /** * @description 渲染块 * @param { number } x - x坐标 * @param { number } y - y坐标 * @param { number } height -高 * @param { string|object } [text] - 块里面可以填充文字,参考texts字段 * @param { number } [width=0] - 宽 如果内部有文字,由文字宽度和内边距决定 * @param { number } [paddingLeft=0] - 内左边距 * @param { number } [paddingRight=0] - 内右边距 * @param { number } [borderWidth] - 边框宽度 * @param { string } [backgroundColor] - 背景颜色 * @param { string } [borderColor] - 边框颜色 * @param { number } [borderRadius=0] - 圆角 * @param { number } [opacity=1] - 透明度 * */ export function drawBlock(blockData: IBlock, drawOptions: IDrawOptions) { const { ctx, toPx, } = drawOptions; const { text, width = 0, height, x, y, paddingLeft = 0, paddingRight = 0, borderWidth, backgroundColor, borderColor, borderRadius = 0, opacity = 1 } = blockData; // 判断是否块内有文字 let blockWidth = 0; // 块的宽度 let textX = 0; let textY = 0; if (typeof text !== 'undefined') { // 如果有文字并且块的宽度小于文字宽度,块的宽度为 文字的宽度 + 内边距 // const textWidth = _getTextWidth(typeof text.text === 'string' ? text : text.text, drawOptions); const textWidth: number = _getTextWidth(text, drawOptions); blockWidth = textWidth > width ? textWidth : width; blockWidth += paddingLeft + paddingLeft; const { textAlign = 'left', // text: textCon, } = text; textY = height / 2 + y; // 文字的y轴坐标在块中线 if (textAlign === 'left') { // 如果是右对齐,那x轴在块的最左边 textX = x + paddingLeft; } else if (textAlign === 'center') { textX = blockWidth / 2 + x; } else { textX = x + blockWidth - paddingRight; } } else { blockWidth = width; } if (backgroundColor) { // 画面 ctx.save(); ctx.setGlobalAlpha(opacity); ctx.setFillStyle(backgroundColor); if (borderRadius > 0) { // 画圆角矩形 let drawData = { x, y, w: blockWidth, h: height, r: borderRadius }; _drawRadiusRect(drawData, drawOptions); ctx.fill(); } else { ctx.fillRect(toPx(x), toPx(y), toPx(blockWidth), toPx(height)); } ctx.restore(); } if (borderWidth) { // 画线 ctx.save(); ctx.setGlobalAlpha(opacity); borderColor && ctx.setStrokeStyle(borderColor); ctx.setLineWidth(toPx(borderWidth)); if (borderRadius > 0) { // 画圆角矩形边框 let drawData = { x, y, w: blockWidth, h: height, r: borderRadius, } _drawRadiusRect(drawData, drawOptions); ctx.stroke(); } else { ctx.strokeRect(toPx(x), toPx(y), toPx(blockWidth), toPx(height)); } ctx.restore(); } if (text) { drawText(Object.assign(text, { x: textX, y: textY }), drawOptions) } }
the_stack
import {isString, deepCopy} from './utils.js'; export type Piece = string; export type PositionObject = {[square: string]: Piece | undefined}; export type Position = PositionObject | 'start' | string; const RUN_ASSERTS = true; export const START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR'; export const COLUMNS = 'abcdefgh'.split(''); export const whitePieces = ['wK', 'wQ', 'wR', 'wB', 'wN', 'wP']; export const blackPieces = ['bK', 'bQ', 'bR', 'bB', 'bN', 'bP']; export const getSquareColor = (square: string) => square.charCodeAt(0) % 2 ^ square.charCodeAt(1) % 2 ? 'white' : 'black'; export const validSquare = (square: unknown): square is string => { return isString(square) && square.search(/^[a-h][1-8]$/) !== -1; }; export const validMove = (move: unknown): move is string => { // move should be a string if (!isString(move)) return false; // move should be in the form of "e2-e4", "f6-d5" const squares = move.split('-'); if (squares.length !== 2) return false; return validSquare(squares[0]) && validSquare(squares[1]); }; if (RUN_ASSERTS) { console.assert(validSquare('a1')); console.assert(validSquare('e2')); console.assert(!validSquare('D2')); console.assert(!validSquare('g9')); console.assert(!validSquare('a')); console.assert(!validSquare(true)); console.assert(!validSquare(null)); console.assert(!validSquare({})); } export const validPieceCode = (code: unknown): code is string => { return isString(code) && code.search(/^[bw][KQRNBP]$/) !== -1; }; if (RUN_ASSERTS) { console.assert(validPieceCode('bP')); console.assert(validPieceCode('bK')); console.assert(validPieceCode('wK')); console.assert(validPieceCode('wR')); console.assert(!validPieceCode('WR')); console.assert(!validPieceCode('Wr')); console.assert(!validPieceCode('a')); console.assert(!validPieceCode(true)); console.assert(!validPieceCode(null)); console.assert(!validPieceCode({})); } const squeezeFenEmptySquares = (fen: string) => { return fen .replace(/11111111/g, '8') .replace(/1111111/g, '7') .replace(/111111/g, '6') .replace(/11111/g, '5') .replace(/1111/g, '4') .replace(/111/g, '3') .replace(/11/g, '2'); }; const expandFenEmptySquares = (fen: string) => { return fen .replace(/8/g, '11111111') .replace(/7/g, '1111111') .replace(/6/g, '111111') .replace(/5/g, '11111') .replace(/4/g, '1111') .replace(/3/g, '111') .replace(/2/g, '11'); }; export const validFen = (fen: unknown): fen is string => { if (!isString(fen)) return false; // cut off any move, castling, etc info from the end // we're only interested in position information fen = fen.replace(/ .+$/, ''); // expand the empty square numbers to just 1s fen = expandFenEmptySquares(fen as string); // FEN should be 8 sections separated by slashes const chunks = (fen as string).split('/'); if (chunks.length !== 8) return false; // check each section for (let i = 0; i < 8; i++) { if (chunks[i].length !== 8 || chunks[i].search(/[^kqrnbpKQRNBP1]/) !== -1) { return false; } } return true; }; if (RUN_ASSERTS) { console.assert(validFen(START_FEN)); console.assert(validFen('8/8/8/8/8/8/8/8')); console.assert( validFen('r1bqkbnr/pppp1ppp/2n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R') ); console.assert( validFen('3r3r/1p4pp/2nb1k2/pP3p2/8/PB2PN2/p4PPP/R4RK1 b - - 0 1') ); console.assert( !validFen('3r3z/1p4pp/2nb1k2/pP3p2/8/PB2PN2/p4PPP/R4RK1 b - - 0 1') ); console.assert(!validFen('anbqkbnr/8/8/8/8/8/PPPPPPPP/8')); console.assert(!validFen('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/')); console.assert(!validFen('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBN')); console.assert(!validFen('888888/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR')); console.assert(!validFen('888888/pppppppp/74/8/8/8/PPPPPPPP/RNBQKBNR')); console.assert(!validFen({})); } export const validPositionObject = (pos: unknown): pos is PositionObject => { if (typeof pos !== 'object' || pos === null) { return false; } for (const [square, piece] of Object.entries(pos)) { if (!validSquare(square) || !validPieceCode(piece)) { return false; } } return true; }; if (RUN_ASSERTS) { // console.assert(validPositionObject(START_POSITION)); console.assert(validPositionObject({})); console.assert(validPositionObject({e2: 'wP'})); console.assert(validPositionObject({e2: 'wP', d2: 'wP'})); console.assert(!validPositionObject({e2: 'BP'})); console.assert(!validPositionObject({y2: 'wP'})); console.assert(!validPositionObject(null)); console.assert(!validPositionObject(undefined)); console.assert(!validPositionObject(1)); console.assert(!validPositionObject('start')); console.assert(!validPositionObject(START_FEN)); } // convert FEN piece code to bP, wK, etc const fenToPieceCode = (piece: string) => { // black piece if (piece.toLowerCase() === piece) { return 'b' + piece.toUpperCase(); } // white piece return 'w' + piece.toUpperCase(); }; // convert bP, wK, etc code to FEN structure const pieceCodeToFen = (piece: string) => { const pieceCodeLetters = piece.split(''); // white piece if (pieceCodeLetters[0] === 'w') { return pieceCodeLetters[1].toUpperCase(); } // black piece return pieceCodeLetters[1].toLowerCase(); }; // convert FEN string to position object // returns false if the FEN string is invalid export const fenToObj = (fen: string) => { if (!validFen(fen)) return false; // cut off any move, castling, etc info from the end // we're only interested in position information fen = fen.replace(/ .+$/, ''); const rows = fen.split('/'); const position: PositionObject = {}; let currentRow = 8; for (let i = 0; i < 8; i++) { const row = rows[i].split(''); let colIdx = 0; // loop through each character in the FEN section for (let j = 0; j < row.length; j++) { // number / empty squares if (row[j].search(/[1-8]/) !== -1) { const numEmptySquares = parseInt(row[j], 10); colIdx = colIdx + numEmptySquares; } else { // piece const square = COLUMNS[colIdx] + currentRow; position[square] = fenToPieceCode(row[j]); colIdx = colIdx + 1; } } currentRow = currentRow - 1; } return position; }; export const START_POSITION = fenToObj(START_FEN) as PositionObject; // position object to FEN string // returns false if the obj is not a valid position object export const objToFen = (obj: PositionObject) => { if (!validPositionObject(obj)) return false; let fen = ''; let currentRow = 8; for (let i = 0; i < 8; i++) { for (let j = 0; j < 8; j++) { const square = COLUMNS[j] + currentRow; // piece exists if (obj.hasOwnProperty(square)) { fen = fen + pieceCodeToFen(obj[square]!); } else { // empty space fen = fen + '1'; } } if (i !== 7) { fen = fen + '/'; } currentRow = currentRow - 1; } // squeeze the empty numbers together fen = squeezeFenEmptySquares(fen); return fen; }; if (RUN_ASSERTS) { console.assert(objToFen(START_POSITION) === START_FEN); console.assert(objToFen({}) === '8/8/8/8/8/8/8/8'); console.assert(objToFen({a2: 'wP', b2: 'bP'}) === '8/8/8/8/8/8/Pp6/8'); } export const normalizePozition = ( position: Position | null ): PositionObject => { if (position == null) { return {}; } // start position if (isString(position) && position.toLowerCase() === 'start') { position = deepCopy(START_POSITION); } // convert FEN to position object if (validFen(position)) { position = fenToObj(position) as PositionObject; } return position as PositionObject; }; // returns the distance between two squares const squareDistance = (squareA: string, squareB: string) => { const squareAArray = squareA.split(''); const squareAx = COLUMNS.indexOf(squareAArray[0]) + 1; const squareAy = parseInt(squareAArray[1], 10); const squareBArray = squareB.split(''); const squareBx = COLUMNS.indexOf(squareBArray[0]) + 1; const squareBy = parseInt(squareBArray[1], 10); const xDelta = Math.abs(squareAx - squareBx); const yDelta = Math.abs(squareAy - squareBy); if (xDelta >= yDelta) return xDelta; return yDelta; }; // returns an array of closest squares from square const createRadius = (square: string) => { const squares = []; // calculate distance of all squares for (let i = 0; i < 8; i++) { for (let j = 0; j < 8; j++) { const s = COLUMNS[i] + (j + 1); // skip the square we're starting from if (square === s) continue; squares.push({ square: s, distance: squareDistance(square, s), }); } } // sort by distance squares.sort(function (a, b) { return a.distance - b.distance; }); // just return the square code const surroundingSquares = []; for (let i = 0; i < squares.length; i++) { surroundingSquares.push(squares[i].square); } return surroundingSquares; }; // returns the square of the closest instance of piece // returns false if no instance of piece is found in position export const findClosestPiece = ( position: PositionObject, piece: string, square: string ) => { // create array of closest squares from square const closestSquares = createRadius(square); // search through the position in order of distance for the piece for (let i = 0; i < closestSquares.length; i++) { const s = closestSquares[i]; if (position.hasOwnProperty(s) && position[s] === piece) { return s; } } return false; }; // given a position and a set of moves, return a new position // with the moves executed export const calculatePositionFromMoves = ( position: PositionObject, moves: {[from: string]: string} ) => { const newPosition = deepCopy(position); for (const i in moves) { if (!moves.hasOwnProperty(i)) continue; // skip the move if the position doesn't have a piece on the source square if (!newPosition.hasOwnProperty(i)) continue; const piece = newPosition[i]; delete newPosition[i]; newPosition[moves[i]] = piece; } return newPosition; }; // TODO: add some asserts here for calculatePositionFromMoves
the_stack
import { RavenTransportOptions } from 'raven-js'; import prefixUrl from '../prefix-url'; const UNKNOWN_SYM = { sym: '??', word: '??' }; const NAV_SYMBOLS = [ { sym: 'dp', word: 'dependencies', rx: /^\/dep/i }, { sym: 'tr', word: 'trace', rx: /^\/trace/i }, { sym: 'sd', word: 'search', rx: /^\/search\?./i }, { sym: 'sr', word: 'search', rx: /^\/search/i }, { sym: 'rt', word: 'home', rx: /^\/$/ }, ]; const FETCH_SYMBOLS = [ { sym: 'svc', word: '', rx: /^\/api\/services$/i }, { sym: 'op', word: '', rx: /^\/api\/.*?operations$/i }, { sym: 'sr', word: '', rx: /^\/api\/traces\?/i }, { sym: 'tr', word: '', rx: /^\/api\/traces\/./i }, { sym: 'dp', word: '', rx: /^\/api\/dep/i }, { sym: '__IGNORE__', word: '', rx: /\.js(\.map)?$/i }, ]; // eslint-disable-next-line no-console const warn = console.warn.bind(console); // common aspect of local URLs const origin = window.location.origin + prefixUrl(''); // truncate and use "~" instead of ellipsis bc it's shorter function truncate(str: string, len: number, front: boolean = false) { if (str.length > len) { if (!front) { return `${str.slice(0, len - 1)}~`; } return `~${str.slice(1 - len)}`; } return str; } // Replace newlines with "|" and collapse whitespace to " " function collapseWhitespace(value: string) { return value .trim() .replace(/\n/g, '|') .replace(/\s\s+/g, ' ') .trim(); } // shorten URLs to eitehr a short code or a word function getSym(syms: typeof NAV_SYMBOLS | typeof FETCH_SYMBOLS, str: string) { for (let i = 0; i < syms.length; i++) { const { rx } = syms[i]; if (rx.test(str)) { return syms[i]; } } warn(`Unable to find symbol for: "${str}"`); return UNKNOWN_SYM; } // Convert an error message to a shorter string with the first "error" removed, // a leading "! " added, and the first ":" replaced with "!". // // Error: Houston we have a problem // ! Houston we have a problem // // Error: HTTP Error: Fetch failed // ! HTTP Error: Fetch failed // // TypeError: Awful things are happening // ! Type! Awful things are happening // // The real error message // ! The real error message function convErrorMessage(message: string, maxLen: number = 0) { let msg = collapseWhitespace(message); const parts = ['! ']; const j = msg.indexOf(':'); if (j > -1) { const start = msg .slice(0, j) .replace(/error/i, '') .trim(); if (start) { parts.push(start, '! '); } msg = msg.slice(j + 1); } parts.push(msg.trim()); const rv = parts.join(''); return maxLen ? truncate(rv, maxLen) : parts.join(''); } // Convert an exception to the error message and a compacted stack trace. The // message is truncated to 149 characters. The strack trace is compacted to the // following format: // From (array of objects): // { filename: 'http://origin/static/js/main.js', function: 'aFn' } // { filename: 'http://origin/static/js/main.js', function: 'bFn' } // { filename: 'http://origin/static/js/chunk.js', function: 'cFn' } // { filename: 'http://origin/static/js/chunk.js', function: 'dFn' } // To (string): // > main.js // aFn // bFn // > chunk.js // cFn // dFn // interface IConvException { type: string; value: number; stacktrace: { frames: { filename: string; function: string; }[]; }; } function convException(errValue: IConvException) { const message = convErrorMessage(`${errValue.type}: ${errValue.value}`, 149); const frames = errValue.stacktrace.frames.map(fr => { const filename = fr.filename.replace(origin, '').replace(/^\/static\/js\//i, ''); const fn = collapseWhitespace(fr.function || '??'); return { filename, fn }; }); const joiner = []; let lastFile = ''; for (let i = frames.length - 1; i >= 0; i--) { const { filename, fn } = frames[i]; if (lastFile !== filename) { joiner.push(`> ${filename}`); lastFile = filename; } joiner.push(fn); } return { message, stack: joiner.join('\n') }; } // Convert a navigation breadcrumb to one of the following string tokens: // "dp" - dependencies page // "tr" - trace page // "sd" - search page with search results // "sr" - search page // "rt" - the root page function convNav(to: string) { const sym = getSym(NAV_SYMBOLS, to); return sym.sym; } // Convert a HTTP fetch breadcrumb to a string token in one of the two // following forms: // "[SYM]" // "[SYM|NNN]" // Where "SYM" is one of: // "svc" - fetch the services for the search page // "op" - fetch the operations for a service // "sr" - execute a search // "tr" - fetch a trace // "dp" - fetch the dependency data // And, "NNN" is a non-200 status code. type TCrumbData = { url: string; status_code: number; to: string; }; function convFetch(data: TCrumbData) { const { url, status_code } = data; const statusStr = status_code === 200 ? '' : `|${status_code}`; const sym = getSym(FETCH_SYMBOLS, url); if (sym.sym === '__IGNORE__') { return null; } return `[${sym.sym}${statusStr}]`; } // Reduce the selector to something similar, but more compact. This is an // informal reduction, i.e. the selector may actually function completely // differently, but it should suffice as a reference for UI events. The // intention is to trim the selector to something more compact but still // recognizable. // // Some examples of the conversion: // // div.ub-relative. > span > span.detail-row-expanded-accent // => .detail-row-expanded-accent // // header > div.TracePageHeader--titleRow > button.ant-btn.ub-mr2[type="button"] // => .TracePageHeader--titleRow >.ant-btn[type="button"] // // span.SpanTreeOffset.is-parent > span.SpanTreeOffset--iconWrapper // => .SpanTreeOffset.is-parent >.SpanTreeOffset--iconWrapper // // div > div > div.AccordianLogs > a.AccordianLogs--header. // => .AccordianLogs >.AccordianLogs--header // // body > div > div > div.ant-modal-wrap. // => .ant-modal-wrap // // a.ub-flex-auto.ub-mr2 > h1.TracePageHeader--title // => .TracePageHeader--title function compressCssSelector(selector: string) { return ( selector // cut dangling dots, "div. > div" to "div > div" .replace(/\.(?=\s|$)/g, '') // cut ub-* class names, "a.ub-p.is-ok" to "a.is-ok" .replace(/\.ub-[^. [:]+/g, '') // cut leading tags, "div > a > .cls" to ".cls" .replace(/^(\w+ > )+/, '') // cut tag names when there is also a class, "a.is-ok" to ".is-ok" .replace(/(^| )\w+?(?=\.)/g, '$1') // cut the first space in child selectors, ".is-ok > .yuh" to ".is-ok >.yuh" .replace(/ > /g, ' >') ); } // Convert the breadcrumbs to a compact string, discarding quite a lot of // information. // // Navigation and HTTP fetch breadcrumbs are described above in `convFetch()` // and `convNav()`. // // Previously logged errors captured by sentry are truncated to 58 characters // and placed on their own line. Further, the first occurrence of "error" is // removed and the first ":" is replaced with "!". E.g. the message: // "Error: some error here with a very long message that will be truncated" // Becomes: // "\n! some error here with a very long message that will be t~\n" // // UI breadcrumbs are reduced to the first letter after the "ui.". And, // repeated tokens are compacted to the form: // "tN" // Where "t" is the event type ("c" is click, "i" is input) and "N" is the // total number of times it occured in that sequence. E.g. "c2" indicates // two "ui.click" breadcrumbs. // // The chronological ordering of the breadcrumbs is older events precede newer // events. This ordering was kept because it's easier to see which page events // occurred on. interface ICrumb { category: string; data: TCrumbData; message: string; selector: string; } function convBreadcrumbs(crumbs: ICrumb[]) { if (!Array.isArray(crumbs) || !crumbs.length) { return ''; } // the last UI breadcrumb has the CSS selector included let iLastUi = -1; for (let i = crumbs.length - 1; i >= 0; i--) { if (crumbs[i].category.slice(0, 2) === 'ui') { iLastUi = i; break; } } let joiner: string[] = []; // note when we're on a newline to avoid extra newlines let onNewLine = true; for (let i = 0; i < crumbs.length; i++) { const c = crumbs[i]; const cStart = c.category.split('.')[0]; switch (cStart) { case 'fetch': { const fetched = convFetch(c.data); if (fetched) { joiner.push(fetched); onNewLine = false; } break; } case 'navigation': { const nav = `${onNewLine ? '' : '\n'}\n${convNav(c.data.to)}\n`; joiner.push(nav); onNewLine = true; break; } case 'ui': { if (i === iLastUi) { const selector = compressCssSelector(c.message); joiner.push(`${c.category[3]}{${selector}}`); } else { joiner.push(c.category[3]); } onNewLine = false; break; } case 'sentry': { const msg = convErrorMessage(c.message, 58); joiner.push(`${onNewLine ? '' : '\n'}${msg}\n`); onNewLine = true; break; } default: // skip } } joiner = joiner.filter(Boolean); // combine repeating UI chars, e.g. ["c","c","c","c"] -> ["c","4"] let c = ''; let ci = -1; const compacted = joiner.reduce((accum: string[], value: string, j: number): string[] => { if (value === c) { return accum; } if (c) { if (j - ci > 1) { accum.push(String(j - ci)); } c = ''; ci = -1; } accum.push(value); if (value.length === 1) { c = value; ci = j; } return accum; }, []); if (c && ci !== joiner.length - 1) { compacted.push(String(joiner.length - ci)); } return compacted .join('') .trim() .replace(/\n\n\n/g, '\n'); } // Create the GA label value from the message, page, duration, git info, and // breadcrumbs. See <./README.md> for details. function getLabel(message: string, page: string, duration: number, git: string, breadcrumbs: ICrumb[]) { const header = [message, page, duration, git, ''].filter(v => v != null).join('\n'); const crumbs = convBreadcrumbs(breadcrumbs); return `${header}\n${truncate(crumbs, 498 - header.length, true)}`; } // Convert the Raven exception data to something that can be sent to Google // Analytics. See <./README.md> for details. export default function convRavenToGa({ data }: RavenTransportOptions) { const { breadcrumbs, exception, extra, request, tags } = data; const { message, stack } = convException(exception.values[0]); const url = truncate(request.url.replace(origin, ''), 50); const { word: page } = getSym(NAV_SYMBOLS, url); const value = Math.round(extra['session:duration'] / 1000); const category = `jaeger/${page}/error`; let action = [message, tags && tags.git, url, '', stack].filter(v => v != null).join('\n'); action = truncate(action, 499); const label = getLabel(message, page, value, tags && tags.git, breadcrumbs && breadcrumbs.values); return { message, category, action, label, value, }; }
the_stack
import { basename, relative, extname, normalize } from 'path' import * as convert from 'convert-source-map' import findRoot from 'find-root' import { memoize } from 'lodash' import { SourceMapGenerator } from 'source-map' import * as ts from 'typescript' const hashString = require('@emotion/hash').default interface ModuleConfig { moduleName: string includesSubPath?: boolean exportedNames: string[] styledName?: string hasDefaultExport?: boolean } interface ImportInfo extends ModuleConfig { name: string type: 'namedImport' | 'namespaceImport' | 'defaultImport' } const FACTORY: typeof ts.factory = 'factory' in ts ? ts.factory : ts export interface Options { sourcemap?: boolean autoLabel?: boolean labelFormat?: string autoInject?: boolean customModules?: ModuleConfig[] jsxFactory?: string jsxImportSource?: string } const defaultEmotionModules: ModuleConfig[] = [ { moduleName: '@emotion/styled', exportedNames: ['styled'], hasDefaultExport: true, styledName: 'styled', }, { moduleName: '@emotion/react', exportedNames: ['css'], }, ] const defaultOptions: Options = { sourcemap: true, autoLabel: true, labelFormat: '[local]', autoInject: true, jsxImportSource: '@emotion/react', } const getPackageRootPath = memoize((filename: string) => findRoot(filename)) const hashArray = (arr: Array<string>) => hashString(arr.join('')) const createImportJSXAst = memoize((propertyName: string | undefined) => { const importClause = FACTORY.createImportClause( false, undefined, FACTORY.createNamedImports([ propertyName ? FACTORY.createImportSpecifier( FACTORY.createIdentifier('jsx'), FACTORY.createIdentifier(propertyName), ) : FACTORY.createImportSpecifier( undefined, FACTORY.createIdentifier('jsx'), ), ]), ) const moduleSpecifier = FACTORY.createStringLiteral('@emotion/react') return FACTORY.createImportDeclaration( undefined, undefined, importClause, moduleSpecifier, ) }) export function createEmotionPlugin( pluginOptions?: Options, ): ts.TransformerFactory<ts.SourceFile> { const options = { ...defaultOptions, ...pluginOptions } const modules = new Map( defaultEmotionModules .concat(options.customModules ?? []) .map((m) => [m.moduleName, m]), ) function getImportCalls( importDeclarationNode: ts.ImportDeclaration, compilerOptions: ts.CompilerOptions, ) { const importCalls: ImportInfo[] = [] const moduleName = (importDeclarationNode.moduleSpecifier as ts.StringLiteral) .text if (!importDeclarationNode.importClause) { return importCalls } const { name, namedBindings } = importDeclarationNode.importClause! for (const moduleInfo of modules.values()) { if ( moduleInfo.moduleName === moduleName || (moduleInfo.includesSubPath && moduleName.includes(moduleInfo.moduleName + '/')) ) { // import lib from 'lib' if (name) { if (moduleInfo.hasDefaultExport) { importCalls.push({ name: name.text, type: 'defaultImport', ...moduleInfo, }) } else if (compilerOptions.allowSyntheticDefaultImports) { // treat it as import * as emotion from 'emotion' importCalls.push({ name: name.text, type: 'namespaceImport', ...moduleInfo, }) } } if (namedBindings) { // import { xxx } from 'lib' if (ts.isNamedImports(namedBindings)) { namedBindings.elements.forEach((node) => { // import { default as lib, a as alias, b } from 'lib' if ( // propertyName's existence means alias node.propertyName ? moduleInfo.exportedNames.includes(node.propertyName.text) || (node.propertyName.text === 'default' && moduleInfo.hasDefaultExport) : moduleInfo.exportedNames.includes(node.name.text) ) { importCalls.push({ name: node.name.text, type: 'namedImport', ...moduleInfo, }) } }) } else if (ts.isNamespaceImport(namedBindings)) { // import * as xxx from 'lib' importCalls.push({ name: namedBindings.name!.text, type: 'namespaceImport', ...moduleInfo, }) } } } } return importCalls } return (context) => { const importCalls: ImportInfo[] = [] const compilerOptions = context.getCompilerOptions() let sourcemapGenerator: SourceMapGenerator let emotionTargetClassNameCount = 0 let sourceFile: ts.SourceFile let inserted = false const visitor: ts.Visitor = (node) => { if (ts.isImportDeclaration(node)) { importCalls.push(...getImportCalls(node, compilerOptions)) // insert import { jsx [as jsxFactory] } from '@emotion/react' behind the react import declaration if ( !inserted && options.autoInject && // only for jsx: 'react' compilerOptions.jsx === ts.JsxEmit.React && (node.moduleSpecifier as ts.StringLiteral).text === 'react' ) { inserted = true return [ createImportJSXAst( options?.jsxFactory ?? compilerOptions.jsxFactory, ), node, ] } return node } if (options.autoLabel || options.sourcemap) { if (ts.isCallExpression(node)) { let { expression } = node if ( ts.isCallExpression(expression) || ts.isPropertyAccessExpression(expression) || ts.isIdentifier(expression) ) { const { expression: subExpression } = ts.isIdentifier(expression) ? node : (expression as ts.CallExpression | ts.PropertyAccessExpression) let transformedNode = node let updateCallFunction = () => transformedNode // styled.div({}) => styled('div')({}) if (ts.isPropertyAccessExpression(expression)) { const info = importCalls.find((importInfo) => { const expr = (expression as ts.PropertyAccessExpression) .expression return ( importInfo.styledName === (ts.isIdentifier(expr) ? expr.text : ts.isPropertyAccessExpression(expr) ? expr.name.text : '') ) }) if (info) { expression = FACTORY.createCallExpression( expression.expression, [], [FACTORY.createStringLiteral(expression.name.text)], ) } } const exp = ts.isCallExpression(expression) ? expression : null if (exp) { updateCallFunction = () => { if (exp.arguments.length >= 1) { const filename = sourceFile.fileName let moduleName = '' let rootPath = filename try { rootPath = getPackageRootPath(filename) moduleName = require(rootPath + '/package.json').name } catch (err) { // } const finalPath = filename === rootPath ? 'root' : filename.slice(rootPath.length) const positionInFile = emotionTargetClassNameCount++ const stuffToHash = [moduleName] if (finalPath) { stuffToHash.push(normalize(finalPath)) } else { stuffToHash.push(sourceFile.getText()) } const stableClassName = `e${hashArray( stuffToHash, )}${positionInFile}` const [el, opts] = exp.arguments const targetAssignment = FACTORY.createPropertyAssignment( FACTORY.createIdentifier('target'), FACTORY.createStringLiteral(stableClassName), ) const args = [el] args.push( FACTORY.createObjectLiteralExpression( opts && ts.isObjectLiteralExpression(opts) ? opts.properties.concat(targetAssignment) : [targetAssignment], true, ), ) const updatedCall = FACTORY.updateCallExpression( exp, exp.expression, exp.typeArguments, args, ) return FACTORY.updateCallExpression( transformedNode, updatedCall, transformedNode.typeArguments, transformedNode.arguments, ) } return transformedNode } } if ( ts.isIdentifier(subExpression) || ts.isPropertyAccessExpression(subExpression) ) { const importedInfo = ts.isIdentifier(subExpression) ? importCalls.find( (imported) => imported.name === subExpression.text, ) : importCalls.find( (imported) => imported.name === (subExpression.expression as ts.Identifier).text, ) if (importedInfo) { if (options.autoLabel) { const rawPath = sourceFile.fileName const localNameNode = (node.parent as ts.VariableDeclaration) .name if (localNameNode && ts.isIdentifier(localNameNode)) { const local = localNameNode.text const fileName = basename(rawPath, extname(rawPath)) transformedNode = FACTORY.updateCallExpression( transformedNode, transformedNode.expression, transformedNode.typeArguments, transformedNode.arguments.concat([ FACTORY.createStringLiteral( `label:${options .labelFormat!.replace('[local]', local) .replace('[filename]', fileName)};`, ), ]), ) } } if ( options.sourcemap && process.env.NODE_ENV !== 'production' ) { const sourceFileNode = node.getSourceFile() const lineAndCharacter = ts.getLineAndCharacterOfPosition( sourceFileNode, node.pos, ) const sourceFileName = relative( process.cwd(), sourceFileNode.fileName, ) sourcemapGenerator.addMapping({ generated: { line: 1, column: 0, }, source: sourceFileName, original: { line: lineAndCharacter.line + 1, column: lineAndCharacter.character + 1, }, }) sourcemapGenerator.setSourceContent( sourceFileName, sourceFileNode.text, ) const comment = convert .fromObject(sourcemapGenerator) .toComment({ multiline: true }) transformedNode = FACTORY.updateCallExpression( transformedNode, transformedNode.expression, transformedNode.typeArguments, transformedNode.arguments.concat([ FACTORY.createStringLiteral(comment), ]), ) } transformedNode = ts.addSyntheticLeadingComment( transformedNode, ts.SyntaxKind.MultiLineCommentTrivia, '#__PURE__', ) return updateCallFunction() } } } } } if ( ts.isJsxAttribute(node) && node.name.text === 'css' && (compilerOptions.jsx === ts.JsxEmit.ReactJSX || compilerOptions.jsx === ts.JsxEmit.ReactJSXDev) && !importCalls.find((info) => { return ( info.moduleName === '@emotion/react' && info.exportedNames.includes('jsx') ) }) ) { inserted = true } return ts.visitEachChild(node, visitor, context) } return (node) => { sourceFile = node sourcemapGenerator = new SourceMapGenerator({ file: basename(node.fileName), sourceRoot: '', }) const distNode = ts.visitNode(node, visitor) if (inserted && options.jsxImportSource && distNode.statements.length) { // fIXME // typeScript private API https://github.com/microsoft/TypeScript/pull/39199/files#diff-1516c8349f7a625a2e4a2aa60f6bbe84e4b1a499128e8705d3087d893e01d367R5974 // @ts-expect-error distNode.pragmas.set('jsximportsource', { arguments: { factory: options.jsxImportSource, }, }) } importCalls.length = 0 inserted = false emotionTargetClassNameCount = 0 return distNode } } }
the_stack
import { $el, bind, getBooleanTypeAttr, getStrTypeAttr, removeAttrs, setCss } from '../../dom-utils'; import { clickoutside, CssTransition, warn, _Popper } from '../../mixins'; import { type, validComps } from '../../utils'; interface Config { config( el: string ): { visible: boolean; events: ({ onClick, onVisibleChange }: DropdownEvents) => void; }; } interface DropdownEvents { onClick?: (key: string) => void; onVisibleChange?: (visible: boolean) => void; onClickOutside?: (event: Event) => void; } const DEFAULTDELAY = 80; const STATEKEY = 'visibleState'; const ITEMKEY = 'itemKey'; const DROPENTERCLS = 'transition-drop-enter'; const DROPLEAVECLS = 'transition-drop-leave'; let VISIBLETIMER: any = null, EVENTTIMER: any = null; class Dropdown implements Config { readonly VERSION: string; readonly COMPONENTS: NodeListOf<Element>; constructor() { this.VERSION = 'v2.0'; this.COMPONENTS = $el('r-dropdown', { all: true }); this._create(this.COMPONENTS); } public config( el: string ): { visible: boolean; events({ onClick, onVisibleChange, onClickOutside }: DropdownEvents): void; } { const target = $el(el) as HTMLElement; validComps(target, 'dropdown'); const { _attrs, _setVisible, _getChildDisabled } = Dropdown.prototype; const { trigger, placement } = _attrs(target); const DropdownRefElm = target.firstElementChild!; const DropdownMenu = target.querySelector('r-dropdown-menu')! as HTMLElement; const DropdownItem = DropdownMenu.querySelectorAll('r-dropdown-item'); return { get visible() { return DropdownMenu.dataset[STATEKEY] === 'visible'; }, set visible(newVal: boolean) { if (newVal && !type.isBol(newVal)) return; _setVisible(target, DropdownMenu, newVal, placement); }, events({ onClick, onVisibleChange, onClickOutside }) { // onVisibleChange const visibleChange = () => { setTimeout(() => { const visible = DropdownMenu.dataset[STATEKEY] === 'visible'; onVisibleChange && type.isFn(onVisibleChange, visible); }, DEFAULTDELAY); }; // onClick const itemClickEv = (elem: Element) => { if (_getChildDisabled(elem)) return false; // @ts-ignore const key = elem.dataset[ITEMKEY]; visibleChange(); onClick && type.isFn(onClick, key); }; if (trigger === 'hover') { bind(target, 'mouseenter', () => { if (EVENTTIMER) clearTimeout(EVENTTIMER); EVENTTIMER = setTimeout(visibleChange, DEFAULTDELAY); }); bind(target, 'mouseleave', () => { if (EVENTTIMER) clearTimeout(EVENTTIMER); if (DropdownMenu.dataset[STATEKEY] === 'visible') setTimeout(visibleChange, DEFAULTDELAY); }); } if (trigger === 'click' || trigger === 'contextMenu') { onClickOutside && clickoutside(target, onClickOutside, DropdownMenu, STATEKEY, 'visible'); } if (trigger === 'click') { bind(DropdownRefElm, 'click', visibleChange); } if (trigger === 'contextMenu') { bind(DropdownRefElm, 'contextmenu', visibleChange); } DropdownItem.forEach((child) => bind(child, 'click', () => itemClickEv(child))); } }; } private _create(COMPONENTS: NodeListOf<Element>): void { COMPONENTS.forEach((node) => { if (!this._correctCompositionNodes(node)) return; const { trigger, placement, visible, stopPropagation } = this._attrs(node); const DropdownMenu = node.querySelector('r-dropdown-menu')! as HTMLElement; const DropdownItem = DropdownMenu.querySelector('r-dropdown-item')! as HTMLElement; const { key } = this._attrs(DropdownItem); this._setVisible(node, DropdownMenu, visible, placement); this._setChildKey(DropdownItem, key); this._setStopPropagation(stopPropagation, node, DropdownMenu); this._handleTrigger(trigger, placement, node, DropdownMenu); this._handleItemClick(trigger, node, DropdownMenu, placement); removeAttrs(node, ['key', 'trigger', 'placement', 'visible', 'stop-propagation']); }); } private _correctCompositionNodes(node: Element): boolean { if (node.firstElementChild?.tagName === 'R-DROPDOWN-MENU') { warn( '👇 The first child element must be the reference element used to trigger the menu display hidden, not r-dropdown-menu' ); console.error(node); return false; } if (node.lastElementChild!.tagName !== 'R-DROPDOWN-MENU') { warn('👇 The last child element tag must be made up of r-dropdown-menu'); console.error(node); return false; } if (node.childElementCount > 2) { warn('👇 The number of child element nodes in this r-dropdown tag cannot exceed two'); console.error(node); return false; } return true; } private _setStopPropagation(stop: boolean, node: Element, child: HTMLElement): void { if (!stop) return; bind(node, 'click', (e: MouseEvent) => e.stopPropagation()); bind(child, 'click', (e: MouseEvent) => e.stopPropagation()); } private _handleTrigger( type: string, placement: string, node: Element, child: HTMLElement ): void { if (type === 'custom') return; const referenceElem = node.firstElementChild!; // 触发菜单显示隐藏的引用元素如果是禁用状态则不做操作 if (/disabled/.test(referenceElem.className)) return; if (this._getChildDisabled(referenceElem)) return; const showMenu = () => { if (VISIBLETIMER) clearTimeout(VISIBLETIMER); if (child.dataset[STATEKEY] === 'visible') return; VISIBLETIMER = setTimeout( () => this._setVisible(node, child, true, placement), DEFAULTDELAY ); }; const hidenMenu = () => { if (VISIBLETIMER) clearTimeout(VISIBLETIMER); if (child.dataset[STATEKEY] === 'visible') { setTimeout(() => this._setVisible(node, child, false, placement), DEFAULTDELAY); } }; const clickIsShow = (e: MouseEvent) => { e.stopPropagation(); if (child.dataset[STATEKEY] === 'hidden') { showMenu(); } else { hidenMenu(); } }; if (type === 'hover') { bind(node, 'mouseenter', showMenu); bind(node, 'mouseleave', hidenMenu); } // 点击菜单栏以外的地方隐藏 if (type === 'click' || type === 'contextMenu') { clickoutside(node, hidenMenu); } if (type === 'click') { bind(referenceElem, 'click', (e: MouseEvent) => clickIsShow(e)); } if (type === 'contextMenu') { bind(referenceElem, 'contextmenu', (e: MouseEvent) => { e.preventDefault(); clickIsShow(e); }); } } private _handleItemClick( type: string, node: Element, child: HTMLElement, placement: string ): void { if (type === 'custom') return; const DropdownItems = child.querySelectorAll('r-dropdown-item'); DropdownItems.forEach((item) => bind(item, 'click', () => { if (this._getChildDisabled(item)) return; this._setVisible(node, child, false, placement); }) ); } private _setChildKey(child: HTMLElement, key: string): void { if (key) { child.dataset[ITEMKEY] = key; child.removeAttribute('key'); } } private _setVisible( node: Element, child: HTMLElement, visible: boolean, placement: string ): void { const { _setPlacement, _setTransitionDrop } = Dropdown.prototype; if (visible) { child.dataset[STATEKEY] = 'visible'; _setPlacement(node, child, placement); _setTransitionDrop('in', child); } else { child.dataset[STATEKEY] = 'hidden'; setTimeout(() => { child.dataset[STATEKEY] === 'hidden' && _setTransitionDrop('out', child); }, 0); } } private _setPlacement(node: Element, child: HTMLElement, placement: string): void { const popperPlacement = child.dataset['popperPlacement'] || placement; if (/^top|right-end|left-end/.test(popperPlacement)) { setCss(child, 'transformOrigin', 'center bottom'); } if (/^bottom|right-start|left-start/.test(popperPlacement)) { setCss(child, 'transformOrigin', 'center top'); } _Popper._newCreatePopper(node, child, placement, 0); } private _setTransitionDrop(type: 'in' | 'out', child: HTMLElement): void { const transitionCls = type === 'in' ? { enterCls: DROPENTERCLS } : { leaveCls: DROPLEAVECLS }; CssTransition(child, { inOrOut: type, ...transitionCls, rmCls: true, timeout: 290 }); } private _getChildDisabled(elem: Element): boolean { if ( elem.getAttribute('disabled') === 'disabled' || elem.getAttribute('disabled') === 'true' || elem.getAttribute('disabled') === '' ) { return true; } return false; } private _attrs(node: Element) { return { key: getStrTypeAttr(node, 'key', ''), trigger: getStrTypeAttr(node, 'trigger', 'hover'), placement: getStrTypeAttr(node, 'placement', 'bottom'), visible: getBooleanTypeAttr(node, 'visible'), stopPropagation: getBooleanTypeAttr(node, 'stop-propagation') }; } } export default Dropdown;
the_stack
import axios from "axios"; import { autobind } from "core-decorators"; import * as _ from "lodash"; import { inject, observer } from "mobx-react"; import * as React from "react"; import { Button, Divider, Dropdown, Form, Header, Icon, Image, Input, Message, Reveal, Segment, } from "semantic-ui-react"; import { allowedItunesCategories } from "../../../lib/constants"; import { IPodcast } from "../../../lib/interfaces"; import { colors, globalStyles } from "../../../lib/styles"; import { RootState } from "../../../state/RootState"; import AvatarEditor from "../generic/AvatarEditor"; interface IPodcastFormProps { onSubmit: (formState: IPodcastFields) => Promise<void>; getUploadPolicy: (file: File) => Promise<{ uploadUrl: string, publicFileUrl: string }>; uploadFile: (file: File, policyUrl: string) => Promise<void>; currentPodcast?: IPodcast; saveButtonTitle?: string; rootState?: RootState; } export interface IPodcastFields { title: string; subtitle: string; author: string; keywords: string; categories: string; imageUrl: string; email: string; _id?: any; } export interface IPodcastFormState { fields: IPodcastFields; uploading: boolean; imagePreviewUrl: string; error: string; categoryWarning: string; isCropping: boolean; file?: any; } @inject("rootState") @observer export default class PodcastForm extends React.Component<IPodcastFormProps, IPodcastFormState> { public state: IPodcastFormState = { uploading: false, imagePreviewUrl: null, error: null, fields: { title: "", subtitle: "", author: "", keywords: "", categories: "", imageUrl: "", email: "" }, categoryWarning: null, isCropping: false, }; constructor(props: IPodcastFormProps) { super(); if (props.currentPodcast) { const userEmail = _.get(props, "rootState.me.email", ""); const { title, subtitle, author, keywords, categories, imageUrl, email } = props.currentPodcast; this.state = { fields: { title, subtitle, author, keywords, categories, imageUrl, email: email || userEmail }, uploading: false, imagePreviewUrl: null, error: null, categoryWarning: null, isCropping: false, }; } } @autobind public render() { const userEmail = _.get(this.props, "rootState.me.email", ""); return ( <Segment> {this.renderError()} <Form onSubmit={this.onSubmit} loading={this.state.uploading}> <Header as="h1" style={{ color: colors.mainDark }}> Tell us about your podcast </Header> <p> <div style={styles.imagePreview} > <Reveal animated="fade" onClick={this.onFileUploadClick}> <Reveal.Content visible> <Image src={ // tslint:disable-next-line:max-line-length this.state.imagePreviewUrl || this.state.fields.imageUrl || "/assets/image.png" } size="small" centered spaced /> </Reveal.Content> <Reveal.Content hidden> <Icon name="upload" size="massive" style={styles.uploadIcon} /> </Reveal.Content> </Reveal> </div> <input ref="podcastImgRef" onChange={this.onFileInput} type="file" style={styles.hidenInput} /> <Header subheader as="h5" color="grey" centered> Image must be between 1400 X 1400 and 3000 X 3000 </Header> </p> <div style={{ marginLeft: -80, }}> <Form.Field inline required> <label style={styles.formLabel}>Title</label> <Input style={styles.formInput} name="title" value={this.state.fields.title} onChange={this.onChangeInputField} required /> </Form.Field> <Form.Field inline required> <label style={styles.formLabel}>Subtitle</label> <Input style={styles.formInput} name="subtitle" value={this.state.fields.subtitle} onChange={this.onChangeInputField} required /> </Form.Field> <Form.Field inline required> <label style={styles.formLabel}>Author</label> <Input style={styles.formInput} name="author" value={this.state.fields.author} onChange={this.onChangeInputField} required /> </Form.Field> <Form.Field inline required> <label style={styles.formLabel}>Email</label> <Input style={styles.formInput} name="email" value={this.state.fields.email || userEmail} onChange={this.onChangeInputField} required /> </Form.Field> <Form.Field inline required> <label style={styles.formLabel}>Keywords</label> <Input style={styles.formInput} name="keywords" value={this.state.fields.keywords} onChange={this.onChangeInputField} required /> </Form.Field> <div style={{ display: "flex", flex: 1, justifyContent: "center", }}> {this.state.categoryWarning ? <Message floating style={{ width: "50%", marginLeft: 90, marginBottom: 15 }} color="red">{this.state.categoryWarning}</Message> : null } </div> <Form.Field inline required> <label style={styles.formLabel}>Categories</label> <Dropdown value={this.state.fields.categories ? this.state.fields.categories.split(",").map(x => x.trim()) : null} placeholder="Technology" multiple selection upward compact inline style={styles.dropdownInput} options={this.getCategories()} onChange={(e, input) => { const categories = this.state.fields.categories.split(","); input.value = _.filter((input.value as string[]), (val) => { return !!val; }); if ((input.value as string[]).length > 3) { this.setState({ categoryWarning: "Only 3 categories are allowed." }); } else { this.setState({ categoryWarning: "", fields: { ...this.state.fields, categories: (input.value as string[]).join(","), }, }); } }} /> </Form.Field> </div> <Form.Button style={{ backgroundColor: colors.mainDark, color: "white", marginTop: 30 }}> {this.props.saveButtonTitle || "Save"} </Form.Button> </Form> <AvatarEditor onFile={(file) => this.onEditedFile(file)} onClose={() => this.setState({ isCropping: false })} file={this.state.file} isOpen={this.state.isCropping} /> </Segment> ); } @autobind protected onEditedFile(file) { this.setState({ uploading: true, isCropping: false }); const reader = new FileReader(); reader.readAsDataURL(file); reader.onloadend = () => { this.setState({ imagePreviewUrl: reader.result, error: null }); const img = document.createElement("img"); this.props.getUploadPolicy(file).then(async (policyData) => { const { uploadUrl, publicFileUrl } = policyData; await this.props.uploadFile(file, uploadUrl); // tslint:disable-next-line:prefer-object-spread const fields = Object.assign({}, this.state.fields, { imageUrl: publicFileUrl }); this.setState({ fields, uploading: false }); }).catch((err: Error) => { alert(err.message); this.setState({ uploading: false }); }); img.src = reader.result; }; } @autobind protected onFileUploadClick(e: MouseEvent) { const inputField: any = this.refs.podcastImgRef; inputField.click(); } @autobind protected onFileInput(e: React.ChangeEvent<HTMLInputElement>) { e.preventDefault(); if (e.target && e.target.files && e.target.files.length) { const file = e.target.files[0]; const reader = new FileReader(); reader.onloadend = () => { this.setState({ imagePreviewUrl: reader.result, error: null }); const img = document.createElement("img"); img.onload = () => { // Check if width and height are between 1400X1400 and 3000X3000 if ((this as any).width < 1400 || (this as any).width > 3000 || (this as any).height < 1400 || (this as any).height > 3000) { // We only check the width since we know that the width and height are equal return this.setState({ uploading: false, imagePreviewUrl: null, error: "Invalid image dimensions, width and height must" + " be between 1400 X 1400 and 3000 X 3000.", }); } this.setState({ isCropping: true, file }); }; img.src = reader.result; }; reader.readAsDataURL(file); } } protected renderError() { if (!this.state.error) { return null; } return ( <Message error header="Error" content={this.state.error} /> ); } @autobind protected onChangeInputField(e: React.ChangeEvent<HTMLInputElement>, input: any) { if (input && input.name) { // tslint:disable-next-line:prefer-object-spread const fields = Object.assign({}, this.state.fields, { [input.name]: input.value }); this.setState({ fields }); } } @autobind protected async onSubmit(e: React.SyntheticEvent<Event>) { e.preventDefault(); const fields = JSON.parse(JSON.stringify(this.state.fields)); if (!fields.email) { const userEmail = _.get(this.props, "rootState.me.email", ""); fields.email = userEmail; } await this.props.onSubmit(fields); } private getCategories(): Array<{ key: string, text: string, value: string }> { const result: Array<{ key: string, text: string, value: string, }> = []; Object.keys(allowedItunesCategories).forEach(category => { result.push({ key: category, text: category, value: category, }); allowedItunesCategories[category].forEach(subCategory => { result.push({ key: `${category} - ${subCategory}`, text: `${category} - ${subCategory}`, value: `${category} - ${subCategory}`, }); }); }); return result; } } const styles = { formLabel: { display: "inline-block", width: 100, maxWidth: "50%", textAlign: "left", fontSize: "120%" as "120%", fontWeight: 300 as 300, }, dropdownInput: { width: "50%", }, formInput: { minWidth: "50%", }, hidenInput: { display: "none", visibility: "hidden", }, imagePreview: { width: 150, height: 150, backgroundColor: "#ECECEC", cursor: "pointer", margin: "auto", }, uploadIcon: { margin: 10 }, };
the_stack
export const STATE_IDLE = "Idle"; export const STATE_RUN = "Run"; export const STATE_HOLD = "Hold"; export const STATE_HOME = "Home"; export const STATE_ALARM = "Alerm"; export const STATE_CHECK = "Check"; export const STATE_DOOR = "Door"; // Special state for disconnected export const STATE_UNKNOWN = "Unknown"; const MESSAGE_STARTUP = /^Grbl (\d\.\d)(.)/; const MESSAGE_OK = /^ok$/; const MESSAGE_ERROR = /^error:(.+)$/; const MESSAGE_ALARM = /^ALARM:(.+)$/; const MESSAGE_FEEDBACK = /^\[(.+)\]$/; const MESSAGE_STATUS = /^<(.+)>$/; const MESSAGE_DOLLAR = /^\$/; export interface GrblVersion { major: number; minor: string; } export interface GrblPosition { x : number; y : number; z : number; } export interface GrblSerialPortError { message: string; } export class GrblLineParserResult { raw: string; constructor(raw: string) { this.raw = raw; } toObject(copy: { [key: string]: any }):{ [key: string]: any } { var ret: { [key: string]: any } = {}; Object.keys(this).forEach( (key: string)=> { ret[key] = (<any>this)[key]; }); if (copy) { Object.keys(copy).forEach( (key: string)=> { ret[key] = copy[key]; }); } return ret; } } export class GrblLineParserResultStartup extends GrblLineParserResult { version: GrblVersion; static parse(line: string) { if (!MESSAGE_STARTUP.test(line)) return null; var ret = new this(line); ret.version = <GrblVersion>{ major: +RegExp.$1, minor: RegExp.$2, }; return ret; } } export class GrblLineParserResultOk extends GrblLineParserResult { static parse(line: string) { if (!MESSAGE_OK.test(line)) return null; return new this(line); } } export class GrblLineParserResultError extends GrblLineParserResult { message: string; static parse(line: string) { if (!MESSAGE_ERROR.test(line)) return null; var ret = new this(line); ret.message = RegExp.$1; return ret; } } export class GrblLineParserResultAlarm extends GrblLineParserResult { message: string; static parse(line: string) { if (!MESSAGE_ALARM.test(line)) return null; var ret = new this(line); ret.message = RegExp.$1; return ret; } } export class GrblLineParserResultFeedback extends GrblLineParserResult { message: string; static parse(line: string) { if (!MESSAGE_FEEDBACK.test(line)) return null; var ret = new this(line); ret.message = RegExp.$1; return ret; } } export class GrblLineParserResultDollar extends GrblLineParserResult { static parse(line: string) { if (!MESSAGE_DOLLAR.test(line)) return null; var ret = new this(line); return ret; } } export class GrblLineParserResultStatus extends GrblLineParserResult { state: string; machinePosition: GrblPosition; workingPosition: GrblPosition; plannerBufferCount: number; rxBufferCount: number; static UNKNOWN = new GrblLineParserResultStatus(null); static parse(line: string) { if (!MESSAGE_STATUS.test(line)) return null; var ret = new this(line); let params = RegExp.$1.split(/,/); ret.state = params.shift(); let map : { [name: string]:Array<string>; } = {}; let current: string; for (let i = 0, len = params.length; i < len; i++) { let param: string = params[i]; if (/^(.+):(.+)/.test(param)) { current = RegExp.$1; param = RegExp.$2; map[current] = new Array<string>(); } if (!current) { throw "Illegal status format: " + line; } map[current].push(param); } ret.machinePosition = <GrblPosition>{ x: +map['MPos'][0], y: +map['MPos'][1], z: +map['MPos'][2], }; ret.workingPosition = <GrblPosition>{ x: +map['WPos'][0], y: +map['WPos'][1], z: +map['WPos'][2], }; if (map.hasOwnProperty('Buf')) { ret.plannerBufferCount = +map['Buf'][0]; } if (map.hasOwnProperty('RX')) { ret.rxBufferCount = +map['RX'][0]; } return ret; } constructor(raw: string) { super(raw); this.state = STATE_UNKNOWN; this.machinePosition = { x: 0, y: 0, z: 0}; this.workingPosition = { x: 0, y: 0, z: 0}; } equals(other: GrblLineParserResultStatus): boolean { var ret = this.state === other.state && this.plannerBufferCount === other.plannerBufferCount && this.rxBufferCount === other.rxBufferCount && this.machinePosition.x === other.machinePosition.x && this.machinePosition.y === other.machinePosition.y && this.machinePosition.z === other.machinePosition.z && this.workingPosition.x === other.workingPosition.x && this.workingPosition.y === other.workingPosition.y && this.workingPosition.z === other.workingPosition.z; return ret; } } export class GrblLineParser { constructor() { } parse(line: string): GrblLineParserResult { const parsers = [ GrblLineParserResultStatus, GrblLineParserResultOk, GrblLineParserResultError, GrblLineParserResultAlarm, GrblLineParserResultFeedback, GrblLineParserResultDollar, GrblLineParserResultStartup ]; for (let i = 0, it: { parse: (line: string)=> GrblLineParserResult }; (it = parsers[i]); i++) { var result = it.parse(line); if (result) { return result; } } // console.log("unknown message: " + line); return null; } } export interface SerialPort { // node-serialport compatible open(cb: (err: any) => void): any; on(ev: string, cb: (e: any) => void): any; write(d: string): any; write(d: string, cb: (err: any, results: any) => void): any; close(cb: (err: any) => void): any; } import events = require("events"); export class Grbl extends events.EventEmitter { status : GrblLineParserResultStatus; lastFeedback: GrblLineParserResultFeedback; lastAlarm: GrblLineParserResultAlarm; serialport : SerialPort; parser : GrblLineParser; isOpened: boolean; isClosing: boolean; statusQueryTimer: NodeJS.Timer; waitingQueue: Array< (err: any) => void >; DEBUG: boolean; constructor(serialport: SerialPort) { super(); this.status = GrblLineParserResultStatus.UNKNOWN; this.serialport = serialport; this.parser = new GrblLineParser(); this.isOpened = false; this.waitingQueue = []; this.DEBUG = false; } open():Promise<any> { this.on("startup", (r: GrblLineParserResultStartup) => { this.waitingQueue = []; this.stopQueryStatus(); this.realtimeCommand("?"); this.startQueryStatus(); }); return new Promise( (resolve, reject) => { this.serialport.open( (err) => { if (err) { this.emit('error', <GrblSerialPortError>{ message: 'error on opening serialport' }); reject(err); return; } this.isOpened = true; this.reset(); this.serialport.on("data", (data) => { this.processData(data); }); this.serialport.on("close", () => { if (!this.isClosing) { this.emit('error', <GrblSerialPortError>{ message: 'unexpected close on the serialport' }); } this.destroy(); }); this.serialport.on("error", (err) => { this.emit('error', <GrblSerialPortError>{ message: 'unexpected error on the serialport' }); this.destroy(); }); this.once("startup", (r: GrblLineParserResultStartup) => { resolve(); }); }); }); } startQueryStatus() { this.statusQueryTimer = setTimeout( () => { this.getStatus(); if (this.isOpened) { this.startQueryStatus(); } }, 1/10 * 1000); } stopQueryStatus() { clearTimeout(this.statusQueryTimer); this.statusQueryTimer = null; } close():Promise<any> { return new Promise( (resolve, reject) => { this.isClosing = true; this.reset(); this.serialport.close((err) => { if (err) reject(err); this.destroy(); resolve(); }); }); } destroy() { if (this.isOpened) { this.isOpened = false; this.stopQueryStatus(); this.status = GrblLineParserResultStatus.UNKNOWN; this.emit("statuschange", this.status); } } getConfig():Promise<Array<GrblLineParserResultDollar>> { return new Promise( (resolve, reject) => { if (this.status.state != STATE_IDLE) { reject('Must called in idle state'); } var results: Array<GrblLineParserResultDollar> = []; var listener = (e: GrblLineParserResultDollar) => { results.push(e); }; this.on("dollar", listener); this.command("$$"). then( () => { this.removeListener("dollar", listener); resolve(results); }, reject); }); } getStatus():Promise<any> { return new Promise( (resolve, reject) => { if (this.status.state !== STATE_ALARM && this.status.state !== STATE_HOME ) { this.once("status", (res: GrblLineParserResultStatus) => { resolve(res); }); this.realtimeCommand("?"); } else { reject("state is alarm or homing"); } }); } command(cmd: string):Promise<any> { var ret = new Promise( (resolve, reject) => { if (this.DEBUG) console.log('>>', cmd); this.serialport.write(cmd + '\n'); this.waitingQueue.push( (err: any) => { if (err) return reject(err); resolve(); }); }); if (cmd === '$H') { // command "?" is not usable in homing var prevState = this.status.state; this.status.state = STATE_HOME; this.stopQueryStatus(); this.emit("statuschange", this.status); this.emit("status", this.status); ret = ret.then( (): any => { this.status.state = prevState; this.startQueryStatus(); } ); } return ret; } realtimeCommand(cmd: string) { this.serialport.write(cmd); } reset() { this.realtimeCommand("\x18"); } processData(data: string) { data = data.replace(/\s+$/, ''); if (this.DEBUG) console.log('<<', data); if (!data) return; this.emit("raw", data); var result = this.parser.parse(data); if (!result) return; this.emit("response", result); if (result instanceof GrblLineParserResultStatus) { if (!this.status.equals(result)) { this.emit("statuschange", result); } this.status = result; this.emit("status", result); } else if (result instanceof GrblLineParserResultOk) { // callback maybe null after reseting var callback = this.waitingQueue.shift(); if (callback) callback(null); } else if (result instanceof GrblLineParserResultError) { // callback maybe null after reseting var callback = this.waitingQueue.shift(); if (callback) callback(result); } else if (result instanceof GrblLineParserResultStartup) { this.emit("startup", result); } else if (result instanceof GrblLineParserResultAlarm) { // command "?" is not usable in alarm, // so set state by hand this.status.state = STATE_ALARM; this.lastAlarm = result; this.emit("alarm", result); this.emit("statuschange", this.status); this.emit("status", this.status); } else if (result instanceof GrblLineParserResultFeedback) { this.lastFeedback = result; this.emit("feedback", result); } else if (result instanceof GrblLineParserResultDollar) { this.emit("dollar", result); } } }
the_stack
import { css } from 'styled-components'; /** * Swiper 6.7.0 * Most modern mobile touch slider and framework with hardware accelerated transitions * https://swiperjs.com * * Copyright 2014-2021 Vladimir Kharlampidi * * Released under the MIT License * * Released on: May 31, 2021 */ const swiperStyle = css` :root { --swiper-theme-color: #007aff; } .swiper-container { margin-left: auto; margin-right: auto; position: relative; overflow: hidden; list-style: none; padding: 0; /* Fix of Webkit flickering */ z-index: 1; } .swiper-container-vertical > .swiper-wrapper { flex-direction: column; } .swiper-wrapper { position: relative; width: 100%; height: 100%; z-index: 1; display: flex; transition-property: transform; box-sizing: content-box; } .swiper-container-android .swiper-slide, .swiper-wrapper { transform: translate3d(0px, 0, 0); } .swiper-container-multirow > .swiper-wrapper { flex-wrap: wrap; } .swiper-container-multirow-column > .swiper-wrapper { flex-wrap: wrap; flex-direction: column; } .swiper-container-free-mode > .swiper-wrapper { transition-timing-function: ease-out; margin: 0 auto; } .swiper-container-pointer-events { touch-action: pan-y; } .swiper-container-pointer-events.swiper-container-vertical { touch-action: pan-x; } .swiper-slide { flex-shrink: 0; width: 100%; height: 100%; position: relative; transition-property: transform; } .swiper-slide-invisible-blank { visibility: hidden; } /* Auto Height */ .swiper-container-autoheight, .swiper-container-autoheight .swiper-slide { height: auto; } .swiper-container-autoheight .swiper-wrapper { align-items: flex-start; transition-property: transform, height; } /* 3D Effects */ .swiper-container-3d { perspective: 1200px; } .swiper-container-3d .swiper-wrapper, .swiper-container-3d .swiper-slide, .swiper-container-3d .swiper-slide-shadow-left, .swiper-container-3d .swiper-slide-shadow-right, .swiper-container-3d .swiper-slide-shadow-top, .swiper-container-3d .swiper-slide-shadow-bottom, .swiper-container-3d .swiper-cube-shadow { transform-style: preserve-3d; } .swiper-container-3d .swiper-slide-shadow-left, .swiper-container-3d .swiper-slide-shadow-right, .swiper-container-3d .swiper-slide-shadow-top, .swiper-container-3d .swiper-slide-shadow-bottom { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; z-index: 10; } .swiper-container-3d .swiper-slide-shadow-left { background-image: linear-gradient(to left, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0)); } .swiper-container-3d .swiper-slide-shadow-right { background-image: linear-gradient(to right, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0)); } .swiper-container-3d .swiper-slide-shadow-top { background-image: linear-gradient(to top, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0)); } .swiper-container-3d .swiper-slide-shadow-bottom { background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0)); } /* CSS Mode */ .swiper-container-css-mode > .swiper-wrapper { overflow: auto; scrollbar-width: none; /* For Firefox */ -ms-overflow-style: none; /* For Internet Explorer and Edge */ } .swiper-container-css-mode > .swiper-wrapper::-webkit-scrollbar { display: none; } .swiper-container-css-mode > .swiper-wrapper > .swiper-slide { scroll-snap-align: start start; } .swiper-container-horizontal.swiper-container-css-mode > .swiper-wrapper { scroll-snap-type: x mandatory; } .swiper-container-vertical.swiper-container-css-mode > .swiper-wrapper { scroll-snap-type: y mandatory; } :root { --swiper-navigation-size: 44px; /* --swiper-navigation-color: var(--swiper-theme-color); */ } .swiper-button-prev, .swiper-button-next { position: absolute; top: 50%; width: calc(var(--swiper-navigation-size) / 44 * 27); height: var(--swiper-navigation-size); margin-top: calc(0px - (var(--swiper-navigation-size) / 2)); z-index: 10; cursor: pointer; display: flex; align-items: center; justify-content: center; color: var(--swiper-navigation-color, var(--swiper-theme-color)); } .swiper-button-prev.swiper-button-disabled, .swiper-button-next.swiper-button-disabled { opacity: 0.35; cursor: auto; pointer-events: none; } .swiper-button-prev:after, .swiper-button-next:after { font-family: swiper-icons; font-size: var(--swiper-navigation-size); text-transform: none !important; letter-spacing: 0; text-transform: none; font-variant: initial; line-height: 1; } .swiper-button-prev, .swiper-container-rtl .swiper-button-next { left: 10px; right: auto; } .swiper-button-next, .swiper-container-rtl .swiper-button-prev { right: 10px; left: auto; } .swiper-button-prev.swiper-button-white, .swiper-button-next.swiper-button-white { --swiper-navigation-color: #ffffff; } .swiper-button-prev.swiper-button-black, .swiper-button-next.swiper-button-black { --swiper-navigation-color: #000000; } .swiper-button-lock { display: none; } :root { /* --swiper-pagination-color: var(--swiper-theme-color); */ } .swiper-pagination { position: absolute; text-align: center; transition: 300ms opacity; transform: translate3d(0, 0, 0); z-index: 10; } .swiper-pagination.swiper-pagination-hidden { opacity: 0; } /* Common Styles */ .swiper-pagination-fraction, .swiper-pagination-custom, .swiper-container-horizontal > .swiper-pagination-bullets { bottom: 10px; left: 0; width: 100%; } /* Bullets */ .swiper-pagination-bullets-dynamic { overflow: hidden; font-size: 0; } .swiper-pagination-bullets-dynamic .swiper-pagination-bullet { transform: scale(0.33); position: relative; } .swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active { transform: scale(1); } .swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-main { transform: scale(1); } .swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-prev { transform: scale(0.66); } .swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-prev-prev { transform: scale(0.33); } .swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-next { transform: scale(0.66); } .swiper-pagination-bullets-dynamic .swiper-pagination-bullet-active-next-next { transform: scale(0.33); } .swiper-pagination-bullet { width: 8px; height: 8px; display: inline-block; border-radius: 50%; background: #000; opacity: 0.2; } button.swiper-pagination-bullet { border: none; margin: 0; padding: 0; box-shadow: none; -webkit-appearance: none; appearance: none; } .swiper-pagination-clickable .swiper-pagination-bullet { cursor: pointer; } .swiper-pagination-bullet-active { opacity: 1; background: var(--swiper-pagination-color, var(--swiper-theme-color)); } .swiper-container-vertical > .swiper-pagination-bullets { right: 10px; top: 50%; transform: translate3d(0px, -50%, 0); } .swiper-container-vertical > .swiper-pagination-bullets .swiper-pagination-bullet { margin: 6px 0; display: block; } .swiper-container-vertical > .swiper-pagination-bullets.swiper-pagination-bullets-dynamic { top: 50%; transform: translateY(-50%); width: 8px; } .swiper-container-vertical > .swiper-pagination-bullets.swiper-pagination-bullets-dynamic .swiper-pagination-bullet { display: inline-block; transition: 200ms transform, 200ms top; } .swiper-container-horizontal > .swiper-pagination-bullets .swiper-pagination-bullet { margin: 0 4px; } .swiper-container-horizontal > .swiper-pagination-bullets.swiper-pagination-bullets-dynamic { left: 50%; transform: translateX(-50%); white-space: nowrap; } .swiper-container-horizontal > .swiper-pagination-bullets.swiper-pagination-bullets-dynamic .swiper-pagination-bullet { transition: 200ms transform, 200ms left; } .swiper-container-horizontal.swiper-container-rtl > .swiper-pagination-bullets-dynamic .swiper-pagination-bullet { transition: 200ms transform, 200ms right; } /* Progress */ .swiper-pagination-progressbar { background: rgba(0, 0, 0, 0.25); position: absolute; } .swiper-pagination-progressbar .swiper-pagination-progressbar-fill { background: var(--swiper-pagination-color, var(--swiper-theme-color)); position: absolute; left: 0; top: 0; width: 100%; height: 100%; transform: scale(0); transform-origin: left top; } .swiper-container-rtl .swiper-pagination-progressbar .swiper-pagination-progressbar-fill { transform-origin: right top; } .swiper-container-horizontal > .swiper-pagination-progressbar, .swiper-container-vertical > .swiper-pagination-progressbar.swiper-pagination-progressbar-opposite { width: 100%; height: 4px; left: 0; top: 0; } .swiper-container-vertical > .swiper-pagination-progressbar, .swiper-container-horizontal > .swiper-pagination-progressbar.swiper-pagination-progressbar-opposite { width: 4px; height: 100%; left: 0; top: 0; } .swiper-pagination-white { --swiper-pagination-color: #ffffff; } .swiper-pagination-black { --swiper-pagination-color: #000000; } .swiper-pagination-lock { display: none; } /* Scrollbar */ .swiper-scrollbar { border-radius: 10px; position: relative; -ms-touch-action: none; background: rgba(0, 0, 0, 0.1); } .swiper-container-horizontal > .swiper-scrollbar { position: absolute; left: 1%; bottom: 3px; z-index: 50; height: 5px; width: 98%; } .swiper-container-vertical > .swiper-scrollbar { position: absolute; right: 3px; top: 1%; z-index: 50; width: 5px; height: 98%; } .swiper-scrollbar-drag { height: 100%; width: 100%; position: relative; background: rgba(0, 0, 0, 0.5); border-radius: 10px; left: 0; top: 0; } .swiper-scrollbar-cursor-drag { cursor: move; } .swiper-scrollbar-lock { display: none; } .swiper-zoom-container { width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; text-align: center; } .swiper-zoom-container > img, .swiper-zoom-container > svg, .swiper-zoom-container > canvas { max-width: 100%; max-height: 100%; object-fit: contain; } .swiper-slide-zoomed { cursor: move; } /* Preloader */ :root { /* --swiper-preloader-color: var(--swiper-theme-color); */ } .swiper-lazy-preloader { width: 42px; height: 42px; position: absolute; left: 50%; top: 50%; margin-left: -21px; margin-top: -21px; z-index: 10; transform-origin: 50%; animation: swiper-preloader-spin 1s infinite linear; box-sizing: border-box; border: 4px solid var(--swiper-preloader-color, var(--swiper-theme-color)); border-radius: 50%; border-top-color: transparent; } .swiper-lazy-preloader-white { --swiper-preloader-color: #fff; } .swiper-lazy-preloader-black { --swiper-preloader-color: #000; } @keyframes swiper-preloader-spin { 100% { transform: rotate(360deg); } } /* a11y */ .swiper-container .swiper-notification { position: absolute; left: 0; top: 0; pointer-events: none; opacity: 0; z-index: -1000; } .swiper-container-fade.swiper-container-free-mode .swiper-slide { transition-timing-function: ease-out; } .swiper-container-fade .swiper-slide { pointer-events: none; transition-property: opacity; } .swiper-container-fade .swiper-slide .swiper-slide { pointer-events: none; } .swiper-container-fade .swiper-slide-active, .swiper-container-fade .swiper-slide-active .swiper-slide-active { pointer-events: auto; } .swiper-container-cube { overflow: visible; } .swiper-container-cube .swiper-slide { pointer-events: none; -webkit-backface-visibility: hidden; backface-visibility: hidden; z-index: 1; visibility: hidden; transform-origin: 0 0; width: 100%; height: 100%; } .swiper-container-cube .swiper-slide .swiper-slide { pointer-events: none; } .swiper-container-cube.swiper-container-rtl .swiper-slide { transform-origin: 100% 0; } .swiper-container-cube .swiper-slide-active, .swiper-container-cube .swiper-slide-active .swiper-slide-active { pointer-events: auto; } .swiper-container-cube .swiper-slide-active, .swiper-container-cube .swiper-slide-next, .swiper-container-cube .swiper-slide-prev, .swiper-container-cube .swiper-slide-next + .swiper-slide { pointer-events: auto; visibility: visible; } .swiper-container-cube .swiper-slide-shadow-top, .swiper-container-cube .swiper-slide-shadow-bottom, .swiper-container-cube .swiper-slide-shadow-left, .swiper-container-cube .swiper-slide-shadow-right { z-index: 0; -webkit-backface-visibility: hidden; backface-visibility: hidden; } .swiper-container-cube .swiper-cube-shadow { position: absolute; left: 0; bottom: 0px; width: 100%; height: 100%; opacity: 0.6; z-index: 0; } .swiper-container-cube .swiper-cube-shadow:before { content: ''; background: #000; position: absolute; left: 0; top: 0; bottom: 0; right: 0; filter: blur(50px); } .swiper-container-flip { overflow: visible; } .swiper-container-flip .swiper-slide { pointer-events: none; -webkit-backface-visibility: hidden; backface-visibility: hidden; z-index: 1; } .swiper-container-flip .swiper-slide .swiper-slide { pointer-events: none; } .swiper-container-flip .swiper-slide-active, .swiper-container-flip .swiper-slide-active .swiper-slide-active { pointer-events: auto; } .swiper-container-flip .swiper-slide-shadow-top, .swiper-container-flip .swiper-slide-shadow-bottom, .swiper-container-flip .swiper-slide-shadow-left, .swiper-container-flip .swiper-slide-shadow-right { z-index: 0; -webkit-backface-visibility: hidden; backface-visibility: hidden; } `; export default swiperStyle;
the_stack
import assert from 'assert'; import electron from 'electron'; import fs from 'fs'; import mkdirp from 'mkdirp'; import path from 'path'; import randomstring from 'randomstring'; import rimraf from 'rimraf'; import settings from './settings'; const rootDir = path.join(__dirname, '..'); const tmpDir = path.join(rootDir, 'tmp'); function getUserDataPath() { const app = electron.app || electron.remote.app; const userDataPath = app.getPath('userData'); return userDataPath; } function createTestDir() { const rand = randomstring.generate(7); const dir = path.join(tmpDir, rand); mkdirp.sync(dir); return dir; } describe('Electron Settings', () => { let dir: string; // Create a test dir for each test. beforeEach(() => { dir = createTestDir(); settings.configure({ dir, }); }); // Delete user data files and reset settings config. afterEach(() => { rimraf.sync(`${getUserDataPath()}/*`); settings.reset(); }); // Delete tmp files. after(() => { rimraf.sync(tmpDir); }); it('should exist', () => { assert(settings); }); describe('methods', () => { describe('#configure', () => { it('should update the configuration', () => { assert.equal(settings.file(), path.join(dir, 'settings.json')); const fileName = 'foo.json'; settings.configure({ dir, fileName, }); assert.equal(settings.file(), path.join(dir, fileName)); }); }); describe('#file', () => { context('by default', () => { it('should point to "settings.json" within the app\'s user data directory', () => { settings.reset(); const userDataPath = getUserDataPath(); assert.equal(settings.file(), path.join(userDataPath, 'settings.json')); }); }); context('when a custom directory was defined', () => { it('should point to "settings.json" within the custom directory', () => { assert.equal(settings.file(), path.join(dir, 'settings.json')); }); }); context('when a custom file name was defined', () => { it('should point to the custom file within the app\'s user data directory', () => { const fileName = 'foo.json'; const userDataPath = getUserDataPath(); settings.reset(); settings.configure({ fileName }); assert.equal(settings.file(), path.join(userDataPath, fileName)); }); }); context('when both a custom directory and file name were defined', () => { it('should point to the custom file within the custom directory', () => { const fileName = 'foo.json'; settings.configure({ fileName }); assert.equal(settings.file(), path.join(dir, fileName)); }); }); }); describe('#has', () => { it('should check the value at the key path', async () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); const hasBar = await settings.has('foo[0].bar'); const hasQux = await settings.has('foo[0].qux'); assert.deepStrictEqual(hasBar, true); assert.deepStrictEqual(hasQux, false); }); }); describe('#hasSync', () => { context('when no key path is given', () => { it('should get all settings', () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); const obj = settings.getSync(); assert.deepStrictEqual(obj, seed); }); }); context('when key path is given', () => { it('should get the value at the key path', () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); const value = settings.getSync('foo[0].bar'); assert.deepStrictEqual(value, seed.foo[0].bar); }); }); }); describe('#get', () => { context('when no key path is given', () => { it('should get all settings', async () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); const obj = await settings.get(); assert.deepStrictEqual(obj, seed); }); }); context('when key path is given', () => { it('should get the value at the key path', async () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); const value = await settings.get('foo[0].bar'); assert.deepStrictEqual(value, seed.foo[0].bar); }); }); }); describe('#getSync', () => { context('when no key path is given', () => { it('should get all settings', () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); const obj = settings.getSync(); assert.deepStrictEqual(obj, seed); }); }); context('when key path is given', () => { it('should get the value at the key path', () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); const value = settings.getSync('foo[0].bar'); assert.deepStrictEqual(value, seed.foo[0].bar); }); }); }); describe('#set', () => { context('when no key path is given', () => { it('should set all settings', async () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); await settings.set(seed); const obj = await settings.get(); assert.deepStrictEqual(obj, seed); }); }); context('when key path is given', () => { it('should set the value at the key path', async () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); const beforeValue = await settings.get('foo[0].bar'); assert.deepStrictEqual(beforeValue, seed.foo[0].bar); await settings.set('foo[0].bar', 'qux'); const afterValue = await settings.get('foo[0].bar'); assert.deepStrictEqual(afterValue, 'qux'); }); }); }); describe('#setSync', () => { context('when no key path is given', () => { it('should set all settings', () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); settings.setSync(seed); const obj = settings.getSync(); assert.deepStrictEqual(obj, seed); }); }); context('when key path is given', () => { it('should set the value at the key path', () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); const beforeValue = settings.getSync('foo[0].bar'); assert.deepStrictEqual(beforeValue, seed.foo[0].bar); settings.setSync('foo[0].bar', 'qux'); const afterValue = settings.getSync('foo[0].bar'); assert.deepStrictEqual(afterValue, 'qux'); }); }); }); describe('#unset', () => { context('when no key path is given', () => { it('should unset all settings', async () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); await settings.unset(); const obj = await settings.get(); assert.deepStrictEqual(obj, {}); }); }); context('when key path is given', () => { it('should unset the value at the key path', async () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); const beforeValue = await settings.get('foo[0].bar'); assert.deepStrictEqual(beforeValue, seed.foo[0].bar); await settings.unset('foo[0].bar'); const afterValue = await settings.unset('foo[0].bar'); assert.deepStrictEqual(afterValue, undefined); }); }); }); describe('#unsetSync', () => { context('when no key path is given', () => { it('should unset all settings', () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); settings.unsetSync(); const obj = settings.getSync(); assert.deepStrictEqual(obj, {}); }); }); context('when key path is given', () => { it('should unset the value at the key path', () => { const seed = { foo: [{ bar: 'baz' }] }; fs.writeFileSync(settings.file(), JSON.stringify(seed)); const beforeValue = settings.getSync('foo[0].bar'); assert.deepStrictEqual(beforeValue, seed.foo[0].bar); settings.unsetSync('foo[0].bar'); const afterValue = settings.getSync('foo[0].bar'); assert.deepStrictEqual(afterValue, undefined); }); }); }); }); describe('options', () => { describe('atomicSave', () => { context('when not given', () => { it('should not reject when saving', async () => { await settings.set('foo', 'bar'); }); it('should not throw when saving synchronously', () => { settings.setSync('foo', 'bar'); }); }); context('when false', () => { it('should not reject when saving', async () => { await settings.set('foo', 'bar'); }); it('should not throw when saving synchronously', () => { settings.setSync('foo', 'bar'); }); }); }); describe('dir', () => { context('when not given', () => { it('should save to the user data path', (done) => { const filePath = path.join(getUserDataPath(), 'settings.json'); settings.reset(); assert.deepStrictEqual(filePath, settings.file()); settings.set('foo', 'bar').then(() => { // If this errors, then the file does not exist. fs.stat(filePath, (err) => { assert.ifError(err); done(); }); }); }); }); context('when given', () => { it('should save to the given directory', (done) => { const dir = createTestDir(); const filePath = path.join(dir, 'settings.json'); settings.configure({ dir }); assert.deepStrictEqual(filePath, settings.file()); settings.set('foo', 'bar').then(() => { // If this errors, then the file does not exist. fs.stat(filePath, (err) => { assert.ifError(err); done(); }); }); }); it('should create the given directory if it does not exist', (done) => { const testDir = createTestDir(); const filePath = path.join(testDir, 'settings.json'); settings.configure({ dir: testDir }); settings.set('foo', 'bar').then(() => { // If this errors, then the file does not exist. fs.stat(filePath, (err) => { assert.ifError(err); done(); }); }); }); it('should create the given directory synchronously if it does not exist', () => { const testDir = createTestDir(); const filePath = path.join(testDir, 'settings.json'); settings.configure({ dir: testDir }); settings.setSync('foo', 'bar'); // If this throws, then the file does not exist. fs.statSync(filePath); }); }); }); describe('fileName', () => { context('when not given', () => { it('should save to "settings.json"', (done) => { assert.deepStrictEqual(settings.file(), path.join(dir, 'settings.json')); settings.set('foo', 'bar').then(() => { fs.readFile(path.join(dir, 'settings.json'), 'utf-8', (err, data) => { assert.ifError(err); assert.ok(/^{"foo":"bar"}$/.test(data)); done(); }); }); }); }); context('when "test.json"', () => { it('should save to "test.json"', (done) => { const fileName = 'test.json'; settings.configure({ fileName }); assert.deepStrictEqual(settings.file(), path.join(dir, fileName)); settings.set('foo', 'bar').then(() => { fs.readFile(path.join(dir, fileName), 'utf-8', (err, data) => { assert.ifError(err); assert.ok(/^{"foo":"bar"}$/.test(data)); done(); }); }); }); }); }); describe('prettify', () => { context('when not given', () => { it('should not prettify the output when saving', (done) => { settings.set('foo', 'bar').then(() => { fs.readFile(settings.file(), 'utf-8', (err, data) => { assert.ifError(err); assert.ok(/^{"foo":"bar"}$/.test(data)); done(); }); }); }); }); context('when true', () => { it('should prettify the output when saving', (done) => { settings.configure({ prettify: true }); settings.set('foo', 'bar').then(() => { fs.readFile(settings.file(), 'utf-8', (err, data) => { assert.ifError(err); assert.ok(/^{\n\s+"foo":\s"bar"\n}$/.test(data)); done(); }); }); }); }); }); describe('numSpaces', () => { context('when not given', () => { it('should prettify the output with two spaces when saving', (done) => { settings.configure({ prettify: true, numSpaces: 2 }); settings.set('foo', 'bar').then(() => { fs.readFile(settings.file(), 'utf-8', (err, data) => { assert.ifError(err); assert.ok(/^{\n(\s){2}"foo": "bar"\n}$/.test(data)); done(); }); }); }); }); context('when 4', () => { it('should prettify the output with four spaces when saving', (done) => { settings.configure({ prettify: true, numSpaces: 4 }); settings.set('foo', 'bar').then(() => { fs.readFile(settings.file(), 'utf-8', (err, data) => { assert.ifError(err); assert.ok(/^{\n(\s){4}"foo": "bar"\n}$/.test(data)); done(); }); }); }); }); }); }); });
the_stack
import { openAlert, AlertButton, AlertConfig, closeAlerts } from './ui/alert/Alert' import { closeToast, openToast, ToastAction } from './ui/toast/Toast' import { ExtendedP2PPairingResponse } from './types/P2PPairingResponse' import { PostMessagePairingRequest } from './types/PostMessagePairingRequest' import { ExtendedPostMessagePairingResponse } from './types/PostMessagePairingResponse' import { BlockExplorer } from './utils/block-explorer' import { Logger } from './utils/Logger' import { shortenString } from './utils/shorten-string' import { BeaconErrorType } from './types/BeaconErrorType' import { P2PPairingRequest, AccountInfo, ErrorResponse, UnknownBeaconError, PermissionResponseOutput, OperationResponseOutput, BroadcastResponseOutput, SignPayloadResponseOutput, Network, BeaconError, ConnectionContext, Transport, NetworkType, AcknowledgeResponse // EncryptPayloadResponseOutput, // EncryptionOperation } from '.' import { isMobile } from './utils/platform' const logger = new Logger('BeaconEvents') const SUCCESS_TIMER: number = 5 * 1000 const SVG_EXTERNAL: string = `<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="external-link-alt" class="svg-inline--fa fa-external-link-alt fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M432,320H400a16,16,0,0,0-16,16V448H64V128H208a16,16,0,0,0,16-16V80a16,16,0,0,0-16-16H48A48,48,0,0,0,0,112V464a48,48,0,0,0,48,48H400a48,48,0,0,0,48-48V336A16,16,0,0,0,432,320ZM488,0h-128c-21.37,0-32.05,25.91-17,41l35.73,35.73L135,320.37a24,24,0,0,0,0,34L157.67,377a24,24,0,0,0,34,0L435.28,133.32,471,169c15,15,41,4.5,41-17V24A24,24,0,0,0,488,0Z"></path></svg>` /** * The different events that can be emitted by the beacon-sdk */ export enum BeaconEvent { PERMISSION_REQUEST_SENT = 'PERMISSION_REQUEST_SENT', PERMISSION_REQUEST_SUCCESS = 'PERMISSION_REQUEST_SUCCESS', PERMISSION_REQUEST_ERROR = 'PERMISSION_REQUEST_ERROR', OPERATION_REQUEST_SENT = 'OPERATION_REQUEST_SENT', OPERATION_REQUEST_SUCCESS = 'OPERATION_REQUEST_SUCCESS', OPERATION_REQUEST_ERROR = 'OPERATION_REQUEST_ERROR', SIGN_REQUEST_SENT = 'SIGN_REQUEST_SENT', SIGN_REQUEST_SUCCESS = 'SIGN_REQUEST_SUCCESS', SIGN_REQUEST_ERROR = 'SIGN_REQUEST_ERROR', // TODO: ENCRYPTION // ENCRYPT_REQUEST_SENT = 'ENCRYPT_REQUEST_SENT', // ENCRYPT_REQUEST_SUCCESS = 'ENCRYPT_REQUEST_SUCCESS', // ENCRYPT_REQUEST_ERROR = 'ENCRYPT_REQUEST_ERROR', BROADCAST_REQUEST_SENT = 'BROADCAST_REQUEST_SENT', BROADCAST_REQUEST_SUCCESS = 'BROADCAST_REQUEST_SUCCESS', BROADCAST_REQUEST_ERROR = 'BROADCAST_REQUEST_ERROR', ACKNOWLEDGE_RECEIVED = 'ACKNOWLEDGE_RECEIVED', LOCAL_RATE_LIMIT_REACHED = 'LOCAL_RATE_LIMIT_REACHED', NO_PERMISSIONS = 'NO_PERMISSIONS', ACTIVE_ACCOUNT_SET = 'ACTIVE_ACCOUNT_SET', ACTIVE_TRANSPORT_SET = 'ACTIVE_TRANSPORT_SET', SHOW_PREPARE = 'SHOW_PREPARE', HIDE_UI = 'HIDE_UI', PAIR_INIT = 'PAIR_INIT', PAIR_SUCCESS = 'PAIR_SUCCESS', CHANNEL_CLOSED = 'CHANNEL_CLOSED', INTERNAL_ERROR = 'INTERNAL_ERROR', UNKNOWN = 'UNKNOWN' } export interface WalletInfo { name: string type?: 'extension' | 'mobile' | 'web' | 'desktop' icon?: string deeplink?: string } export interface ExtraInfo { resetCallback?(): Promise<void> } interface RequestSentInfo { extraInfo: ExtraInfo walletInfo: WalletInfo } /** * The type of the payload of the different BeaconEvents */ export interface BeaconEventType { [BeaconEvent.PERMISSION_REQUEST_SENT]: RequestSentInfo [BeaconEvent.PERMISSION_REQUEST_SUCCESS]: { account: AccountInfo output: PermissionResponseOutput blockExplorer: BlockExplorer connectionContext: ConnectionContext walletInfo: WalletInfo } [BeaconEvent.PERMISSION_REQUEST_ERROR]: { errorResponse: ErrorResponse; walletInfo: WalletInfo } [BeaconEvent.OPERATION_REQUEST_SENT]: RequestSentInfo [BeaconEvent.OPERATION_REQUEST_SUCCESS]: { account: AccountInfo output: OperationResponseOutput blockExplorer: BlockExplorer connectionContext: ConnectionContext walletInfo: WalletInfo } [BeaconEvent.OPERATION_REQUEST_ERROR]: { errorResponse: ErrorResponse; walletInfo: WalletInfo } [BeaconEvent.SIGN_REQUEST_SENT]: RequestSentInfo [BeaconEvent.SIGN_REQUEST_SUCCESS]: { output: SignPayloadResponseOutput connectionContext: ConnectionContext walletInfo: WalletInfo } [BeaconEvent.SIGN_REQUEST_ERROR]: { errorResponse: ErrorResponse; walletInfo: WalletInfo } // TODO: ENCRYPTION // [BeaconEvent.ENCRYPT_REQUEST_SENT]: RequestSentInfo // [BeaconEvent.ENCRYPT_REQUEST_SUCCESS]: { // output: EncryptPayloadResponseOutput // connectionContext: ConnectionContext // walletInfo: WalletInfo // } // [BeaconEvent.ENCRYPT_REQUEST_ERROR]: { errorResponse: ErrorResponse; walletInfo: WalletInfo } [BeaconEvent.BROADCAST_REQUEST_SENT]: RequestSentInfo [BeaconEvent.BROADCAST_REQUEST_SUCCESS]: { network: Network output: BroadcastResponseOutput blockExplorer: BlockExplorer connectionContext: ConnectionContext walletInfo: WalletInfo } [BeaconEvent.BROADCAST_REQUEST_ERROR]: { errorResponse: ErrorResponse; walletInfo: WalletInfo } [BeaconEvent.ACKNOWLEDGE_RECEIVED]: { message: AcknowledgeResponse extraInfo: ExtraInfo walletInfo: WalletInfo } [BeaconEvent.LOCAL_RATE_LIMIT_REACHED]: undefined [BeaconEvent.NO_PERMISSIONS]: undefined [BeaconEvent.ACTIVE_ACCOUNT_SET]: AccountInfo [BeaconEvent.ACTIVE_TRANSPORT_SET]: Transport [BeaconEvent.SHOW_PREPARE]: { walletInfo?: WalletInfo } [BeaconEvent.HIDE_UI]: ('alert' | 'toast')[] | undefined [BeaconEvent.PAIR_INIT]: { p2pPeerInfo: () => Promise<P2PPairingRequest> postmessagePeerInfo: () => Promise<PostMessagePairingRequest> preferredNetwork: NetworkType abortedHandler?(): void disclaimerText?: string } [BeaconEvent.PAIR_SUCCESS]: ExtendedPostMessagePairingResponse | ExtendedP2PPairingResponse [BeaconEvent.CHANNEL_CLOSED]: string [BeaconEvent.INTERNAL_ERROR]: { text: string; buttons?: AlertButton[] } [BeaconEvent.UNKNOWN]: undefined } /** * Show a "Request sent" toast */ const showSentToast = async (data: RequestSentInfo): Promise<void> => { let openWalletAction const actions: ToastAction[] = [] if (data.walletInfo.deeplink) { if ( data.walletInfo.type === 'web' || (data.walletInfo.type === 'mobile' && isMobile(window)) || (data.walletInfo.type === 'desktop' && !isMobile(window)) ) { const link = data.walletInfo.deeplink openWalletAction = async (): Promise<void> => { const a = document.createElement('a') a.setAttribute('href', link) a.setAttribute('target', '_blank') a.dispatchEvent(new MouseEvent('click', { view: window, bubbles: true, cancelable: true })) } } } actions.push({ text: `<strong>No answer from your wallet received yet. Please make sure the wallet is open.</strong>` }) actions.push({ text: 'Did you make a mistake?', actionText: 'Cancel Request', actionCallback: async (): Promise<void> => { await closeToast() } }) actions.push({ text: 'Wallet not receiving request?', actionText: 'Reset Connection', actionCallback: async (): Promise<void> => { await closeToast() // eslint-disable-next-line @typescript-eslint/unbound-method const resetCallback = data.extraInfo.resetCallback if (resetCallback) { logger.log('showSentToast', 'resetCallback invoked') await resetCallback() } } }) openToast({ body: `<span class="beacon-toast__wallet__outer">Request sent to&nbsp;{{wallet}}<span>`, walletInfo: data.walletInfo, state: 'loading', actions, openWalletAction }).catch((toastError) => console.error(toastError)) } const showAcknowledgedToast = async (data: { message: AcknowledgeResponse extraInfo: ExtraInfo walletInfo: WalletInfo }): Promise<void> => { openToast({ body: '<span class="beacon-toast__wallet__outer">Awaiting confirmation in&nbsp;{{wallet}}<span>', state: 'acknowledge', walletInfo: data.walletInfo }).catch((toastError) => console.error(toastError)) } const showPrepare = async (data: { walletInfo?: WalletInfo }): Promise<void> => { const text = data.walletInfo ? `Preparing Request for&nbsp;{{wallet}}...` : 'Preparing Request...' openToast({ body: `<span class="beacon-toast__wallet__outer">${text}<span>`, state: 'prepare', walletInfo: data.walletInfo }).catch((toastError) => console.error(toastError)) } const hideUI = async (elements?: ('alert' | 'toast')[]): Promise<void> => { if (elements) { if (elements.includes('alert')) { closeAlerts() } if (elements.includes('toast')) { closeToast() } } else { closeToast() } } /** * Show a "No Permission" alert */ const showNoPermissionAlert = async (): Promise<void> => { await openAlert({ title: 'No Permission', body: 'Please allow the wallet to handle this type of request.' }) } /** * Show an error toast * * @param beaconError The beacon error */ const showErrorToast = async ( response: { errorResponse: ErrorResponse; walletInfo: WalletInfo }, buttons?: AlertButton[] ): Promise<void> => { const error = response.errorResponse.errorType ? BeaconError.getError(response.errorResponse.errorType, response.errorResponse.errorData) : new UnknownBeaconError() const actions: ToastAction[] = [ { text: `<strong>${error.title}</strong>` }, { text: error.description } ] if ( response.errorResponse.errorType === BeaconErrorType.TRANSACTION_INVALID_ERROR && response.errorResponse.errorData ) { actions.push({ text: '', actionText: 'Show Details', actionCallback: async (): Promise<void> => { await closeToast() await openAlert({ title: error.title, // eslint-disable-next-line @typescript-eslint/unbound-method body: error.fullDescription, buttons }) } }) } await openToast({ body: `{{wallet}}&nbsp;has returned an error`, timer: response.errorResponse.errorType === BeaconErrorType.ABORTED_ERROR ? SUCCESS_TIMER : undefined, state: 'finished', walletInfo: response.walletInfo, actions }) } /** * Show a rate limit reached toast */ const showRateLimitReached = async (): Promise<void> => { openAlert({ title: 'Error', body: 'Rate limit reached. Please slow down', buttons: [{ text: 'Done', style: 'outline' }], timer: 3000 }).catch((toastError) => console.error(toastError)) } /** * Show a "connection successful" alert for 1.5 seconds */ const showExtensionConnectedAlert = async (): Promise<void> => { await closeAlerts() } /** * Show a "channel closed" alert for 1.5 seconds */ const showChannelClosedAlert = async (): Promise<void> => { await openAlert({ title: 'Channel closed', body: `Your peer has closed the connection.`, buttons: [{ text: 'Done', style: 'outline' }], timer: 1500 }) } const showInternalErrorAlert = async ( data: BeaconEventType[BeaconEvent.INTERNAL_ERROR] ): Promise<void> => { const buttons: AlertButton[] = [...(data.buttons ?? [])] buttons.push({ text: 'Done', style: 'outline' }) const alertConfig: AlertConfig = { title: 'Internal Error', body: data.text, buttons } await openAlert(alertConfig) } /** * Show a connect alert with QR code * * @param data The data that is emitted by the PAIR_INIT event */ const showPairAlert = async (data: BeaconEventType[BeaconEvent.PAIR_INIT]): Promise<void> => { const alertConfig: AlertConfig = { title: 'Choose your preferred wallet', body: `<p></p>`, pairingPayload: { p2pSyncCode: data.p2pPeerInfo, postmessageSyncCode: data.postmessagePeerInfo, preferredNetwork: data.preferredNetwork }, // eslint-disable-next-line @typescript-eslint/unbound-method closeButtonCallback: data.abortedHandler, disclaimerText: data.disclaimerText } await openAlert(alertConfig) } /** * Show a "Permission Granted" alert * * @param data The data that is emitted by the PERMISSION_REQUEST_SUCCESS event */ const showPermissionSuccessAlert = async ( data: BeaconEventType[BeaconEvent.PERMISSION_REQUEST_SUCCESS] ): Promise<void> => { const { output } = data await openToast({ body: `{{wallet}}&nbsp;has granted permission`, timer: SUCCESS_TIMER, walletInfo: data.walletInfo, state: 'finished', actions: [ { text: 'Address', actionText: `<strong>${shortenString(output.address)}</strong>` }, { text: 'Network', actionText: `${output.network.type}` }, { text: 'Permissions', actionText: output.scopes.join(', ') } ] }) } /** * Show an "Operation Broadcasted" alert * * @param data The data that is emitted by the OPERATION_REQUEST_SUCCESS event */ const showOperationSuccessAlert = async ( data: BeaconEventType[BeaconEvent.OPERATION_REQUEST_SUCCESS] ): Promise<void> => { const { account, output, blockExplorer } = data await openToast({ body: `{{wallet}}&nbsp;successfully submitted operation`, timer: SUCCESS_TIMER, state: 'finished', walletInfo: data.walletInfo, actions: [ { text: `<strong>${shortenString(output.transactionHash)}</strong>`, actionText: `Open Blockexplorer ${SVG_EXTERNAL}`, actionCallback: async (): Promise<void> => { const link: string = await blockExplorer.getTransactionLink( output.transactionHash, account.network ) window.open(link, '_blank') await closeToast() } } ] }) } /** * Show a "Transaction Signed" alert * * @param data The data that is emitted by the SIGN_REQUEST_SUCCESS event */ const showSignSuccessAlert = async ( data: BeaconEventType[BeaconEvent.SIGN_REQUEST_SUCCESS] ): Promise<void> => { const output = data.output await openToast({ body: `{{wallet}}&nbsp;successfully signed payload`, timer: SUCCESS_TIMER, state: 'finished', walletInfo: data.walletInfo, actions: [ { text: `Signature: <strong>${shortenString(output.signature)}</strong>`, actionText: 'Copy to clipboard', actionCallback: async (): Promise<void> => { navigator.clipboard.writeText(output.signature).then( () => { logger.log('showSignSuccessAlert', 'Copying to clipboard was successful!') }, (err) => { logger.error('showSignSuccessAlert', 'Could not copy text to clipboard: ', err) } ) await closeToast() } } ] }) } /** * Show a "Transaction Signed" alert * * @param data The data that is emitted by the ENCRYPT_REQUEST_SUCCESS event */ // TODO: ENCRYPTION // const showEncryptSuccessAlert = async ( // data: BeaconEventType[BeaconEvent.ENCRYPT_REQUEST_SUCCESS] // ): Promise<void> => { // const output = data.output // await openToast({ // body: `{{wallet}}&nbsp;successfully ${ // data.output.cryptoOperation === EncryptionOperation.ENCRYPT ? 'encrypted' : 'decrypted' // } payload`, // timer: SUCCESS_TIMER, // state: 'finished', // walletInfo: data.walletInfo, // actions: [ // { // text: `Payload: <strong>${shortenString(output.payload)}</strong>`, // actionText: 'Copy to clipboard', // actionCallback: async (): Promise<void> => { // navigator.clipboard.writeText(output.payload).then( // () => { // logger.log('showSignSuccessAlert', 'Copying to clipboard was successful!') // }, // (err) => { // logger.error('showSignSuccessAlert', 'Could not copy text to clipboard: ', err) // } // ) // await closeToast() // } // } // ] // }) // } /** * Show a "Broadcasted" alert * * @param data The data that is emitted by the BROADCAST_REQUEST_SUCCESS event */ const showBroadcastSuccessAlert = async ( data: BeaconEventType[BeaconEvent.BROADCAST_REQUEST_SUCCESS] ): Promise<void> => { const { network, output, blockExplorer } = data await openToast({ body: `{{wallet}}&nbsp;successfully injected operation`, timer: SUCCESS_TIMER, state: 'finished', walletInfo: data.walletInfo, actions: [ { text: `<strong>${shortenString(output.transactionHash)}</strong>`, actionText: `Open Blockexplorer ${SVG_EXTERNAL}`, actionCallback: async (): Promise<void> => { const link: string = await blockExplorer.getTransactionLink( output.transactionHash, network ) window.open(link, '_blank') await closeToast() } } ] }) } const emptyHandler = (): BeaconEventHandlerFunction => async (): Promise<void> => { // } export type BeaconEventHandlerFunction<T = unknown> = ( data: T, eventCallback?: AlertButton[] ) => void | Promise<void> /** * The default event handlers */ export const defaultEventCallbacks: { [key in BeaconEvent]: BeaconEventHandlerFunction<BeaconEventType[key]> } = { [BeaconEvent.PERMISSION_REQUEST_SENT]: showSentToast, [BeaconEvent.PERMISSION_REQUEST_SUCCESS]: showPermissionSuccessAlert, [BeaconEvent.PERMISSION_REQUEST_ERROR]: showErrorToast, [BeaconEvent.OPERATION_REQUEST_SENT]: showSentToast, [BeaconEvent.OPERATION_REQUEST_SUCCESS]: showOperationSuccessAlert, [BeaconEvent.OPERATION_REQUEST_ERROR]: showErrorToast, [BeaconEvent.SIGN_REQUEST_SENT]: showSentToast, [BeaconEvent.SIGN_REQUEST_SUCCESS]: showSignSuccessAlert, [BeaconEvent.SIGN_REQUEST_ERROR]: showErrorToast, // TODO: ENCRYPTION // [BeaconEvent.ENCRYPT_REQUEST_SENT]: showSentToast, // [BeaconEvent.ENCRYPT_REQUEST_SUCCESS]: showEncryptSuccessAlert, // [BeaconEvent.ENCRYPT_REQUEST_ERROR]: showErrorToast, [BeaconEvent.BROADCAST_REQUEST_SENT]: showSentToast, [BeaconEvent.BROADCAST_REQUEST_SUCCESS]: showBroadcastSuccessAlert, [BeaconEvent.BROADCAST_REQUEST_ERROR]: showErrorToast, [BeaconEvent.ACKNOWLEDGE_RECEIVED]: showAcknowledgedToast, [BeaconEvent.LOCAL_RATE_LIMIT_REACHED]: showRateLimitReached, [BeaconEvent.NO_PERMISSIONS]: showNoPermissionAlert, [BeaconEvent.ACTIVE_ACCOUNT_SET]: emptyHandler(), [BeaconEvent.ACTIVE_TRANSPORT_SET]: emptyHandler(), [BeaconEvent.SHOW_PREPARE]: showPrepare, [BeaconEvent.HIDE_UI]: hideUI, [BeaconEvent.PAIR_INIT]: showPairAlert, [BeaconEvent.PAIR_SUCCESS]: showExtensionConnectedAlert, [BeaconEvent.CHANNEL_CLOSED]: showChannelClosedAlert, [BeaconEvent.INTERNAL_ERROR]: showInternalErrorAlert, [BeaconEvent.UNKNOWN]: emptyHandler() } /** * @internalapi * * Handles beacon events */ export class BeaconEventHandler { private readonly callbackMap: { [key in BeaconEvent]: BeaconEventHandlerFunction<any>[] // TODO: Fix type } = { [BeaconEvent.PERMISSION_REQUEST_SENT]: [defaultEventCallbacks.PERMISSION_REQUEST_SENT], [BeaconEvent.PERMISSION_REQUEST_SUCCESS]: [defaultEventCallbacks.PERMISSION_REQUEST_SUCCESS], [BeaconEvent.PERMISSION_REQUEST_ERROR]: [defaultEventCallbacks.PERMISSION_REQUEST_ERROR], [BeaconEvent.OPERATION_REQUEST_SENT]: [defaultEventCallbacks.OPERATION_REQUEST_SENT], [BeaconEvent.OPERATION_REQUEST_SUCCESS]: [defaultEventCallbacks.OPERATION_REQUEST_SUCCESS], [BeaconEvent.OPERATION_REQUEST_ERROR]: [defaultEventCallbacks.OPERATION_REQUEST_ERROR], [BeaconEvent.SIGN_REQUEST_SENT]: [defaultEventCallbacks.SIGN_REQUEST_SENT], [BeaconEvent.SIGN_REQUEST_SUCCESS]: [defaultEventCallbacks.SIGN_REQUEST_SUCCESS], [BeaconEvent.SIGN_REQUEST_ERROR]: [defaultEventCallbacks.SIGN_REQUEST_ERROR], // TODO: ENCRYPTION // [BeaconEvent.ENCRYPT_REQUEST_SENT]: [defaultEventCallbacks.ENCRYPT_REQUEST_SENT], // [BeaconEvent.ENCRYPT_REQUEST_SUCCESS]: [defaultEventCallbacks.ENCRYPT_REQUEST_SUCCESS], // [BeaconEvent.ENCRYPT_REQUEST_ERROR]: [defaultEventCallbacks.ENCRYPT_REQUEST_ERROR], [BeaconEvent.BROADCAST_REQUEST_SENT]: [defaultEventCallbacks.BROADCAST_REQUEST_SENT], [BeaconEvent.BROADCAST_REQUEST_SUCCESS]: [defaultEventCallbacks.BROADCAST_REQUEST_SUCCESS], [BeaconEvent.BROADCAST_REQUEST_ERROR]: [defaultEventCallbacks.BROADCAST_REQUEST_ERROR], [BeaconEvent.ACKNOWLEDGE_RECEIVED]: [defaultEventCallbacks.ACKNOWLEDGE_RECEIVED], [BeaconEvent.LOCAL_RATE_LIMIT_REACHED]: [defaultEventCallbacks.LOCAL_RATE_LIMIT_REACHED], [BeaconEvent.NO_PERMISSIONS]: [defaultEventCallbacks.NO_PERMISSIONS], [BeaconEvent.ACTIVE_ACCOUNT_SET]: [defaultEventCallbacks.ACTIVE_ACCOUNT_SET], [BeaconEvent.ACTIVE_TRANSPORT_SET]: [defaultEventCallbacks.ACTIVE_TRANSPORT_SET], [BeaconEvent.SHOW_PREPARE]: [defaultEventCallbacks.SHOW_PREPARE], [BeaconEvent.HIDE_UI]: [defaultEventCallbacks.HIDE_UI], [BeaconEvent.PAIR_INIT]: [defaultEventCallbacks.PAIR_INIT], [BeaconEvent.PAIR_SUCCESS]: [defaultEventCallbacks.PAIR_SUCCESS], [BeaconEvent.CHANNEL_CLOSED]: [defaultEventCallbacks.CHANNEL_CLOSED], [BeaconEvent.INTERNAL_ERROR]: [defaultEventCallbacks.INTERNAL_ERROR], [BeaconEvent.UNKNOWN]: [defaultEventCallbacks.UNKNOWN] } constructor( eventsToOverride: { [key in BeaconEvent]?: { handler: BeaconEventHandlerFunction<BeaconEventType[key]> } } = {}, overrideAll?: boolean ) { if (overrideAll) { this.setAllHandlers() } this.overrideDefaults(eventsToOverride) } /** * A method to subscribe to a specific beacon event and register a callback * * @param event The event being emitted * @param eventCallback The callback that will be invoked */ public async on<K extends BeaconEvent>( event: K, eventCallback: BeaconEventHandlerFunction<BeaconEventType[K]> ): Promise<void> { const listeners = this.callbackMap[event] || [] listeners.push(eventCallback) this.callbackMap[event] = listeners } /** * Emit a beacon event * * @param event The event being emitted * @param data The data to be emit */ public async emit<K extends BeaconEvent>( event: K, data?: BeaconEventType[K], eventCallback?: AlertButton[] ): Promise<void> { const listeners = this.callbackMap[event] if (listeners && listeners.length > 0) { listeners.forEach(async (listener: BeaconEventHandlerFunction) => { try { await listener(data, eventCallback) } catch (listenerError) { logger.error(`error handling event ${event}`, listenerError) } }) } } /** * Override beacon event default callbacks. This can be used to disable default alert/toast behaviour * * @param eventsToOverride An object with the events to override */ private overrideDefaults( eventsToOverride: { [key in BeaconEvent]?: { handler: BeaconEventHandlerFunction<BeaconEventType[key]> } } ): void { Object.keys(eventsToOverride).forEach((untypedEvent: string) => { const eventType: BeaconEvent = untypedEvent as BeaconEvent const event = eventsToOverride[eventType] if (event) { this.callbackMap[eventType] = [event.handler] } }) } /** * Set all event callbacks to a specific handler. */ private setAllHandlers(handler?: BeaconEventHandlerFunction): void { Object.keys(this.callbackMap).forEach((untypedEvent: string) => { const eventType: BeaconEvent = untypedEvent as BeaconEvent this.callbackMap[eventType] = [] if (handler) { this.callbackMap[eventType].push(handler) } else { this.callbackMap[eventType].push((...data) => { logger.log(untypedEvent, ...data) }) } }) } }
the_stack
export const description = ` Util math unit tests. `; import { makeTestGroup } from '../common/framework/test_group.js'; import { kBit } from '../webgpu/shader/execution/builtin/builtin.js'; import { f32, f32Bits, Scalar } from '../webgpu/util/conversion.js'; import { correctlyRounded, diffULP, nextAfter } from '../webgpu/util/math.js'; import { UnitTest } from './unit_test.js'; export const g = makeTestGroup(UnitTest); interface DiffULPCase { a: number; b: number; ulp: number; } /** Converts a 32-bit hex values to a 32-bit float value */ function hexToF32(hex: number): number { return new Float32Array(new Uint32Array([hex]).buffer)[0]; } /** Converts two 32-bit hex values to a 64-bit float value */ function hexToFloat64(h32: number, l32: number): number { const u32Arr = new Uint32Array(2); u32Arr[0] = l32; u32Arr[1] = h32; const f64Arr = new Float64Array(u32Arr.buffer); return f64Arr[0]; } g.test('test,math,diffULP') .paramsSimple<DiffULPCase>([ { a: 0, b: 0, ulp: 0 }, { a: 1, b: 2, ulp: 2 ** 23 }, // Single exponent step { a: 2, b: 1, ulp: 2 ** 23 }, // Single exponent step { a: 2, b: 4, ulp: 2 ** 23 }, // Single exponent step { a: 4, b: 2, ulp: 2 ** 23 }, // Single exponent step { a: -1, b: -2, ulp: 2 ** 23 }, // Single exponent step { a: -2, b: -1, ulp: 2 ** 23 }, // Single exponent step { a: -2, b: -4, ulp: 2 ** 23 }, // Single exponent step { a: -4, b: -2, ulp: 2 ** 23 }, // Single exponent step { a: 1, b: 4, ulp: 2 ** 24 }, // Double exponent step { a: 4, b: 1, ulp: 2 ** 24 }, // Double exponent step { a: -1, b: -4, ulp: 2 ** 24 }, // Double exponent step { a: -4, b: -1, ulp: 2 ** 24 }, // Double exponent step { a: hexToF32(0x00800000), b: hexToF32(0x00800001), ulp: 1 }, // Single mantissa step { a: hexToF32(0x00800001), b: hexToF32(0x00800000), ulp: 1 }, // Single mantissa step { a: hexToF32(0x03800000), b: hexToF32(0x03800001), ulp: 1 }, // Single mantissa step { a: hexToF32(0x03800001), b: hexToF32(0x03800000), ulp: 1 }, // Single mantissa step { a: -hexToF32(0x00800000), b: -hexToF32(0x00800001), ulp: 1 }, // Single mantissa step { a: -hexToF32(0x00800001), b: -hexToF32(0x00800000), ulp: 1 }, // Single mantissa step { a: -hexToF32(0x03800000), b: -hexToF32(0x03800001), ulp: 1 }, // Single mantissa step { a: -hexToF32(0x03800001), b: -hexToF32(0x03800000), ulp: 1 }, // Single mantissa step { a: hexToF32(0x00800000), b: hexToF32(0x00800002), ulp: 2 }, // Double mantissa step { a: hexToF32(0x00800002), b: hexToF32(0x00800000), ulp: 2 }, // Double mantissa step { a: hexToF32(0x03800000), b: hexToF32(0x03800002), ulp: 2 }, // Double mantissa step { a: hexToF32(0x03800002), b: hexToF32(0x03800000), ulp: 2 }, // Double mantissa step { a: -hexToF32(0x00800000), b: -hexToF32(0x00800002), ulp: 2 }, // Double mantissa step { a: -hexToF32(0x00800002), b: -hexToF32(0x00800000), ulp: 2 }, // Double mantissa step { a: -hexToF32(0x03800000), b: -hexToF32(0x03800002), ulp: 2 }, // Double mantissa step { a: -hexToF32(0x03800002), b: -hexToF32(0x03800000), ulp: 2 }, // Double mantissa step { a: hexToF32(0x00800000), b: 0, ulp: 1 }, // Normals near 0 { a: 0, b: hexToF32(0x00800000), ulp: 1 }, // Normals near 0 { a: -hexToF32(0x00800000), b: 0, ulp: 1 }, // Normals near 0 { a: 0, b: -hexToF32(0x00800000), ulp: 1 }, // Normals near 0 { a: hexToF32(0x00800000), b: -hexToF32(0x00800000), ulp: 2 }, // Normals around 0 { a: -hexToF32(0x00800000), b: hexToF32(0x00800000), ulp: 2 }, // Normals around 0 { a: hexToF32(0x00000001), b: 0, ulp: 0 }, // Subnormals near 0 { a: 0, b: hexToF32(0x00000001), ulp: 0 }, // Subnormals near 0 { a: -hexToF32(0x00000001), b: 0, ulp: 0 }, // Subnormals near 0 { a: 0, b: -hexToF32(0x00000001), ulp: 0 }, // Subnormals near 0 { a: hexToF32(0x00000001), b: -hexToF32(0x00000001), ulp: 0 }, // Subnormals near 0 { a: -hexToF32(0x00000001), b: hexToF32(0x00000001), ulp: 0 }, // Subnormals near 0 { a: hexToF32(0x00000001), b: hexToF32(0x00800000), ulp: 1 }, // Normal/Subnormal boundary { a: hexToF32(0x00800000), b: hexToF32(0x00000001), ulp: 1 }, // Normal/Subnormal boundary { a: -hexToF32(0x00000001), b: -hexToF32(0x00800000), ulp: 1 }, // Normal/Subnormal boundary { a: -hexToF32(0x00800000), b: -hexToF32(0x00000001), ulp: 1 }, // Normal/Subnormal boundary { a: hexToF32(0x00800001), b: hexToF32(0x00000000), ulp: 2 }, // Just-above-Normal/Subnormal boundary { a: hexToF32(0x00800001), b: hexToF32(0x00000001), ulp: 2 }, // Just-above-Normal/Subnormal boundary { a: hexToF32(0x00800005), b: hexToF32(0x00000001), ulp: 6 }, // Just-above-Normal/Subnormal boundary { a: hexToF32(0x00800005), b: hexToF32(0x00000111), ulp: 6 }, // Just-above-Normal/Subnormal boundary ]) .fn(t => { const a = t.params.a; const b = t.params.b; const got = diffULP(a, b); const expect = t.params.ulp; t.expect(got === expect, `diffULP(${a}, ${b}) returned ${got}. Expected ${expect}`); }); interface nextAfterCase { val: number; dir: boolean; result: Scalar; } g.test('test,math,nextAfter') .paramsSimple<nextAfterCase>([ // Edge Cases { val: Number.NaN, dir: true, result: f32Bits(0x7fffffff) }, { val: Number.NaN, dir: false, result: f32Bits(0x7fffffff) }, { val: Number.POSITIVE_INFINITY, dir: true, result: f32Bits(kBit.f32.infinity.positive) }, { val: Number.POSITIVE_INFINITY, dir: false, result: f32Bits(kBit.f32.infinity.positive) }, { val: Number.NEGATIVE_INFINITY, dir: true, result: f32Bits(kBit.f32.infinity.negative) }, { val: Number.NEGATIVE_INFINITY, dir: false, result: f32Bits(kBit.f32.infinity.negative) }, // Zeroes { val: +0, dir: true, result: f32Bits(kBit.f32.subnormal.positive.min) }, { val: +0, dir: false, result: f32Bits(kBit.f32.subnormal.negative.max) }, { val: -0, dir: true, result: f32Bits(kBit.f32.subnormal.positive.min) }, { val: -0, dir: false, result: f32Bits(kBit.f32.subnormal.negative.max) }, // Subnormals { val: hexToF32(kBit.f32.subnormal.positive.min), dir: true, result: f32Bits(0x00000002) }, { val: hexToF32(kBit.f32.subnormal.positive.min), dir: false, result: f32(0) }, // prettier-ignore { val: hexToF32(kBit.f32.subnormal.positive.max), dir: true, result: f32Bits(kBit.f32.positive.min) }, { val: hexToF32(kBit.f32.subnormal.positive.max), dir: false, result: f32Bits(0x007ffffe) }, { val: hexToF32(kBit.f32.subnormal.negative.min), dir: true, result: f32Bits(0x807ffffe) }, // prettier-ignore { val: hexToF32(kBit.f32.subnormal.negative.min), dir: false, result: f32Bits(kBit.f32.negative.max) }, { val: hexToF32(kBit.f32.subnormal.negative.max), dir: true, result: f32(0) }, { val: hexToF32(kBit.f32.subnormal.negative.max), dir: false, result: f32Bits(0x80000002) }, // Normals // prettier-ignore { val: hexToF32(kBit.f32.positive.max), dir: true, result: f32Bits(kBit.f32.infinity.positive) }, { val: hexToF32(kBit.f32.positive.max), dir: false, result: f32Bits(0x7f7ffffe) }, { val: hexToF32(kBit.f32.positive.min), dir: true, result: f32Bits(0x00800001) }, // prettier-ignore { val: hexToF32(kBit.f32.positive.min), dir: false, result: f32Bits(kBit.f32.subnormal.positive.max) }, // prettier-ignore { val: hexToF32(kBit.f32.negative.max), dir: true, result: f32Bits(kBit.f32.subnormal.negative.min) }, { val: hexToF32(kBit.f32.negative.max), dir: false, result: f32Bits(0x80800001) }, { val: hexToF32(kBit.f32.negative.min), dir: true, result: f32Bits(0xff7ffffe) }, // prettier-ignore { val: hexToF32(kBit.f32.negative.min), dir: false, result: f32Bits(kBit.f32.infinity.negative) }, { val: hexToF32(0x03800000), dir: true, result: f32Bits(0x03800001) }, { val: hexToF32(0x03800000), dir: false, result: f32Bits(0x037fffff) }, { val: hexToF32(0x83800000), dir: true, result: f32Bits(0x837fffff) }, { val: hexToF32(0x83800000), dir: false, result: f32Bits(0x83800001) }, ]) .fn(t => { const val = t.params.val; const dir = t.params.dir; const expect = t.params.result; const expect_type = typeof expect; const got = nextAfter(val, dir); const got_type = typeof got; t.expect( got.value === expect.value || (Number.isNaN(got.value) && Number.isNaN(expect.value)), `nextAfter(${val}, ${dir}) returned ${got} (${got_type}). Expected ${expect} (${expect_type})` ); }); interface correctlyRoundedCase { test_val: Scalar; target: number; is_correct: boolean; } g.test('test,math,correctlyRounded') .paramsSimple<correctlyRoundedCase>([ // NaN Cases { test_val: f32Bits(kBit.f32.nan.positive.s), target: NaN, is_correct: true }, { test_val: f32Bits(kBit.f32.nan.positive.q), target: NaN, is_correct: true }, { test_val: f32Bits(kBit.f32.nan.negative.s), target: NaN, is_correct: true }, { test_val: f32Bits(kBit.f32.nan.negative.q), target: NaN, is_correct: true }, { test_val: f32Bits(0x7fffffff), target: NaN, is_correct: true }, { test_val: f32Bits(0xffffffff), target: NaN, is_correct: true }, { test_val: f32Bits(kBit.f32.infinity.positive), target: NaN, is_correct: false }, { test_val: f32Bits(kBit.f32.infinity.negative), target: NaN, is_correct: false }, { test_val: f32Bits(kBit.f32.positive.zero), target: NaN, is_correct: false }, { test_val: f32Bits(kBit.f32.negative.zero), target: NaN, is_correct: false }, // Infinities // prettier-ignore { test_val: f32Bits(kBit.f32.nan.positive.s), target: Number.POSITIVE_INFINITY, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.nan.positive.q), target: Number.POSITIVE_INFINITY, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.nan.negative.s), target: Number.POSITIVE_INFINITY, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.nan.negative.q), target: Number.POSITIVE_INFINITY, is_correct: false }, { test_val: f32Bits(0x7fffffff), target: Number.POSITIVE_INFINITY, is_correct: false }, { test_val: f32Bits(0xffffffff), target: Number.POSITIVE_INFINITY, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.infinity.positive), target: Number.POSITIVE_INFINITY, is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.infinity.negative), target: Number.POSITIVE_INFINITY, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.nan.positive.s), target: Number.NEGATIVE_INFINITY, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.nan.positive.q), target: Number.NEGATIVE_INFINITY, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.nan.negative.s), target: Number.NEGATIVE_INFINITY, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.nan.negative.q), target: Number.NEGATIVE_INFINITY, is_correct: false }, { test_val: f32Bits(0x7fffffff), target: Number.NEGATIVE_INFINITY, is_correct: false }, { test_val: f32Bits(0xffffffff), target: Number.NEGATIVE_INFINITY, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.infinity.positive), target: Number.NEGATIVE_INFINITY, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.infinity.negative), target: Number.NEGATIVE_INFINITY, is_correct: true }, // Zeros { test_val: f32Bits(kBit.f32.positive.zero), target: 0, is_correct: true }, { test_val: f32Bits(kBit.f32.negative.zero), target: 0, is_correct: true }, { test_val: f32Bits(kBit.f32.subnormal.positive.min), target: 0, is_correct: false }, { test_val: f32Bits(kBit.f32.subnormal.positive.max), target: 0, is_correct: false }, { test_val: f32Bits(kBit.f32.subnormal.negative.max), target: 0, is_correct: false }, { test_val: f32Bits(kBit.f32.subnormal.negative.min), target: 0, is_correct: false }, { test_val: f32Bits(kBit.f32.positive.zero), target: -0, is_correct: true }, { test_val: f32Bits(kBit.f32.negative.zero), target: -0, is_correct: true }, { test_val: f32Bits(kBit.f32.subnormal.positive.min), target: -0, is_correct: false }, { test_val: f32Bits(kBit.f32.subnormal.positive.max), target: -0, is_correct: false }, { test_val: f32Bits(kBit.f32.subnormal.negative.max), target: -0, is_correct: false }, { test_val: f32Bits(kBit.f32.subnormal.negative.min), target: -0, is_correct: false }, // 32-bit subnormals // prettier-ignore { test_val: f32Bits(kBit.f32.positive.zero), target: f32Bits(kBit.f32.subnormal.positive.min).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.negative.zero), target: f32Bits(kBit.f32.subnormal.positive.min).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.positive.min), target: f32Bits(kBit.f32.subnormal.positive.min).value as number, is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.positive.max), target: f32Bits(kBit.f32.subnormal.positive.min).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.negative.max), target: f32Bits(kBit.f32.subnormal.positive.min).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.negative.min), target: f32Bits(kBit.f32.subnormal.positive.min).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.positive.zero), target: f32Bits(kBit.f32.subnormal.positive.max).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.negative.zero), target: f32Bits(kBit.f32.subnormal.positive.max).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.positive.min), target: f32Bits(kBit.f32.subnormal.positive.max).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.positive.max), target: f32Bits(kBit.f32.subnormal.positive.max).value as number, is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.negative.max), target: f32Bits(kBit.f32.subnormal.positive.max).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.negative.min), target: f32Bits(kBit.f32.subnormal.positive.max).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.positive.zero), target: f32Bits(kBit.f32.subnormal.negative.max).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.negative.zero), target: f32Bits(kBit.f32.subnormal.negative.max).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.positive.min), target: f32Bits(kBit.f32.subnormal.negative.max).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.positive.max), target: f32Bits(kBit.f32.subnormal.negative.max).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.negative.max), target: f32Bits(kBit.f32.subnormal.negative.max).value as number, is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.negative.min), target: f32Bits(kBit.f32.subnormal.negative.max).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.positive.zero), target: f32Bits(kBit.f32.subnormal.negative.min).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.negative.zero), target: f32Bits(kBit.f32.subnormal.negative.min).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.positive.min), target: f32Bits(kBit.f32.subnormal.negative.min).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.positive.max), target: f32Bits(kBit.f32.subnormal.negative.min).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.negative.max), target: f32Bits(kBit.f32.subnormal.negative.min).value as number, is_correct: false }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.negative.min), target: f32Bits(kBit.f32.subnormal.negative.min).value as number, is_correct: true }, // 64-bit subnormals // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.positive.min), target: hexToFloat64(0x00000000, 0x00000001), is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.positive.zero), target: hexToFloat64(0x00000000, 0x00000001), is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.negative.zero), target: hexToFloat64(0x00000000, 0x00000001), is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.positive.min), target: hexToFloat64(0x00000000, 0x00000002), is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.positive.zero), target: hexToFloat64(0x00000000, 0x00000002), is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.negative.zero), target: hexToFloat64(0x00000000, 0x00000002), is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.negative.max), target: hexToFloat64(0x800fffff, 0xffffffff), is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.positive.zero), target: hexToFloat64(0x800fffff, 0xffffffff), is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.negative.zero), target: hexToFloat64(0x800fffff, 0xffffffff), is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.subnormal.negative.max), target: hexToFloat64(0x800fffff, 0xfffffffe), is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.positive.zero), target: hexToFloat64(0x800fffff, 0xfffffffe), is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.negative.zero), target: hexToFloat64(0x800fffff, 0xfffffffe), is_correct: true }, // 32-bit normals // prettier-ignore { test_val: f32Bits(kBit.f32.positive.max), target: hexToF32(kBit.f32.positive.max), is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.positive.min), target: hexToF32(kBit.f32.positive.min), is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.negative.max), target: hexToF32(kBit.f32.negative.max), is_correct: true }, // prettier-ignore { test_val: f32Bits(kBit.f32.negative.min), target: hexToF32(kBit.f32.negative.min), is_correct: true }, { test_val: f32Bits(0x03800000), target: hexToF32(0x03800000), is_correct: true }, { test_val: f32Bits(0x03800001), target: hexToF32(0x03800001), is_correct: true }, { test_val: f32Bits(0x83800000), target: hexToF32(0x83800000), is_correct: true }, { test_val: f32Bits(0x83800001), target: hexToF32(0x83800001), is_correct: true }, // 64-bit normals // prettier-ignore { test_val: f32Bits(0x3f800000), target: hexToFloat64(0x3ff00000, 0x00000001), is_correct: true }, // prettier-ignore { test_val: f32Bits(0x3f800001), target: hexToFloat64(0x3ff00000, 0x00000001), is_correct: true }, // prettier-ignore { test_val: f32Bits(0x3f800000), target: hexToFloat64(0x3ff00000, 0x00000002), is_correct: true }, // prettier-ignore { test_val: f32Bits(0x3f800001), target: hexToFloat64(0x3ff00000, 0x00000002), is_correct: true }, // prettier-ignore { test_val: f32Bits(0xbf800000), target: hexToFloat64(0xbff00000, 0x00000001), is_correct: true }, // prettier-ignore { test_val: f32Bits(0xbf800001), target: hexToFloat64(0xbff00000, 0x00000001), is_correct: true }, // prettier-ignore { test_val: f32Bits(0xbf800000), target: hexToFloat64(0xbff00000, 0x00000002), is_correct: true }, // prettier-ignore { test_val: f32Bits(0xbf800001), target: hexToFloat64(0xbff00000, 0x00000002), is_correct: true }, ]) .fn(t => { const test_val = t.params.test_val; const target = t.params.target; const is_correct = t.params.is_correct; const got = correctlyRounded(test_val, target); t.expect( got === is_correct, `correctlyRounded(${test_val}, ${target}) returned ${got}. Expected ${is_correct}` ); });
the_stack
interface pbxFile { basename: string; lastKnownFileType?: string; group?: string; path?: string; fileEncoding?: number; defaultEncoding?: number; sourceTree: string; includeInIndex?: number; explicitFileType?: unknown; settings?: object; uuid?: string; fileRef: string; target?: string; } declare module 'xcode' { /** * UUID that is a key to each fragment of PBXProject. */ type UUID = string; /** * if has following format `${UUID}_comment` */ type UUIDComment = string; type XCObjectType = | 'PBXBuildFile' | 'PBXFileReference' | 'PBXFrameworksBuildPhase' | 'PBXGroup' | 'PBXNativeTarget' | 'PBXProject' | 'PBXResourcesBuildPhase' | 'PBXShellScriptBuildPhase' | 'PBXSourcesBuildPhase' | 'PBXVariantGroup' | 'XCBuildConfiguration' | 'XCConfigurationList'; type PBXFile = pbxFile; interface PBXProject { isa: 'PBXProject'; attributes: { LastUpgradeCheck: number; TargetAttributes: Record< UUID, { CreatedOnToolsVersion?: string; TestTargetID?: UUID; LastSwiftMigration?: number; ProvisioningStyle?: string; } & Record<string, undefined | number | string> >; }; buildConfigurationList: UUID; buildConfigurationList_comment: string; compatibilityVersion: string; developmentRegion: string; hasScannedForEncodings: number; knownRegions: string[]; mainGroup: UUID; productRefGroup: UUID; productRefGroup_comment: string; projectDirPath: string; projectRoot: string; targets: Array<{ value: UUID; comment: string; }>; } interface PBXNativeTarget { isa: 'PBXNativeTarget'; buildConfigurationList: UUID; buildConfigurationList_comment: string; buildPhases: Array<{ value: UUID; comment: string; }>; buildRules: []; dependencies: []; name: string; productName: string; productReference: UUID; productReference_comment: string; productType: string; } interface PBXBuildFile { isa: 'PBXBuildFile'; fileRef: UUID; // "AppDelegate.m" fileRef_comment: string; } interface XCConfigurationList { isa: 'XCConfigurationList'; buildConfigurations: Array<{ value: UUID; comment: string | 'Release' | 'Debug'; }>; defaultConfigurationIsVisible: number; defaultConfigurationName: string; } interface XCBuildConfiguration { isa: 'XCBuildConfiguration'; baseConfigurationReference: UUID; baseConfigurationReference_comment: string; buildSettings: Record<string, string | undefined | number | Array<unknown>> & { // '"$(TARGET_NAME)"', PRODUCT_NAME?: string; // '"io.expo.demo.$(PRODUCT_NAME:rfc1034identifier)"', PRODUCT_BUNDLE_IDENTIFIER?: string; PROVISIONING_PROFILE_SPECIFIER?: string; // '"$(BUILT_PRODUCTS_DIR)/rni.app/rni"' TEST_HOST?: any; DEVELOPMENT_TEAM?: string; CODE_SIGN_IDENTITY?: string; CODE_SIGN_STYLE?: string; // '"$(TEST_HOST)"' BUNDLE_LOADER?: string; GCC_PREPROCESSOR_DEFINITIONS?: Array<unknown>; INFOPLIST_FILE?: string; IPHONEOS_DEPLOYMENT_TARGET?: string; LD_RUNPATH_SEARCH_PATHS?: string; OTHER_LDFLAGS?: Array<unknown>; ASSETCATALOG_COMPILER_APPICON_NAME?: string; ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME?: string; CLANG_ANALYZER_NONNULL?: string; CLANG_WARN_DOCUMENTATION_COMMENTS?: string; CLANG_WARN_INFINITE_RECURSION?: string; CLANG_WARN_SUSPICIOUS_MOVE?: string; DEBUG_INFORMATION_FORMAT?: string; ENABLE_TESTABILITY?: string; GCC_NO_COMMON_BLOCKS?: string; // 'appletvos' SDKROOT?: string; TARGETED_DEVICE_FAMILY?: number | string; // '10.0' TVOS_DEPLOYMENT_TARGET?: string; }; name: string; } type ProductType = | 'com.apple.product-type.application' | 'com.apple.product-type.app-extension' | 'com.apple.product-type.bundle' | 'com.apple.product-type.tool' | 'com.apple.product-type.library.dynamic' | 'com.apple.product-type.framework' | 'com.apple.product-type.library.static' | 'com.apple.product-type.bundle.unit-test' | 'com.apple.product-type.application.watchapp' | 'com.apple.product-type.application.watchapp2' | 'com.apple.product-type.watchkit-extension' | 'com.apple.product-type.watchkit2-extension'; interface PBXGroup { isa: 'PBXGroup'; children: Array<{ value: UUID; comment?: string; }>; name: string; path?: string; sourceTree: '"<group>"' | unknown; } export class XcodeProject { /** * `.pbxproj` file path. */ public filepath: string; // Ex: '$(TARGET_NAME)' public productName: string; public hash: { headComment: string; project: { archiveVersion: number; objectVersion: number; objects: { [T in XCObjectType]: Record< string, { isa: T; name: string; [key: string]: any; } >; }; rootObject: string; rootObject_comment: string; }; }; constructor(pbxprojPath: string); // ------------------------------------------------------------------------ // // `.pbxproj` related operation - starting & ending point. // // ------------------------------------------------------------------------ /** * First step to be executed while working with `.pbxproj` file. */ public parse(callback?: (err: Error | null, results?: string) => void): this; public parseSync(): void; /** * @returns Content of .pbxproj file. */ public writeSync(options?: { omitEmptyValues?: boolean }): string; public allUuids(): UUID[]; public generateUuid(): UUID; public addPluginFile(path: unknown, opt: unknown): unknown; public removePluginFile(path: unknown, opt: unknown): unknown; public addProductFile(targetPath: unknown, opt: unknown): unknown; public removeProductFile(path: unknown, opt: unknown): unknown; public addSourceFile(path: string, opt: unknown, group: string): unknown; public removeSourceFile(path: string, opt: unknown, group: string): unknown; public addHeaderFile(path: string, opt: unknown, group: string): unknown; public removeHeaderFile(path: string, opt: unknown, group: string): unknown; public addResourceFile(path: string, opt: unknown, group: string): unknown; public removeResourceFile(path: string, opt: unknown, group: string): unknown; public addFramework(fpath: unknown, opt: unknown): unknown; public removeFramework(fpath: unknown, opt: unknown): unknown; public addCopyfile(fpath: unknown, opt: unknown): unknown; public pbxCopyfilesBuildPhaseObj(target: unknown): unknown; public addToPbxCopyfilesBuildPhase(file: unknown): void; public removeCopyfile(fpath: unknown, opt: unknown): unknown; public removeFromPbxCopyfilesBuildPhase(file: unknown): void; public addStaticLibrary(path: unknown, opt: unknown): unknown; /** * Adds to `PBXBuildFile` section */ public addToPbxBuildFileSection(file: PBXFile): void; public removeFromPbxBuildFileSection(file: unknown): void; public addPbxGroup( filePathsArray: string[], name: string, path: string, sourceTree?: string, ): { uuid: UUID; pbxGroup: PBXGroup }; public removePbxGroup(groupName: unknown): void; public addToPbxProjectSection(target: unknown): void; public addToPbxNativeTargetSection(target: unknown): void; public addToPbxFileReferenceSection(file: any): void; public removeFromPbxFileReferenceSection(file: unknown): unknown; public addToXcVersionGroupSection(file: unknown): void; public addToPluginsPbxGroup(file: unknown): void; public removeFromPluginsPbxGroup(file: unknown): unknown; public addToResourcesPbxGroup(file: unknown): void; public removeFromResourcesPbxGroup(file: unknown): unknown; public addToFrameworksPbxGroup(file: unknown): void; public removeFromFrameworksPbxGroup(file: unknown): unknown; public addToPbxEmbedFrameworksBuildPhase(file: unknown): void; public removeFromPbxEmbedFrameworksBuildPhase(file: unknown): void; public addToProductsPbxGroup(file: unknown): void; public removeFromProductsPbxGroup(file: unknown): unknown; public addToPbxSourcesBuildPhase(file: unknown): void; public removeFromPbxSourcesBuildPhase(file: unknown): void; /** * Adds to PBXResourcesBuildPhase` section * @param resourcesBuildPhaseSectionKey Because there's might more than one `Resources` build phase we need to ensure file is placed under correct one. */ public addToPbxResourcesBuildPhase(file: PBXFile): void; public removeFromPbxResourcesBuildPhase(file: unknown): void; public addToPbxFrameworksBuildPhase(file: unknown): void; public removeFromPbxFrameworksBuildPhase(file: unknown): void; public addXCConfigurationList( configurationObjectsArray: unknown, defaultConfigurationName: unknown, comment: unknown, ): { uuid: unknown; xcConfigurationList: { isa: string; buildConfigurations: Array<unknown>; defaultConfigurationIsVisible: number; defaultConfigurationName: unknown; }; }; public addTargetDependency( target: unknown, dependencyTargets: unknown, ): { uuid: unknown; target: unknown; }; public addBuildPhase( filePathsArray: unknown, buildPhaseType: unknown, comment: unknown, target: unknown, optionsOrFolderType: unknown, subfolderPath: unknown, ): { uuid: unknown; buildPhase: { isa: unknown; buildActionMask: number; files: Array<unknown>; runOnlyForDeploymentPostprocessing: number; }; }; /** * Retrieves main part describing PBXProjects that are available in `.pbxproj` file. */ public pbxProjectSection(): Record<UUID, PBXProject> & Record<UUIDComment, string>; public pbxBuildFileSection(): Record<UUID, PBXBuildFile> & Record<UUIDComment, string>; public pbxXCBuildConfigurationSection(): Record<UUID, XCBuildConfiguration> & Record<UUIDComment, string>; public pbxFileReferenceSection(): Record<UUID, PBXFile> & Record<UUIDComment, string>; public pbxNativeTargetSection(): Record<UUID, PBXNativeTarget> & Record<UUIDComment, string>; public xcVersionGroupSection(): unknown; public pbxXCConfigurationList(): Record<UUID, XCConfigurationList> & Record<UUIDComment, string>; public pbxGroupByName(name: string): PBXGroup | undefined; /** * @param targetName in most cases it's the name of the application */ public pbxTargetByName(targetName: string): PBXNativeTarget | undefined; public findTargetKey(name: string): string; public pbxItemByComment(name: string, pbxSectionName: unknown): unknown; public pbxSourcesBuildPhaseObj(target: unknown): unknown; public pbxResourcesBuildPhaseObj(target: unknown): unknown; public pbxFrameworksBuildPhaseObj(target: unknown): unknown; public pbxEmbedFrameworksBuildPhaseObj(target: unknown): unknown; public buildPhase(group: unknown, target: unknown): string; public buildPhaseObject(name: string, group: unknown, target: unknown): unknown; public addBuildProperty(prop: unknown, value: unknown, build_name: unknown): void; public removeBuildProperty(prop: unknown, build_name: unknown): void; public updateBuildProperty(prop: string, value: unknown, build: string): void; public updateProductName(name: string): void; public removeFromFrameworkSearchPaths(file: unknown): void; public addToFrameworkSearchPaths(file: unknown): void; public removeFromLibrarySearchPaths(file: unknown): void; public addToLibrarySearchPaths(file: unknown): void; public removeFromHeaderSearchPaths(file: unknown): void; public addToHeaderSearchPaths(file: unknown): void; public addToOtherLinkerFlags(flag: unknown): void; public removeFromOtherLinkerFlags(flag: unknown): void; public addToBuildSettings(buildSetting: unknown, value: unknown): void; public removeFromBuildSettings(buildSetting: unknown): void; /** * Checks whether there is a file with given `filePath` in the project. */ public hasFile(filePath: string): PBXFile | false; public addTarget( name: unknown, type: unknown, subfolder: unknown, ): { uuid: unknown; pbxNativeTarget: { isa: string; name: string; productName: string; productReference: unknown; productType: string; buildConfigurationList: unknown; buildPhases: Array<unknown>; buildRules: Array<unknown>; dependencies: Array<unknown>; }; }; /** * Get First PBXProject that can be found in `.pbxproj` file. */ public getFirstProject(): { uuid: UUID; firstProject: PBXProject }; public getFirstTarget(): { uuid: UUID; firstTarget: unknown; }; /** * Retrieves PBXNativeTarget by the type */ public getTarget(productType: ProductType): { uuid: UUID; target: PBXNativeTarget } | null; public addToPbxGroupType(file: unknown, groupKey: unknown, groupType: unknown): void; public addToPbxVariantGroup(file: unknown, groupKey: unknown): void; public addToPbxGroup(file: PBXFile, groupKey: UUID): void; public pbxCreateGroupWithType(name: unknown, pathName: unknown, groupType: unknown): unknown; public pbxCreateVariantGroup(name: unknown): unknown; public pbxCreateGroup(name: string, pathName: string): UUID; public removeFromPbxGroupAndType(file: unknown, groupKey: unknown, groupType: unknown): void; public removeFromPbxGroup(file: unknown, groupKey: unknown): void; public removeFromPbxVariantGroup(file: unknown, groupKey: unknown): void; public getPBXGroupByKeyAndType(key: unknown, groupType: unknown): unknown; /** * @param groupKey UUID. */ public getPBXGroupByKey(groupKey: string): PBXGroup | undefined; public getPBXVariantGroupByKey(key: unknown): unknown; public findPBXGroupKeyAndType(criteria: unknown, groupType: unknown): string; /** * @param criteria Params that should be used to locate desired PBXGroup. */ public findPBXGroupKey(criteria: { name?: string; path?: string }): UUID | undefined; public findPBXVariantGroupKey(criteria: unknown): string; public addLocalizationVariantGroup( name: unknown, ): { uuid: unknown; fileRef: unknown; basename: unknown; }; public addKnownRegion(name: string): void; public removeKnownRegion(name: string): void; public hasKnownRegion(name: string): boolean; public getPBXObject(name: string): unknown; /** * - creates `PBXFile` * - adds to `PBXFileReference` section * - adds to `PBXGroup` or `PBXVariantGroup` if applicable * @returns `null` if file is already in `pbxproj`. */ public addFile( path: string, group?: string, opt?: { plugin?: string; target?: string; variantGroup?: string; lastKnownFileType?: string; defaultEncoding?: 4; customFramework?: true; explicitFileType?: number; weak?: true; compilerFLags?: string; embed?: boolean; sign?: boolean; }, ): PBXFile | null; public removeFile(path: unknown, group: unknown, opt: unknown): unknown; public getBuildProperty(prop: unknown, build: unknown): unknown; public getBuildConfigByName(name: unknown): object; public addDataModelDocument(filePath: unknown, group: unknown, opt: unknown): unknown; public addTargetAttribute(prop: unknown, value: unknown, target: unknown): void; public removeTargetAttribute(prop: unknown, target: unknown): void; } export function project(projectPath: string): XcodeProject; } declare module 'xcode/lib/pbxFile' { export default class PBXFile implements pbxFile { public basename: string; public lastKnownFileType?: string; public group?: string; public path?: string; public fileEncoding?: number; public defaultEncoding?: number; public sourceTree: string; public includeInIndex?: number; public explicitFileType?: unknown; public settings?: object; public uuid?: string; public fileRef: string; public target?: string; constructor(file: string); } }
the_stack
import React, { useCallback, useMemo } from 'react'; import { defineMessages } from 'react-intl'; import { ColonyRole, ROOT_DOMAIN_ID } from '@colony/colony-js'; import sortBy from 'lodash/sortBy'; import { FormikProps } from 'formik'; import { InputLabel, Select, Annotations } from '~core/Fields'; import { DialogSection } from '~core/Dialog'; import Heading from '~core/Heading'; import PermissionRequiredInfo from '~core/PermissionRequiredInfo'; import SingleUserPicker, { filterUserSelection } from '~core/SingleUserPicker'; import Toggle from '~core/Fields/Toggle'; import { ItemDataType } from '~core/OmniPicker'; import MotionDomainSelect from '~dashboard/MotionDomainSelect'; import HookedUserAvatar from '~users/HookedUserAvatar'; import { Address } from '~types/index'; import { useMembersSubscription, AnyUser, Colony } from '~data/index'; import { useTransformer } from '~utils/hooks'; import { getAllUserRolesForDomain } from '../../../transformers'; import { availableRoles } from './constants'; import { FormValues } from './PermissionManagementDialog'; import PermissionManagementCheckbox from './PermissionManagementCheckbox'; import styles from './PermissionManagementDialog.css'; const MSG = defineMessages({ title: { id: 'dashboard.PermissionManagementDialog.PermissionManagementForm.title', defaultMessage: 'Permissions', }, domain: { id: 'dashboard.PermissionManagementDialog.PermissionManagementForm.domain', defaultMessage: 'Team', }, permissionsLabel: { id: `dashboard .PermissionManagementDialog.PermissionManagementForm.permissionsLabel`, defaultMessage: 'Permissions', }, annotation: { id: `dashboard.PermissionManagementDialog.PermissionManagementForm.annotation`, defaultMessage: 'Explain why you’re making these changes (optional)', }, selectUser: { id: `dashboard.PermissionManagementDialog.PermissionManagementForm.selectUser`, defaultMessage: 'Member', }, userPickerPlaceholder: { id: 'SingleUserPicker.userPickerPlaceholder', defaultMessage: 'Search for a user or paste wallet address', }, }); interface Props { colony: Colony; currentUserRoles: ColonyRole[]; domainId: number; rootAccounts: Address[]; userDirectRoles: ColonyRole[]; currentUserRolesInRoot: ColonyRole[]; userInheritedRoles: ColonyRole[]; onDomainSelected: (domain: number) => void; onChangeSelectedUser: (user: AnyUser) => void; onMotionDomainChange: (domain: number) => void; inputDisabled: boolean; userHasPermission: boolean; isVotingExtensionEnabled: boolean; } const UserAvatar = HookedUserAvatar({ fetchUser: false }); const supRenderAvatar = (address: string, item: ItemDataType<AnyUser>) => ( <UserAvatar address={address} user={item} size="xs" notSet={false} /> ); const PermissionManagementForm = ({ colony: { colonyAddress, domains }, colony, currentUserRoles, domainId, rootAccounts, userDirectRoles, userInheritedRoles, currentUserRolesInRoot, inputDisabled, userHasPermission, isVotingExtensionEnabled, onDomainSelected, onMotionDomainChange, onChangeSelectedUser, values, }: Props & FormikProps<FormValues>) => { const { data: colonyMembers } = useMembersSubscription({ variables: { colonyAddress, }, }); const domain = domains?.find(({ ethDomainId }) => ethDomainId === domainId); const canSetPermissionsInRoot = domainId === ROOT_DOMAIN_ID && currentUserRoles.includes(ColonyRole.Root) && (!userDirectRoles.includes(ColonyRole.Root) || rootAccounts.length > 1); const hasRoot = currentUserRolesInRoot.includes(ColonyRole.Root); const hasArchitectureInRoot = currentUserRolesInRoot.includes( ColonyRole.Architecture, ); const canEditPermissions = (domainId === ROOT_DOMAIN_ID && currentUserRolesInRoot.includes(ColonyRole.Root)) || currentUserRolesInRoot.includes(ColonyRole.Architecture); const requiredRoles: ColonyRole[] = [ColonyRole.Architecture]; // Check which roles the current user is allowed to set in this domain const canRoleBeSet = useCallback( (role: ColonyRole) => { switch (role) { // Can't set arbitration at all yet case ColonyRole.Arbitration: return false; // Can only be set by root and in root domain (and only unset if other root accounts exist) case ColonyRole.Root: case ColonyRole.Recovery: return canSetPermissionsInRoot; // Must be root for these case ColonyRole.Administration: case ColonyRole.Funding: return hasArchitectureInRoot; // Can be set if root domain and has root OR has architecture in parent case ColonyRole.Architecture: return ( (domainId === ROOT_DOMAIN_ID && hasRoot) || hasArchitectureInRoot ); default: return false; } }, [domainId, canSetPermissionsInRoot, hasArchitectureInRoot, hasRoot], ); const domainRoles = useTransformer(getAllUserRolesForDomain, [ colony, domainId, ]); const directDomainRoles = useTransformer(getAllUserRolesForDomain, [ colony, domainId, true, ]); const domainSelectOptions = sortBy( domains.map(({ ethDomainId, name }) => ({ value: ethDomainId.toString(), label: name, })), ['value'], ); const domainRolesArray = useMemo( () => domainRoles .sort(({ roles }) => (roles.includes(ColonyRole.Root) ? -1 : 1)) .filter(({ roles }) => !!roles.length) .map(({ address, roles }) => { const directUserRoles = directDomainRoles.find( ({ address: userAddress }) => userAddress === address, ); return { userAddress: address, roles, directRoles: directUserRoles ? directUserRoles.roles : [], }; }), [directDomainRoles, domainRoles], ); const members = (colonyMembers?.subscribedUsers || []).map((user) => { const { profile: { walletAddress }, } = user; const domainRole = domainRolesArray.find( (rolesObject) => rolesObject.userAddress === walletAddress, ); return { ...user, roles: domainRole ? domainRole.roles : [], directRoles: domainRole ? domainRole.directRoles : [], }; }); const handleDomainChange = useCallback( (domainValue: string) => { const fromDomainId = parseInt(domainValue, 10); const selectedMotionDomainId = parseInt(values.motionDomainId, 10); onDomainSelected(fromDomainId); if ( selectedMotionDomainId !== ROOT_DOMAIN_ID && selectedMotionDomainId !== fromDomainId ) { onMotionDomainChange(fromDomainId); } }, [onDomainSelected, onMotionDomainChange, values.motionDomainId], ); const handleFilterMotionDomains = useCallback( (optionDomain) => { const optionDomainId = parseInt(optionDomain.value, 10); if (domainId === ROOT_DOMAIN_ID) { return optionDomainId === ROOT_DOMAIN_ID; } return optionDomainId === domainId || optionDomainId === ROOT_DOMAIN_ID; }, [domainId], ); const handleMotionDomainChange = useCallback( (motionDomainId) => onMotionDomainChange(motionDomainId), [onMotionDomainChange], ); const filteredRoles = useMemo( () => domainId !== ROOT_DOMAIN_ID ? availableRoles.filter( (role) => role !== ColonyRole.Root && role !== ColonyRole.Recovery, ) : availableRoles, [domainId], ); return ( <> <DialogSection appearance={{ theme: 'sidePadding' }}> <div className={styles.modalHeading}> {isVotingExtensionEnabled && ( <div className={styles.motionVoteDomain}> <MotionDomainSelect colony={colony} onDomainChange={handleMotionDomainChange} disabled={values.forceAction} /* * @NOTE We can only create a motion to vote in a subdomain if we * create a payment from that subdomain */ filterDomains={handleFilterMotionDomains} initialSelectedDomain={parseInt(values.motionDomainId, 10)} /> </div> )} <div className={styles.headingContainer}> <Heading appearance={{ size: 'medium', margin: 'none', theme: 'dark' }} text={MSG.title} textValues={{ domain: domain?.name }} /> {canEditPermissions && isVotingExtensionEnabled && ( <Toggle label={{ id: 'label.force' }} name="forceAction" /> )} </div> </div> </DialogSection> {!userHasPermission && ( <DialogSection> <PermissionRequiredInfo requiredRoles={requiredRoles} /> </DialogSection> )} <DialogSection appearance={{ theme: 'sidePadding' }}> <div className={styles.singleUserContainer}> <SingleUserPicker data={members} label={MSG.selectUser} name="user" filter={filterUserSelection} onSelected={onChangeSelectedUser} renderAvatar={supRenderAvatar} disabled={inputDisabled} placeholder={MSG.userPickerPlaceholder} /> </div> </DialogSection> <DialogSection appearance={{ theme: 'sidePadding' }}> <div className={styles.domainSelectContainer}> <Select options={domainSelectOptions} label={MSG.domain} name="domainId" appearance={{ theme: 'grey' }} onChange={handleDomainChange} /> </div> <InputLabel label={MSG.permissionsLabel} appearance={{ colorSchema: 'grey' }} /> <div className={styles.permissionChoiceContainer}> {filteredRoles.map((role) => { const roleIsInherited = !userDirectRoles.includes(role) && userInheritedRoles.includes(role); return ( <PermissionManagementCheckbox key={role} disabled={ !isVotingExtensionEnabled ? inputDisabled || !canRoleBeSet(role) || roleIsInherited : false } role={role} asterisk={roleIsInherited} domainId={domainId} /> ); })} </div> <Annotations label={MSG.annotation} name="annotationMessage" disabled={inputDisabled} /> </DialogSection> </> ); }; export default PermissionManagementForm;
the_stack
import { useEffect, useState, Fragment } from 'react'; import Head from 'next/head'; import toast from 'react-hot-toast'; import { useClipboard } from 'use-clipboard-copy'; import { ChevronDownIcon, GlobeIcon, DocumentIcon, CollectionIcon } from '@heroicons/react/solid'; import { DocumentIcon as DocumentIconOutline } from '@heroicons/react/outline'; import { Menu, Transition } from '@headlessui/react'; import { IAWSEventPayload, ILog } from '@/types/index'; import Editor from '@/components/Editor'; import SaveEventModal from '@/components/Modals/SaveEventModal'; import ViewEventLog from '@/components/Modals/ViewEventLog'; import PublishEventIntervalModal from '@/components/Modals/PublishEventIntervalModal'; import useEvents from '@/hooks/useEvents'; import useLogs from '@/hooks/useLogs'; const tabs = [ { name: 'Event', href: '#', current: true }, // { name: 'Schema', href: '#', current: false }, // { name: 'Targets', href: '#', current: false }, ]; function classNames(...classes) { return classes.filter(Boolean).join(' '); } interface IEventViewerProps { id?: string; name?: string; schemaName: string; description?: string; version: string; payload: IAWSEventPayload; source: string; eventBus: string; detailType: string; isEditingEvent?: boolean; collectionId?: string; } const EventViewer = ({ id, name, schemaName, description, version, payload, source, detailType, eventBus, isEditingEvent = false, collectionId }: IEventViewerProps) => { const [editorValue, setEditorValue] = useState(payload); const [interval, setCustomInterval] = useState(null); const clipboard = useClipboard(); useEffect(() => { setEditorValue(payload); // eslint-disable-next-line react-hooks/exhaustive-deps }, [id, name, detailType]); const [showSaveEventModal, setShowEventModal] = useState(false); const [showPublishIntervalModal, setShowPublishIntervalModal] = useState(false); const [selectedLog, setSelectedLog] = useState(); const [__, { getLogsForEvent }] = useLogs(); const [_, { saveEvent, updateEvent, publishEvent }] = useEvents(); const logs = getLogsForEvent(id, detailType); const sendEventToBus = async (payload) => { try { toast.promise( publishEvent({ id, payload, }), { loading: 'Publishing event...', success: ( <div> <span className="block text-bold">Succesfully Published Event</span> <span className="block text-xs text-pink-500 ">{schemaName}</span> </div> ), error: ( <div> <span className="block text-bold text-red-400">Failed to publish event</span> <span className="block text-xs text-gray-500 ">{schemaName}</span> </div> ), }, { duration: 2000, icon: <DocumentIconOutline className="h-5 w-5 text-pink-400" />, } ); setSelectedLog(null); } catch (error) { toast.error('Failed to publish event'); } }; const handleResendEvent = async (log: ILog) => { const { payload } = log; await sendEventToBus(payload); setSelectedLog(null); }; const handlePublishEvent = async () => { await sendEventToBus(editorValue); }; const handleUpdateEvent = async () => { try { toast.promise( updateEvent({ id, payload: editorValue, collectionId, }), { loading: 'Updating event...', success: ( <div> <span className="block text-bold">Updated Event</span> <span className="block text-xs text-pink-500 ">{name}</span> </div> ), error: ( <div> <span className="block text-bold text-red-400">Failed to update event</span> <span className="block text-xs text-gray-500 ">{name}</span> </div> ), }, { duration: 2000, } ); } catch (error) { toast.error('Failed to update event'); } }; const handleSaveEvent = async (eventMetadata) => { try { const newEvent = await saveEvent({ detailType, source, version, eventBus, schemaName, payload: editorValue, ...eventMetadata, }); toast.success('Successfully saved event'); window.location.href = `/collection/${newEvent.collectionId}/event/${newEvent.id}`; // TODO Fix this with state updates. // router.push(`/collection/${newEvent.collectionId}/event/${newEvent.id}`); } catch (error) { toast.error('Failed to create event'); } }; const handleCreateInterval = async ({ interval: intervalInSeconds }) => { setCustomInterval({ value: intervalInSeconds, interval: setInterval(() => { handlePublishEvent(); }, intervalInSeconds * 1000), }); setShowPublishIntervalModal(false); }; const stopPublishInterval = async () => { clearInterval(interval.interval); setCustomInterval(null); }; const handleExportEvent = async () => { clipboard.copy( JSON.stringify( { detailType, source, version, eventBus, schemaName, payload: editorValue, descripton: description || '', name, }, null, 4 ) ); toast.success('Succesfully copied to clipboard'); }; return ( <div className="flex-1 flex flex-col"> <Head> <title>{name || detailType}</title> </Head> <SaveEventModal isOpen={showSaveEventModal} onCreate={handleSaveEvent} onCancel={() => setShowEventModal(false)} /> <ViewEventLog isOpen={!!selectedLog} log={selectedLog} onCancel={() => setSelectedLog(null)} onResend={handleResendEvent} /> <PublishEventIntervalModal isOpen={!!showPublishIntervalModal} onCancel={() => setShowPublishIntervalModal(null)} onCreate={handleCreateInterval} /> <> <header className="w-full"> <div className=" bg-white flex"> <div className=" w-full "> <div className="flex justify-between px-4 items-center py-4 bg-white border-b border-gray-200"> <div> <h2 className="text-2xl font-bold leading-7 text-gray-800 sm:text-3xl sm:truncate">{name || schemaName}</h2> {description && <h2 className="text-sm leading-7 text-gray-600 sm:truncate">{description}</h2>} <div className="mt-1 flex flex-col sm:flex-row sm:flex-wrap sm:mt-0 sm:space-x-6"> <div className="mt-2 flex items-center text-sm text-gray-400"> <GlobeIcon className="flex-shrink-0 mr-1.5 h-5 w-5 text-gray-500" aria-hidden="true" /> {eventBus} </div> <div className="mt-2 flex items-center text-sm text-gray-400"> <CollectionIcon className="flex-shrink-0 mr-1.5 h-5 w-5 text-gray-500" aria-hidden="true" /> {source} </div> <div className="mt-2 flex items-center text-sm text-gray-400"> <DocumentIcon className="flex-shrink-0 mr-1.5 h-5 w-5 text-gray-500" aria-hidden="true" /> {detailType} (v{version}) </div> </div> </div> <div className="space-x-3"> <span className="relative z-0 inline-flex shadow-sm rounded-md"> <button onClick={() => { interval ? stopPublishInterval() : handlePublishEvent(); }} type="button" className="relative inline-flex items-center px-4 py-2 rounded-l-md border border-pink-300 bg-pink-600 text-sm font-medium text-white hover:bg-pink-500 focus:z-10 focus:outline-none focus:ring-1 focus:ring-pink-500 focus:border-pink-500" > {interval ? 'Stop Publishing' : 'Publish Event'} </button> <Menu as="span" className="relative block"> {({ open }) => ( <> <Menu.Button className="relative inline-flex items-center px-2 py-2.5 rounded-r-md border border-pink-300 bg-pink-600 text-sm font-medium text-white hover:bg-pink-500 focus:z-10 focus:outline-none focus:ring-1 focus:ring-pink-500 focus:border-pink-500"> <span className="sr-only">Open options</span> <ChevronDownIcon className="h-5 w-5" aria-hidden="true" /> </Menu.Button> <Transition show={open} as={Fragment} enter="transition ease-out duration-100" enterFrom="transform opacity-0 scale-95" enterTo="transform opacity-100 scale-100" leave="transition ease-in duration-75" leaveFrom="transform opacity-100 scale-100" leaveTo="transform opacity-0 scale-95" > <Menu.Items static className="origin-top-right absolute right-0 mt-2 -mr-1 w-56 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 focus:outline-none"> <div className="py-1 hover:bg-gray-100"> <Menu.Item> <button onClick={() => setShowPublishIntervalModal(true)} className="text-gray-700 block px-4 py-2 text-sm"> Publish on Interval </button> </Menu.Item> </div> </Menu.Items> </Transition> </> )} </Menu> </span> <span className="relative z-0 inline-flex shadow-sm rounded-md"> <button onClick={() => { if (isEditingEvent) { handleUpdateEvent(); } else { setShowEventModal(true); } }} type="button" className="relative inline-flex items-center px-4 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 focus:z-10 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500" > Save </button> <Menu as="span" className="relative block"> {({ open }) => ( <> <Menu.Button className="relative inline-flex items-center px-2 py-2.5 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 focus:z-10 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500"> <span className="sr-only">Open options</span> <ChevronDownIcon className="h-5 w-5" aria-hidden="true" /> </Menu.Button> <Transition show={open} as={Fragment} enter="transition ease-out duration-100" enterFrom="transform opacity-0 scale-95" enterTo="transform opacity-100 scale-100" leave="transition ease-in duration-75" leaveFrom="transform opacity-100 scale-100" leaveTo="transform opacity-0 scale-95" > <Menu.Items static className="origin-top-right absolute right-0 mt-2 -mr-1 w-56 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 focus:outline-none"> <div className="py-1 hover:bg-gray-100"> <Menu.Item> <button onClick={() => setShowEventModal(true)} className="text-gray-700 block px-4 py-2 text-sm"> Save As... </button> </Menu.Item> </div> <div className="py-1 hover:bg-gray-100"> <Menu.Item> <button onClick={() => handleExportEvent()} className="text-gray-700 block px-4 py-2 text-sm"> Export Event </button> </Menu.Item> </div> </Menu.Items> </Transition> </> )} </Menu> </span> </div> </div> <div className="flex justify-between w-full px-4 pt-2 pb-0"> <div> <div className="sm:hidden"> <label htmlFor="tabs" className="sr-only"> Select a tab </label> <select id="tabs" name="tabs" className="block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md" defaultValue={tabs.find((tab) => tab.current).name}> {tabs.map((tab) => ( <option key={tab.name}>{tab.name}</option> ))} </select> </div> <div className="hidden sm:block"> <div className=""> <nav className="-mb-px flex" aria-label="Tabs"> {tabs.map((tab) => ( <a key={tab.name} href={tab.href} className={classNames(tab.current ? ' border-b-2 border-pink-400 text-gray-800 ' : ' text-gray-500 ', 'whitespace-nowrap py-3 px-8 font-medium text-sm ')} aria-current={tab.current ? 'page' : undefined}> {tab.name} </a> ))} </nav> </div> </div> </div> {interval && interval.value && <div className="mr-2 mt-4 text-xs animate-pulse text-gray-700 bg-green-200 p-2 rounded-lg">Currently publishing event every {interval.value} seconds...</div>} </div> </div> </div> </header> <div className="p-4 items-stretch"> <main className="flex-1 space-y-6"> <section aria-labelledby="primary-heading" className="flex mt-1 lg:order-last border border-gray-200"> <Editor value={JSON.stringify(editorValue, null, 4)} onChange={(value) => { try { setEditorValue(JSON.parse(value)); } catch (error) {} }} /> </section> {logs.length > 0 && ( <> <h2 className=" text-gray-800">Event Logs</h2> <div className="flex flex-col"> <div className="-my-2 sm:-mx-6 lg:-mx-8"> <div className="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8"> <div className="shadow border-b border-gray-200 sm:rounded-lg"> <table className="w-full divide-y divide-gray-200 border border-gray-200"> <thead className="bg-gray-500 text-gray-100"> <tr> <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider"> AWS Event ID </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider"> Status </th> <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider"> Created At </th> </tr> </thead> <tbody className="bg-white divide-y divide-gray-200"> {logs.reverse().map((log) => ( <tr key={log.awsPublishEventId}> <td className="px-6 py-4 whitespace-nowrap"> <button className="text-indigo-600 hover:text-indigo-900" onClick={() => setSelectedLog(log)}> {log.awsPublishEventId} </button> </td> <td className="px-6 py-4 whitespace-nowrap"> <span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">Success</span> </td> <td className="px-6 py-4 whitespace-nowrap">{log.createdAt}</td> </tr> ))} </tbody> </table> </div> </div> </div> </div> </> )} {logs.length === 0 && ( <div> <h2 className=" text-gray-800">Event Logs</h2> <p className="text-sm text-gray-500">No logs found. Start by publishing your event.</p> </div> )} </main> </div> </> </div> ); }; export default EventViewer;
the_stack
import { BatchingStrategy, Collab, CollabEvent, CRDTApp, CRDTRuntime, EventEmitter, Optional, Pre, Unsubscribe, } from "@collabs/collabs"; import { ContainerMessage, HostMessage, LoadMessage, SaveRequestMessage, } from "./message_types"; interface CRDTContainerEventsRecord { /** * Emitted each time the container's state is changed and * is in a reasonable user-facing state * (so not in the middle of a transaction). * * A simple way to keep a GUI in sync with the container is to * do `container.on("Change", refreshDisplay)`. * * Identical to [[CRDTApp]]'s "Change" event. */ Change: CollabEvent; } // Opt: is replicaID needed? // Opt: skip expensive CRDTMetadata where possible // (e.g. causal ordering is guaranteed for us). /** * Entrypoint for a Collabs container: a network-agnostic, * self-contained collaborative app that is deployed using static * files only. * * See [container docs](https://github.com/composablesys/collabs/blob/master/collabs/docs/containers.md). * * This class is similar to, and replaces, @collabs/collabs * `CRDTApp` class as the Collabs entrypoint. This means that * it is the first thing you construct when using Collabs, * and you register your top-level (global variable) Collabs * using [[registerCollab]]. Unlike `CRDTApp`, there are no * methods/events for sending or receiving messages or for * saving and loading; those are handled for you. * Specifically, those happen via communication with an instance * of [[CRDTContainerHost]] running in a separate window * (currently assumed to be `window.parent`). * * As the name suggests, `CRDTContainer` is specifically designed for use * with `Collab`s that are (op-based) CRDTs. Currently, this includes * all `Collab`s that come built-in with @collabs/collabs. * * ## `CRDTContainer` Lifecycle * * After construction a `CRDTContainer`, you must first * register your Collabs using [[registerCollab]]. * Afterwards, you must eventually call [[load]], await * its Promise, and then call [[ready]]. Only then can you * use the `CRDTContainer`, i.e., you can perform `Collab` * operations and the container will deliver messages * to the `Collab`s. * * See the * [container docs](https://github.com/composablesys/collabs/blob/master/collabs/docs/containers.md) * for step-by-step instructions on when to call these methods * during your app's setup. */ export class CRDTContainer extends EventEmitter<CRDTContainerEventsRecord> { private readonly app: CRDTApp; private readonly messagePort: MessagePort; private _isReady = false; /** * The ID of the last received message (-1 if none). * * This counts messages received as a result of loading. */ private lastReceivedID = -1; private loadEarlyMessage: LoadMessage | null = null; private loadResolve: ((message: LoadMessage) => void) | null = null; /** * Constructs a new `CRDTContainer` that connects to * a `CRDTContainerHost` running in `window.parent`. * * @param options Options to pass to the internal [[CRDTApp]]. * It is recommended that you leave `batchingStrategy` as * its default value (an `ImmediateBatchingStrategy`); * that way, the choice of batching is left up to your * container host. */ constructor(options?: { batchingStrategy?: BatchingStrategy; debugReplicaID?: string; }) { super(); // Setup a channel with our host's window. // For now, this is assumed to be window.parent. const channel = new MessageChannel(); this.messagePort = channel.port1; this.messagePort.onmessage = this.messagePortReceive.bind(this); window.parent.postMessage(null, "*", [channel.port2]); this.app = new CRDTApp({ ...options, causalityGuaranteed: true }); this.app.on("Change", (e) => this.emit("Change", e)); this.app.on("Send", (e) => { if (!this.isReady) { if (!this.isLoaded) { throw new Error( "Not yet ready (pending: load, receiveFurtherMessages)" ); } else { throw new Error("Not yet ready (pending: receiveFurtherMessages)"); } } this.messagePortSend({ type: "Send", message: e.message, predID: this.lastReceivedID, }); }); } private messagePortSend(message: HostMessage) { this.messagePort.postMessage(message); } private messagePortReceive(e: MessageEvent<ContainerMessage>) { switch (e.data.type) { case "Receive": // Make sure that loadFurtherMessages are processed // before any new messages. Probably this is assured // because the setTimeout in ready() should be queued // before any future MessagePort messages, but it // doesn't hurt to double check. this.receiveFurtherMessages(); this.app.receive(e.data.message); this.lastReceivedID = e.data.id; break; case "Load": // Dispatch the load message where [[load]] can get // it. If [[load]] was called already, we pass the message // to its Promise resolver, this.loadResolve; else // we store it in this.loadMessage. if (this.loadResolve !== null) { this.loadResolve(e.data); this.loadResolve = null; } else { this.loadEarlyMessage = e.data; } break; case "SaveRequest": // Note we ignore the returned Promise; processSaveRequest // completes independently. void this.processSaveRequest(e.data); break; default: throw new Error("bad e.data.type: " + e.data); } } /** * Constructs `preCollab` and registers it as a * top-level (global variable) `Collab` with the * given name. * * @param name The `Collab`'s name, which must be * unique among all registered `Collabs`. E.g., its name * as a variable in your program. * @param preCollab The `Collab` to construct, typically * created using a statement of the form * `Pre(class_name)<generic types>(constructor args)` * @return The registered `Collab`. You should assign * this to a variable for later use. */ registerCollab<C extends Collab>(name: string, preCollab: Pre<C>): C { return this.app.registerCollab(name, preCollab); } private loadFurtherMessages: Uint8Array[] | null = null; /** * Waits to receive prior save data from the container host, * then applies it to the registered `Collab`s. * * Analogous to `CRDTApp.load`, except that you don't have * to provide the save data; the host does that for us. * * @return Whether loading was skipped, i.e., there was no * prior save data. */ async load(): Promise<boolean> { // Get the load message from messagePortReceive. let loadMessage: LoadMessage; if (this.loadEarlyMessage !== null) { // loadMessage already arrived. // Do it in a Promise for consistency with the other // case, so that if the caller does stuff in the same // thread as loadSaveData (without awaiting), it will // always happen before loading. loadMessage = await Promise.resolve(this.loadEarlyMessage); } else { // Not yet arrived; await it. loadMessage = await new Promise((resolve) => { this.loadResolve = resolve; }); } // Store furtherMessages for receiveFurtherMessages. this.loadFurtherMessages = loadMessage.furtherMessages; // Load latestSaveData, if present. if (loadMessage.latestSaveData === null) { this.app.load(Optional.empty()); } else { this.app.load(Optional.of(loadMessage.latestSaveData)); } return loadMessage.latestSaveData === null; } /** * Signals to your container host that you are ready. * * Your host will then reveal the container to the user * (e.g., unhide its IFrame), allow user input, and start * delivering messages - both new messages from collaborators, * and old messages that didn't make it into the loaded state. */ ready(): void { if (this.loadFurtherMessages !== null) { setTimeout(() => this.receiveFurtherMessages()); } this.messagePortSend({ type: "Ready" }); this._isReady = true; } /** * Optionally, this may be called after [[load]] to cause * all "further messages" to be delivered immediately and * synchronously. * * The "further messages" are messages that should have been * part of our loaded save data (i.e., they were received * before the previous instance was saved), but were * not included. This can happen because * `CRDTContainerHost.save` must run synchronously, * so it does not have time to instruct us to call our * internal analog of `CRDTApp.save`. Instead, `CRDTContainerHost` * instructs us to do so occasionally, then saves any * further messages as part of its own save data. * (See [[onSaveRequest]].) * * Ordinarily, the further messages are delivered to your * `Collab`s in an event loop iteration after [[ready]] * is called. This makes them indistinguishable from newly * received messages. However, you can instead call this * method earlier (but after [[load]]). This is never * necessary but can serve as an optimization; see * the [container docs](https://github.com/composablesys/collabs/blob/master/collabs/docs/containers.md#loading). */ receiveFurtherMessages(): void { if (!this.app.isLoaded) { throw new Error("not yet loaded"); } if (this.loadFurtherMessages === null) return; const furtherMessages = this.loadFurtherMessages; this.loadFurtherMessages = null; furtherMessages.forEach((message) => this.app.receive(message)); this.lastReceivedID = furtherMessages.length - 1; } /** * Whether [[load]] has completed (including its Promise). */ get isLoaded(): boolean { return this.app.isLoaded; } /** * Whether [[ready]] has completed. */ get isReady(): boolean { return this._isReady; } /** * The internal [[CRDTRuntime]], i.e., the value of * `runtime` on any `Collab`. */ get runtime(): CRDTRuntime { return this.app.runtime; } private saveRequestHandlers = new Set< (caller: this) => void | Promise<void> >(); /** * Registers an event handler that is triggered and awaited * when the host makes a save request (due to * [[CRDTContainerHost.compactSaveData]] being called). * * The event handler will be run and awaited before * calling `runtime.save()` and responding to the save * request. So, you can use event handlers to make the * save data nicer/smaller before `runtime.save()` is called. * E.g., if you have your own [[CRDTContainerHost]], * you can call its [[CRDTContainerHost.compactSaveData]] * methods and return the resulting Promise, so that our save * data uses the nested container's compacted save data. * * @param handler Callback that handles the event (possibly async) * @return An "off" function that removes the event handler when called */ onSaveRequest(handler: (caller: this) => void | Promise<void>): Unsubscribe { this.saveRequestHandlers.add(handler); return () => this.saveRequestHandlers.delete(handler); } private async processSaveRequest(message: SaveRequestMessage): Promise<void> { try { // Make sure that loadFurtherMessages are processed // before saving. Probably this is assured // because the setTimeout in ready() should be queued // before any future MessagePort messages, but it // doesn't hurt to double check. this.receiveFurtherMessages(); // Wait for SaveRequest handlers to complete. const toAwait: Promise<void>[] = []; for (const handler of this.saveRequestHandlers) { try { const ret = handler(this); if (ret instanceof Promise) toAwait.push(ret); } catch (err) { // Don't let the error block other event handlers // or interrupt the save request as a whole // (there's still benefit in calling runtime.save()), // but still make it print // its error like it was unhandled. void Promise.resolve().then(() => { throw err; }); } } await Promise.all(toAwait); // Save and respond to the request. const saveData = this.app.save(); this.messagePortSend({ type: "Saved", saveData, lastReceivedID: this.lastReceivedID, requestID: message.requestID, }); } catch (error) { this.messagePortSend({ type: "SaveRequestFailed", requestID: message.requestID, errorToString: String(error), }); // Also "throw" the error separately, so it gets // logged in the console. void Promise.resolve().then(() => { throw error; }); } } }
the_stack
export namespace SemanticDataInterconnectModels { /** * * @export * @class RequiredError * @extends {Error} */ export class RequiredError extends Error { name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } } /** * * @export * @interface Aliases */ export interface Aliases { /** * * @type {string} * @memberof Aliases */ attributeName: string; /** * * @type {string} * @memberof Aliases */ aliasValue: string; } /** * * @export * @interface ApiErrorsView */ export interface ApiErrorsView { /** * * @type {Array<ApiFieldError>} * @memberof ApiErrorsView */ errors?: Array<ApiFieldError>; } /** * * @export * @interface ApiFieldError */ export interface ApiFieldError { /** * * @type {string} * @memberof ApiFieldError */ code?: string; /** * * @type {string} * @memberof ApiFieldError */ logref?: string; /** * * @type {string} * @memberof ApiFieldError */ message?: string; /** * * @type {Array<MessageParameter>} * @memberof ApiFieldError */ messageParameters?: Array<MessageParameter>; } /** * * @export * @interface CreateDataLakeRequest */ export interface CreateDataLakeRequest { /** * * @type {string} * @memberof CreateDataLakeRequest */ name?: string; /** * * @type {string} * @memberof CreateDataLakeRequest */ type?: CreateDataLakeRequest.TypeEnum; /** * This is currently supported only for the IDL customer. Please refer to the document section \"For Integrated Data Lake (IDL) customers\" on correct basePath structure. * @type {string} * @memberof CreateDataLakeRequest */ basePath?: string; } /** * @export * @namespace CreateDataLakeRequest */ export namespace CreateDataLakeRequest { /** * @export * @enum {string} */ export enum TypeEnum { MindSphere = <any>"MindSphere", Custom = <any>"Custom", } } /** * * @export * @interface CreateDataLakeResponse */ export interface CreateDataLakeResponse { /** * * @type {string} * @memberof CreateDataLakeResponse */ id?: string; /** * * @type {string} * @memberof CreateDataLakeResponse */ name?: string; /** * * @type {string} * @memberof CreateDataLakeResponse */ type?: CreateDataLakeResponse.TypeEnum; /** * * @type {string} * @memberof CreateDataLakeResponse */ basePath?: string; /** * * @type {string} * @memberof CreateDataLakeResponse */ createdDate?: string; /** * * @type {string} * @memberof CreateDataLakeResponse */ updatedDate?: string; } /** * @export * @namespace CreateDataLakeResponse */ export namespace CreateDataLakeResponse { /** * @export * @enum {string} */ export enum TypeEnum { MindSphere = <any>"MindSphere", Custom = <any>"Custom", } } /** * * @export * @interface CreateDataRegistryRequest */ export interface CreateDataRegistryRequest { /** * * @type {string} * @memberof CreateDataRegistryRequest */ dataTag?: string; /** * * @type {string} * @memberof CreateDataRegistryRequest */ defaultRootTag?: string; /** * * @type {string} * @memberof CreateDataRegistryRequest */ filePattern?: string; /** * * @type {string} * @memberof CreateDataRegistryRequest */ fileUploadStrategy?: CreateDataRegistryRequest.FileUploadStrategyEnum; /** * * @type {Array<string>} * @memberof CreateDataRegistryRequest */ metaDataTags?: Array<string>; /** * * @type {string} * @memberof CreateDataRegistryRequest */ sourceName?: string; /** * * @type {Array<string>} * @memberof CreateDataRegistryRequest */ xmlProcessRules?: Array<string>; /** * This property must be set to false during initial creation of a registry. It can be changed to true after the initial schema creation to reuse the existing schema for the newly ingested data * @type {boolean} * @memberof CreateDataRegistryRequest */ schemaFrozen?: boolean; } /** * @export * @namespace CreateDataRegistryRequest */ export namespace CreateDataRegistryRequest { /** * @export * @enum {string} */ export enum FileUploadStrategyEnum { Append = <any>"append", Replace = <any>"replace", } } /** * * @export * @interface DataLakeList */ export interface DataLakeList { /** * * @type {Array<DataLakeResponse>} * @memberof DataLakeList */ dataLakes?: Array<DataLakeResponse>; } /** * * @export * @interface DataLakeResponse */ export interface DataLakeResponse { /** * * @type {string} * @memberof DataLakeResponse */ basePath?: string; /** * * @type {string} * @memberof DataLakeResponse */ createdDate?: string; /** * * @type {string} * @memberof DataLakeResponse */ id?: string; /** * * @type {string} * @memberof DataLakeResponse */ updatedDate?: string; /** * * @type {string} * @memberof DataLakeResponse */ name?: string; /** * * @type {string} * @memberof DataLakeResponse */ type?: string; } /** * Either parameters or aliases must be present. * @export * @interface DataQueryExecuteQueryRequest */ export interface DataQueryExecuteQueryRequest { /** * * @type {string} * @memberof DataQueryExecuteQueryRequest */ description?: string; /** * * @type {Array<Parameters>} * @memberof DataQueryExecuteQueryRequest */ parameters?: Array<Parameters>; /** * * @type {Array<Aliases>} * @memberof DataQueryExecuteQueryRequest */ aliases?: Array<Aliases>; } /** * * @export * @interface DataQueryExecuteQueryResponse */ export interface DataQueryExecuteQueryResponse { /** * * @type {string} * @memberof DataQueryExecuteQueryResponse */ id?: string; /** * * @type {string} * @memberof DataQueryExecuteQueryResponse */ status?: string; /** * * @type {string} * @memberof DataQueryExecuteQueryResponse */ message?: string; } /** * * @export * @interface DataQueryExecutionResponse */ export interface DataQueryExecutionResponse { /** * * @type {string} * @memberof DataQueryExecutionResponse */ id?: string; /** * * @type {string} * @memberof DataQueryExecutionResponse */ description?: string; /** * * @type {Array<Parameters>} * @memberof DataQueryExecutionResponse */ parameters?: Array<Parameters>; /** * * @type {Array<Aliases>} * @memberof DataQueryExecutionResponse */ aliases?: Array<Aliases>; /** * * @type {string} * @memberof DataQueryExecutionResponse */ queryId?: string; /** * Status of execution job. - CURRENT: Job has executed successfully and results are current. - IN_PROGRESS: Job execution is in progress. - OUTDATED: Job execution completed but results are outdated. - FAILED: Job execution has failed. - OBSOLETE: Job execution completed but results are obsolete. * @type {string} * @memberof DataQueryExecutionResponse */ status?: DataQueryExecutionResponse.StatusEnum; /** * * @type {string} * @memberof DataQueryExecutionResponse */ createdDate?: string; /** * * @type {string} * @memberof DataQueryExecutionResponse */ updatedDate?: string; } /** * @export * @namespace DataQueryExecutionResponse */ export namespace DataQueryExecutionResponse { /** * @export * @enum {string} */ export enum StatusEnum { CURRENT = <any>"CURRENT", INPROGRESS = <any>"IN_PROGRESS", OUTDATED = <any>"OUTDATED", FAILED = <any>"FAILED", OBSOLETE = <any>"OBSOLETE", } } /** * * @export * @interface DataQuerySQLRequest */ export interface DataQuerySQLRequest { /** * * @type {string} * @memberof DataQuerySQLRequest */ description?: string; /** * * @type {boolean} * @memberof DataQuerySQLRequest */ isBusinessQuery?: boolean; /** * If isBusinessQuery is true then ontologyId must be passed. * @type {string} * @memberof DataQuerySQLRequest */ ontologyId?: string; /** * * @type {boolean} * @memberof DataQuerySQLRequest */ isDynamic?: boolean; /** * * @type {string} * @memberof DataQuerySQLRequest */ name: string; /** * Pass base64 encode value of spark sql like SELECT vehicle.vin, make.def FROM vehicle, make WHERE vehicle.make = make.id. Please refer SDI-How -to-create-query documentation for preparing sqlStatement. * @type {string} * @memberof DataQuerySQLRequest */ sqlStatement: string; } /** * * @export * @interface DataQuerySQLResponse */ export interface DataQuerySQLResponse { /** * * @type {string} * @memberof DataQuerySQLResponse */ createdDate?: string; /** * * @type {string} * @memberof DataQuerySQLResponse */ description?: string; /** * * @type {boolean} * @memberof DataQuerySQLResponse */ executable?: boolean; /** * * @type {string} * @memberof DataQuerySQLResponse */ id?: string; /** * * @type {boolean} * @memberof DataQuerySQLResponse */ isBusinessQuery?: boolean; /** * * @type {boolean} * @memberof DataQuerySQLResponse */ isDynamic?: boolean; /** * * @type {string} * @memberof DataQuerySQLResponse */ name?: string; /** * * @type {string} * @memberof DataQuerySQLResponse */ ontologyId?: string; /** * * @type {Array<MappingErrorSQLDetails>} * @memberof DataQuerySQLResponse */ pendingActions?: Array<MappingErrorSQLDetails>; /** * * @type {string} * @memberof DataQuerySQLResponse */ sqlStatement?: string; /** * * @type {string} * @memberof DataQuerySQLResponse */ updatedDate?: string; } /** * * @export * @interface DataQuerySQLUpdateRequest */ export interface DataQuerySQLUpdateRequest { /** * * @type {string} * @memberof DataQuerySQLUpdateRequest */ description?: string; /** * * @type {boolean} * @memberof DataQuerySQLUpdateRequest */ isBusinessQuery?: boolean; /** * If isBusinessQuery is true then ontologyId must be passed. * @type {string} * @memberof DataQuerySQLUpdateRequest */ ontologyId?: string; /** * * @type {boolean} * @memberof DataQuerySQLUpdateRequest */ isDynamic?: boolean; /** * * @type {string} * @memberof DataQuerySQLUpdateRequest */ name?: string; /** * Pass base64 encode value of spark sql like SELECT vehicle.vin, make.def FROM vehicle, make WHERE vehicle.make = make.id. Please refer SDI-How -to-create-query documentation for preparing sqlStatement. * @type {string} * @memberof DataQuerySQLUpdateRequest */ sqlStatement?: string; } /** * * @export * @interface DataRegistry */ export interface DataRegistry { /** * * @type {string} * @memberof DataRegistry */ createdDate?: string; /** * * @type {string} * @memberof DataRegistry */ dataTag?: string; /** * * @type {string} * @memberof DataRegistry */ defaultRootTag?: string; /** * * @type {string} * @memberof DataRegistry */ filePattern?: string; /** * * @type {string} * @memberof DataRegistry */ fileUploadStrategy?: DataRegistry.FileUploadStrategyEnum; /** * * @type {string} * @memberof DataRegistry */ updatedDate?: string; /** * * @type {Array<string>} * @memberof DataRegistry */ metaDataTags?: Array<string>; /** * * @type {Array<string>} * @memberof DataRegistry */ xmlProcessRules?: Array<string>; /** * * @type {boolean} * @memberof DataRegistry */ mutable?: boolean; /** * * @type {string} * @memberof DataRegistry */ registryId?: string; /** * * @type {string} * @memberof DataRegistry */ sourceId?: string; /** * * @type {string} * @memberof DataRegistry */ sourceName?: string; /** * * @type {boolean} * @memberof DataRegistry */ schemaFrozen?: boolean; } /** * @export * @namespace DataRegistry */ export namespace DataRegistry { /** * @export * @enum {string} */ export enum FileUploadStrategyEnum { Append = <any>"append", Replace = <any>"replace", } } /** * * @export * @interface DataTypeDefinition */ export interface DataTypeDefinition { /** * * @type {string} * @memberof DataTypeDefinition */ name?: string; /** * * @type {Array<string>} * @memberof DataTypeDefinition */ patterns?: Array<string>; } /** * * @export * @interface DataTypePattern */ export interface DataTypePattern { /** * * @type {Array<string>} * @memberof DataTypePattern */ patterns?: Array<string>; } /** * * @export * @interface ErrorMessage */ export interface ErrorMessage { /** * * @type {Array<ApiFieldError>} * @memberof ErrorMessage */ errors?: Array<ApiFieldError>; } /** * * @export * @interface GetAllSQLQueriesData */ export interface GetAllSQLQueriesData { /** * * @type {string} * @memberof GetAllSQLQueriesData */ createdBy?: string; /** * * @type {string} * @memberof GetAllSQLQueriesData */ createdDate?: string; /** * * @type {string} * @memberof GetAllSQLQueriesData */ description?: string; /** * * @type {boolean} * @memberof GetAllSQLQueriesData */ executable?: boolean; /** * * @type {string} * @memberof GetAllSQLQueriesData */ id?: string; /** * * @type {boolean} * @memberof GetAllSQLQueriesData */ isBusinessQuery?: boolean; /** * * @type {boolean} * @memberof GetAllSQLQueriesData */ isDynamic?: boolean; /** * * @type {string} * @memberof GetAllSQLQueriesData */ name?: string; /** * * @type {string} * @memberof GetAllSQLQueriesData */ ontologyId?: string; /** * * @type {Array<MappingErrorSQLDetails>} * @memberof GetAllSQLQueriesData */ pendingActions?: Array<MappingErrorSQLDetails>; /** * * @type {string} * @memberof GetAllSQLQueriesData */ updatedBy?: string; /** * * @type {string} * @memberof GetAllSQLQueriesData */ updatedDate?: string; } /** * * @export * @interface InferSchemaSearchRequest */ export interface InferSchemaSearchRequest { /** * * @type {Array<InferSearchObject>} * @memberof InferSchemaSearchRequest */ schemas?: Array<InferSearchObject>; /** * * @type {Array<string>} * @memberof InferSchemaSearchRequest */ excludeProperties?: Array<string>; } /** * * @export * @interface InferSearchObject */ export interface InferSearchObject { /** * * @type {string} * @memberof InferSearchObject */ dataTag?: string; /** * * @type {string} * @memberof InferSearchObject */ schemaName?: string; /** * * @type {string} * @memberof InferSearchObject */ sourceName?: string; /** * * @type {string} * @memberof InferSearchObject */ assetId?: string; /** * * @type {string} * @memberof InferSearchObject */ aspectName?: string; } /** * * @export * @interface InputClass */ export interface InputClass { /** * * @type {string} * @memberof InputClass */ description?: string; /** * * @type {string} * @memberof InputClass */ name?: string; /** * If class mapped with more than one schemas then user can define either one of them as primary schema. * @type {string} * @memberof InputClass */ primarySchema?: string; /** * Class keyMappingType. If Parent level 'keyMappingType' is defined then class 'keyMappingType' property will overwrite Parent level 'keyMappingType' value. * @type {string} * @memberof InputClass */ keyMappingType?: InputClass.KeyMappingTypeEnum; } /** * @export * @namespace InputClass */ export namespace InputClass { /** * @export * @enum {string} */ export enum KeyMappingTypeEnum { INNERJOIN = <any>"INNER JOIN", FULLOUTERJOIN = <any>"FULL OUTER JOIN", } } /** * * @export * @interface InputClassProperty */ export interface InputClassProperty { /** * * @type {string} * @memberof InputClassProperty */ datatype?: string; /** * * @type {string} * @memberof InputClassProperty */ description?: string; /** * * @type {string} * @memberof InputClassProperty */ name?: string; /** * * @type {InputParent} * @memberof InputClassProperty */ parentClass?: InputParent; } /** * * @export * @interface InputMapping */ export interface InputMapping { /** * * @type {InputMappingClassProperty} * @memberof InputMapping */ classProperty?: InputMappingClassProperty; /** * * @type {string} * @memberof InputMapping */ description?: string; /** * * @type {boolean} * @memberof InputMapping */ functionalMapping?: boolean; /** * * @type {boolean} * @memberof InputMapping */ keyMapping?: boolean; /** * * @type {MappingFunction} * @memberof InputMapping */ mappingFunction?: MappingFunction; /** * * @type {string} * @memberof InputMapping */ name?: string; /** * * @type {Array<InputMappingSchemaProperty>} * @memberof InputMapping */ schemaProperties?: Array<InputMappingSchemaProperty>; } /** * * @export * @interface InputMappingClassProperty */ export interface InputMappingClassProperty { /** * * @type {string} * @memberof InputMappingClassProperty */ name?: string; /** * * @type {InputParent} * @memberof InputMappingClassProperty */ parentClass?: InputParent; } /** * * @export * @interface InputMappingSchemaProperty */ export interface InputMappingSchemaProperty { /** * * @type {string} * @memberof InputMappingSchemaProperty */ name?: string; /** * * @type {string} * @memberof InputMappingSchemaProperty */ order?: string; /** * * @type {InputParent} * @memberof InputMappingSchemaProperty */ parentSchema?: InputParent; } /** * * @export * @interface InputParent */ export interface InputParent { /** * * @type {string} * @memberof InputParent */ name?: string; } /** * * @export * @interface InputPropertyRelation */ export interface InputPropertyRelation { /** * * @type {string} * @memberof InputPropertyRelation */ description?: string; /** * * @type {InputMappingClassProperty} * @memberof InputPropertyRelation */ endClassProperty?: InputMappingClassProperty; /** * * @type {string} * @memberof InputPropertyRelation */ name?: string; /** * * @type {string} * @memberof InputPropertyRelation */ relationType?: string; /** * * @type {InputMappingClassProperty} * @memberof InputPropertyRelation */ startClassProperty?: InputMappingClassProperty; } /** * * @export * @interface InputSchema */ export interface InputSchema { /** * * @type {string} * @memberof InputSchema */ description?: string; /** * * @type {string} * @memberof InputSchema */ name?: string; } /** * * @export * @interface InputSchemaProperty */ export interface InputSchemaProperty { /** * * @type {string} * @memberof InputSchemaProperty */ datatype?: string; /** * * @type {string} * @memberof InputSchemaProperty */ description?: string; /** * * @type {string} * @memberof InputSchemaProperty */ name?: string; /** * * @type {InputParent} * @memberof InputSchemaProperty */ parentSchema?: InputParent; } /** * * @export * @interface IotDataRegistry */ export interface IotDataRegistry { /** * * @type {string} * @memberof IotDataRegistry */ assetId?: string; /** * * @type {string} * @memberof IotDataRegistry */ aspectName?: string; } /** * * @export * @interface IotDataRegistryResponse */ export interface IotDataRegistryResponse { /** * * @type {string} * @memberof IotDataRegistryResponse */ aspectName?: string; /** * * @type {string} * @memberof IotDataRegistryResponse */ assetId?: string; /** * The category for this IoT Data Registry is always IOT * @type {string} * @memberof IotDataRegistryResponse */ category?: string; /** * * @type {string} * @memberof IotDataRegistryResponse */ createdDate?: string; /** * The dataTag is combination of assetId and aspectName, separated by _ * @type {string} * @memberof IotDataRegistryResponse */ dataTag?: string; /** * * @type {string} * @memberof IotDataRegistryResponse */ fileUploadStrategy?: IotDataRegistryResponse.FileUploadStrategyEnum; /** * * @type {string} * @memberof IotDataRegistryResponse */ updatedDate?: string; /** * * @type {string} * @memberof IotDataRegistryResponse */ registryId?: string; /** * The sourceName is always MindSphere. * @type {string} * @memberof IotDataRegistryResponse */ sourceName?: string; } /** * @export * @namespace IotDataRegistryResponse */ export namespace IotDataRegistryResponse { /** * @export * @enum {string} */ export enum FileUploadStrategyEnum { Append = <any>"append", Replace = <any>"replace", } } /** * * @export * @interface JobStatus */ export interface JobStatus { /** * Unique Ontology job ID. * @type {string} * @memberof JobStatus */ id?: string; /** * Status of ontology creation/updation job. - SUBMITTED: job has been created but creation/updation of ontology not yet started. - IN_PROGRESS: Ontology creation or updation started. - FAILED: Ontology creation or updation has failed. No data is available to be retrieved. - SUCCESS: Ontology creation or updation has been successfully finished. * @type {string} * @memberof JobStatus */ status?: JobStatus.StatusEnum; /** * Contains an message in case the job created. Possible messages: - The Request for Create Ontology. - The Request for Create Ontology using owl file upload. - The Request for Update Ontology. * @type {string} * @memberof JobStatus */ message?: string; /** * Start time of Ontology job created in UTC date format. * @type {string} * @memberof JobStatus */ createdDate?: string; /** * Job last modified time in UTC date format. The backend updates this time whenever the job status changes. * @type {string} * @memberof JobStatus */ updatedDate?: string; /** * ontologyResponse will contain either ontology id or ontology error based on job success or fail. * @type {any} * @memberof JobStatus */ ontologyResponse?: any; } /** * @export * @namespace JobStatus */ export namespace JobStatus { /** * @export * @enum {string} */ export enum StatusEnum { SUBMITTED = <any>"SUBMITTED", INPROGRESS = <any>"IN_PROGRESS", ERROR = <any>"ERROR", SUCCESS = <any>"SUCCESS", } } /** * * @export * @interface ListOfDataTypeDefinition */ export interface ListOfDataTypeDefinition { /** * * @type {Array<DataTypeDefinition>} * @memberof ListOfDataTypeDefinition */ dataTypes?: Array<DataTypeDefinition>; /** * * @type {TokenPage} * @memberof ListOfDataTypeDefinition */ page?: TokenPage; } /** * * @export * @interface ListOfIoTRegistryResponse */ export interface ListOfIoTRegistryResponse { /** * * @type {Array<IotDataRegistryResponse>} * @memberof ListOfIoTRegistryResponse */ iotDataRegistries?: Array<IotDataRegistryResponse>; /** * * @type {TokenPage} * @memberof ListOfIoTRegistryResponse */ page?: TokenPage; } /** * * @export * @interface ListOfJobIds */ export interface ListOfJobIds { /** * * @type {Array<SdiJobStatusResponse>} * @memberof ListOfJobIds */ ingestJobStatus?: Array<SdiJobStatusResponse>; /** * * @type {TokenPage} * @memberof ListOfJobIds */ page?: TokenPage; } /** * * @export * @interface ListOfPatterns */ export interface ListOfPatterns { /** * * @type {Array<Pattern>} * @memberof ListOfPatterns */ suggestPatterns?: Array<Pattern>; } /** * * @export * @interface ListOfRegistryResponse */ export interface ListOfRegistryResponse { /** * * @type {Array<DataRegistry>} * @memberof ListOfRegistryResponse */ dataRegistries?: Array<DataRegistry>; /** * * @type {TokenPage} * @memberof ListOfRegistryResponse */ page?: TokenPage; } /** * * @export * @interface ListOfSchemaProperties */ export interface ListOfSchemaProperties {} /** * * @export * @interface ListOfSchemaRegistry */ export interface ListOfSchemaRegistry { /** * * @type {Array<SDISchemaRegistry>} * @memberof ListOfSchemaRegistry */ schemas?: Array<SDISchemaRegistry>; /** * * @type {TokenPage} * @memberof ListOfSchemaRegistry */ page?: TokenPage; } /** * * @export * @interface MappingErrorSQLDetails */ export interface MappingErrorSQLDetails { /** * * @type {string} * @memberof MappingErrorSQLDetails */ field?: string; /** * * @type {string} * @memberof MappingErrorSQLDetails */ message?: string; } /** * * @export * @interface MappingFunction */ export interface MappingFunction { /** * * @type {string} * @memberof MappingFunction */ operator?: string; } /** * A descriptor for errors that are integral parts of resources. * @export * @interface MdspApiError */ export interface MdspApiError { /** * Unique error code. Every code is bound to one (parametrized) message. * @type {string} * @memberof MdspApiError */ code?: string; /** * Human readable error message in English. * @type {string} * @memberof MdspApiError */ message?: string; /** * In case an error message is parametrized, the parameter names and values are returned for, e.g., localization purposes. The parametrized error messages are defined at the operation error response descriptions in this API specification. Parameters are denoted by named placeholders '{\\<parameter name\\>}' in the message specifications. At runtime, returned message placeholders are substituted by actual parameter values. * @type {Array<any>} * @memberof MdspApiError */ messageParameters?: Array<any>; } /** * A descriptor for error responses. * @export * @interface MdspError */ export interface MdspError extends MdspApiError { /** * Logging correlation ID for debugging purposes. * @type {string} * @memberof MdspError */ logref?: string; } /** * * @export * @interface MdspErrors */ export interface MdspErrors { /** * * @type {Array<MdspError>} * @memberof MdspErrors */ errors?: Array<MdspError>; } /** * * @export * @interface MessageParameter */ export interface MessageParameter { /** * * @type {string} * @memberof MessageParameter */ name?: string; /** * * @type {any} * @memberof MessageParameter */ value?: any; } /** * * @export * @interface NativeQueryGetResponse */ export interface NativeQueryGetResponse { /** * * @type {string} * @memberof NativeQueryGetResponse */ createdDate?: string; /** * * @type {string} * @memberof NativeQueryGetResponse */ description?: string; /** * * @type {boolean} * @memberof NativeQueryGetResponse */ executable?: boolean; /** * * @type {string} * @memberof NativeQueryGetResponse */ id?: string; /** * * @type {boolean} * @memberof NativeQueryGetResponse */ isBusinessQuery?: boolean; /** * * @type {boolean} * @memberof NativeQueryGetResponse */ isDynamic?: boolean; /** * * @type {string} * @memberof NativeQueryGetResponse */ name?: string; /** * * @type {string} * @memberof NativeQueryGetResponse */ ontologyId?: string; /** * * @type {Array<MappingErrorSQLDetails>} * @memberof NativeQueryGetResponse */ pendingActions?: Array<MappingErrorSQLDetails>; /** * * @type {string} * @memberof NativeQueryGetResponse */ sqlStatement?: string; /** * * @type {string} * @memberof NativeQueryGetResponse */ updatedDate?: string; /** * * @type {Array<string>} * @memberof NativeQueryGetResponse */ lastTenExecutionJobIds?: Array<string>; } /** * * @export * @interface OntologyJob */ export interface OntologyJob { /** * Unique Ontology job ID. * @type {string} * @memberof OntologyJob */ id?: string; /** * Status of ontology creation/updation job. - SUBMITTED: job has been created but creation/updation of ontology not yet started. - IN_PROGRESS: Ontology creation or updation started. - FAILED: Ontology creation or updation has failed. No data is available to be retrieved. - SUCCESS: Ontology creation or updation has been successfully finished. * @type {string} * @memberof OntologyJob */ status?: OntologyJob.StatusEnum; /** * Contains an message in case the job created. Possible messages: - The Resuest for Create Ontology. - The Resuest for Create Ontology using owl file upload. - The Resuest for Update Ontology. * @type {string} * @memberof OntologyJob */ message?: string; /** * Start time of Ontology job created in UTC date format. * @type {string} * @memberof OntologyJob */ createdDate?: string; /** * Job last modified time in UTC date format. The backend updates this time whenever the job status changes. * @type {string} * @memberof OntologyJob */ updatedDate?: string; } /** * @export * @namespace OntologyJob */ export namespace OntologyJob { /** * @export * @enum {string} */ export enum StatusEnum { SUBMITTED = <any>"SUBMITTED", INPROGRESS = <any>"IN_PROGRESS", ERROR = <any>"ERROR", SUCCESS = <any>"SUCCESS", } } /** * * @export * @interface OntologyMetadata */ export interface OntologyMetadata { /** * * @type {string} * @memberof OntologyMetadata */ createdDate?: string; /** * Ontology description. * @type {string} * @memberof OntologyMetadata */ ontologyDescription?: string; /** * Ontology id. * @type {string} * @memberof OntologyMetadata */ id?: string; /** * Ontology name. * @type {string} * @memberof OntologyMetadata */ ontologyName?: string; /** * Ontology keyMappingType. * @type {string} * @memberof OntologyMetadata */ keyMappingType?: string; /** * * @type {string} * @memberof OntologyMetadata */ updatedDate?: string; } /** * * @export * @interface OntologyResponseData */ export interface OntologyResponseData { /** * * @type {string} * @memberof OntologyResponseData */ createdDate?: string; /** * Ontology description. * @type {string} * @memberof OntologyResponseData */ ontologyDescription?: string; /** * Ontology id. * @type {string} * @memberof OntologyResponseData */ id?: string; /** * Ontology name. * @type {string} * @memberof OntologyResponseData */ ontologyName?: string; /** * Ontology keyMappingType. * @type {string} * @memberof OntologyResponseData */ keyMappingType?: string; /** * * @type {string} * @memberof OntologyResponseData */ updatedDate?: string; /** * * @type {Array<InputClassProperty>} * @memberof OntologyResponseData */ classProperties?: Array<InputClassProperty>; /** * * @type {Array<InputClass>} * @memberof OntologyResponseData */ classes?: Array<InputClass>; /** * * @type {Array<InputMapping>} * @memberof OntologyResponseData */ mappings?: Array<InputMapping>; /** * * @type {Array<InputPropertyRelation>} * @memberof OntologyResponseData */ propertyRelations?: Array<InputPropertyRelation>; /** * * @type {Array<InputSchemaProperty>} * @memberof OntologyResponseData */ schemaProperties?: Array<InputSchemaProperty>; /** * * @type {Array<InputSchema>} * @memberof OntologyResponseData */ schemas?: Array<InputSchema>; } /** * * @export * @interface Parameters */ export interface Parameters { /** * * @type {string} * @memberof Parameters */ paramName: string; /** * * @type {string} * @memberof Parameters */ paramValue: string; } /** * * @export * @interface Pattern */ export interface Pattern { /** * * @type {string} * @memberof Pattern */ schema?: string; /** * * @type {Array<string>} * @memberof Pattern */ matches?: Array<string>; /** * * @type {boolean} * @memberof Pattern */ schemaValid?: boolean; } /** * * @export * @interface QueryObsoleteResult */ export interface QueryObsoleteResult { /** * * @type {Array<ApiFieldError>} * @memberof QueryObsoleteResult */ errors?: Array<ApiFieldError>; /** * * @type {Array<any>} * @memberof QueryObsoleteResult */ data?: Array<any>; } /** * If user creates query 'SELECT vehicle.vin, make.def FROM vehicle, make WHERE vehicle.make = make.id' returns results as array of json object contaning keys as 'vehicle.vin', 'make.def' and values matching according to criteria. * @export * @interface QueryResult */ export interface QueryResult { /** * Query result status. * @type {string} * @memberof QueryResult */ status?: string; /** * * @type {string} * @memberof QueryResult */ timestamp?: string; /** * * @type {Array<any>} * @memberof QueryResult */ data?: Array<any>; } /** * * @export * @interface ResponseAllDataQueryExecutionResponse */ export interface ResponseAllDataQueryExecutionResponse { /** * * @type {TokenPage} * @memberof ResponseAllDataQueryExecutionResponse */ page?: TokenPage; /** * * @type {Array<DataQueryExecutionResponse>} * @memberof ResponseAllDataQueryExecutionResponse */ jobs?: Array<DataQueryExecutionResponse>; } /** * * @export * @interface ResponseAllDataSQLQuery */ export interface ResponseAllDataSQLQuery { /** * * @type {TokenPage} * @memberof ResponseAllDataSQLQuery */ page?: TokenPage; /** * * @type {Array<GetAllSQLQueriesData>} * @memberof ResponseAllDataSQLQuery */ queries?: Array<GetAllSQLQueriesData>; } /** * * @export * @interface ResponseAllOntologies */ export interface ResponseAllOntologies { /** * * @type {Array<OntologyMetadata>} * @memberof ResponseAllOntologies */ ontologies?: Array<OntologyMetadata>; /** * * @type {TokenPage} * @memberof ResponseAllOntologies */ page?: TokenPage; } /** * * @export * @interface SDIIngestData */ export interface SDIIngestData { /** * * @type {string} * @memberof SDIIngestData */ dataTag?: string; /** * * @type {string} * @memberof SDIIngestData */ filePath?: string; /** * * @type {string} * @memberof SDIIngestData */ rootTag?: string; /** * * @type {string} * @memberof SDIIngestData */ sourceName?: string; } /** * * @export * @interface SDISchemaProperty */ export interface SDISchemaProperty { /** * * @type {string} * @memberof SDISchemaProperty */ dataType: string; /** * * @type {Array<string>} * @memberof SDISchemaProperty */ customTypes?: Array<string>; } /** * * @export * @interface SDISchemaRegistry */ export interface SDISchemaRegistry { /** * * @type {string} * @memberof SDISchemaRegistry */ createdDate?: string; /** * * @type {string} * @memberof SDISchemaRegistry */ id?: string; /** * * @type {string} * @memberof SDISchemaRegistry */ updatedDate?: string; /** * * @type {Array<string>} * @memberof SDISchemaRegistry */ originalFileNames?: Array<string>; /** * This is a loosely defined schema string containing property name, one or more data type for given property and list of regex patterns for a type. * @type {{ [key: string]: ListOfSchemaProperties; }} * @memberof SDISchemaRegistry */ schema?: { [key: string]: ListOfSchemaProperties }; /** * * @type {string} * @memberof SDISchemaRegistry */ schemaName?: string; /** * * @type {string} * @memberof SDISchemaRegistry */ registryId?: string; /** * * @type {string} * @memberof SDISchemaRegistry */ category?: string; } /** * * @export * @interface SchemaSearchObject */ export interface SchemaSearchObject { /** * * @type {string} * @memberof SchemaSearchObject */ dataTag?: string; /** * * @type {string} * @memberof SchemaSearchObject */ schemaName?: string; /** * * @type {string} * @memberof SchemaSearchObject */ category?: SchemaSearchObject.CategoryEnum; /** * * @type {string} * @memberof SchemaSearchObject */ aspectName?: string; /** * * @type {string} * @memberof SchemaSearchObject */ assetId?: string; /** * * @type {string} * @memberof SchemaSearchObject */ sourceName?: string; /** * metaDataTags can be defined while creating a data registry. * @type {Array<string>} * @memberof SchemaSearchObject */ metaDataTags?: Array<string>; } /** * @export * @namespace SchemaSearchObject */ export namespace SchemaSearchObject { /** * @export * @enum {string} */ export enum CategoryEnum { ENTERPRISE = <any>"ENTERPRISE", IOT = <any>"IOT", } } /** * * @export * @interface SchemaSearchRequest */ export interface SchemaSearchRequest { /** * * @type {Array<SchemaSearchObject>} * @memberof SchemaSearchRequest */ schemas?: Array<SchemaSearchObject>; } /** * * @export * @interface SdiFileUploadResponse */ export interface SdiFileUploadResponse { /** * * @type {string} * @memberof SdiFileUploadResponse */ filePath?: string; } /** * * @export * @interface SdiJobStatusResponse */ export interface SdiJobStatusResponse { /** * * @type {string} * @memberof SdiJobStatusResponse */ jobId?: string; /** * * @type {string} * @memberof SdiJobStatusResponse */ startedDate?: string; /** * * @type {string} * @memberof SdiJobStatusResponse */ finishedDate?: string; /** * * @type {string} * @memberof SdiJobStatusResponse */ message?: string; /** * * @type {string} * @memberof SdiJobStatusResponse */ fileName?: string; /** * * @type {string} * @memberof SdiJobStatusResponse */ status?: SdiJobStatusResponse.StatusEnum; } /** * @export * @namespace SdiJobStatusResponse */ export namespace SdiJobStatusResponse { /** * @export * @enum {string} */ export enum StatusEnum { INPROGRESS = <any>"IN_PROGRESS", ERROR = <any>"ERROR", STARTED = <any>"STARTED", FINISHED = <any>"FINISHED", } } /** * * @export * @interface TokenPage */ export interface TokenPage { /** * Opaque token to next page. Can be used in query paramter 'pageToken' to request next page. The property is only present in case there is a next page. * @type {string} * @memberof TokenPage */ nextToken?: string; } /** * * @export * @interface UpdateDataLakeRequest */ export interface UpdateDataLakeRequest { /** * * @type {string} * @memberof UpdateDataLakeRequest */ basePath?: string; } /** * * @export * @interface UpdateDataRegistryRequest */ export interface UpdateDataRegistryRequest { /** * * @type {string} * @memberof UpdateDataRegistryRequest */ defaultRootTag?: string; /** * * @type {string} * @memberof UpdateDataRegistryRequest */ filePattern?: string; /** * * @type {string} * @memberof UpdateDataRegistryRequest */ fileUploadStrategy?: UpdateDataRegistryRequest.FileUploadStrategyEnum; /** * * @type {Array<string>} * @memberof UpdateDataRegistryRequest */ metaDataTags?: Array<string>; /** * * @type {Array<string>} * @memberof UpdateDataRegistryRequest */ xmlProcessRules?: Array<string>; /** * This property can be changed to true after creating the initial schema to reuse the schema for the newly ingested data * @type {boolean} * @memberof UpdateDataRegistryRequest */ schemaFrozen?: boolean; } /** * @export * @namespace UpdateDataRegistryRequest */ export namespace UpdateDataRegistryRequest { /** * @export * @enum {string} */ export enum FileUploadStrategyEnum { Append = <any>"append", Replace = <any>"replace", } } /** * !fix: Manually created type for Suggest Pattern Request * * @export * @interface SuggestPatternsRequest */ export interface SuggestPatternsRequest { sampleValues: Array<string>; testValues: Array<string>; } }
the_stack
import * as React from 'react' import classnames from 'classnames/bind' import { User, UserAdminView } from 'src/global_types' import { adminChangePassword, adminSetUserFlags, adminDeleteUser, addHeadlessUser, deleteGlobalAuthScheme, deleteTotpForUser, adminCreateLocalUser, adminInviteUser } from 'src/services' import AuthContext from 'src/auth_context' import Button from 'src/components/button' import ChallengeModalForm from 'src/components/challenge_modal_form' import Checkbox from 'src/components/checkbox' import Input from 'src/components/input' import Modal from 'src/components/modal' import Form from 'src/components/form' import ModalForm from 'src/components/modal_form' import { InputWithCopyButton } from 'src/components/text_copiers' import { useForm, useFormField } from 'src/helpers' const cx = classnames.bind(require('./stylesheet')) export const ResetPasswordModal = (props: { user: User, onRequestClose: () => void, }) => { const tempPassword = useFormField<string>("") const formComponentProps = useForm({ fields: [tempPassword], onSuccess: () => props.onRequestClose(), handleSubmit: () => adminChangePassword({ userSlug: props.user.slug, newPassword: tempPassword.value, }), }) return ( <ModalForm title="Set Temporary Password" submitText="Update" onRequestClose={props.onRequestClose} {...formComponentProps}> <Input label="New Temporary Password" {...tempPassword} /> </ModalForm> ) } export const AddHeadlessUserModal = (props: { onRequestClose: () => void, }) => { const headlessName = useFormField<string>("") const contactEmail = useFormField<string>("") const formComponentProps = useForm({ fields: [headlessName, contactEmail], onSuccess: () => props.onRequestClose(), handleSubmit: () => { if (headlessName.value.length == 0) { return new Promise((resolve, reject) => reject(Error("Headless users must be given a name"))) } return addHeadlessUser({ firstName: 'Headless', lastName: headlessName.value, email: contactEmail.value, }) }, }) return ( <ModalForm title="Create New Headless User" submitText="Create" onRequestClose={props.onRequestClose} {...formComponentProps}> <Input label="Headless name" {...headlessName} /> <Input type="email" label="Contact Email" {...contactEmail} /> </ModalForm> ) } export const AddUserModal = (props: { onRequestClose: () => void, }) => { const firstName = useFormField<string>("") const lastName = useFormField<string>("") const contactEmail = useFormField<string>("") const [username, setUsername] = React.useState<string>("") const [password, setPassword] = React.useState<string>("") const [isDisabled, setDisabled] = React.useState<boolean>(false) const formComponentProps = useForm({ fields: [firstName, lastName, contactEmail], handleSubmit: () => { if (firstName.value.length == 0) { return new Promise((_resolve, reject) => reject(Error("Users should have at least a first name"))) } if (contactEmail.value.length == 0) { return new Promise((_resolve, reject) => reject(Error("Users must have an email address"))) } // TODO: this should create the user, then update the form with the new user/password combo // to share. const runSubmit = async () => { const result = await adminCreateLocalUser({ firstName: firstName.value, lastName: lastName.value, email: contactEmail.value, }) setUsername(contactEmail.value) setPassword(result.temporaryPassword) setDisabled(true) // lock the form -- we don't need to allow submits at this time. } return runSubmit() }, }) return ( <Modal title="Create New User" onRequestClose={props.onRequestClose}> <Form {...formComponentProps} loading={isDisabled} submitText={isDisabled ? undefined : "Submit"} > <Input label="First Name" {...firstName} disabled={isDisabled} /> <Input label="Last Name" {...lastName} disabled={isDisabled} /> <Input label="Email" {...contactEmail} disabled={isDisabled} /> </Form> {isDisabled && (<> <div className={cx('success-area')}> <p>Below is the new user's initial login credentials:</p> <InputWithCopyButton label="Username" value={username} /> <InputWithCopyButton label="Password" value={password} /> <Button className={cx('success-close-button')} primary onClick={props.onRequestClose} >Close</Button> </div> </>) } </Modal> ) } export const UpdateUserFlagsModal = (props: { user: UserAdminView, onRequestClose: () => void, }) => { const fullContext = React.useContext(AuthContext) const adminSlug = fullContext.user ? fullContext.user.slug : "" const isAdmin = useFormField(props.user.admin) const isDisabled = useFormField(props.user.disabled) const formComponentProps = useForm({ fields: [isAdmin, isDisabled], onSuccess: () => props.onRequestClose(), handleSubmit: () => { return adminSetUserFlags({ userSlug: props.user.slug, disabled: isDisabled.value, admin: isAdmin.value }) } }) const badAdmin = { disabled: true, title: "Admins cannot alter this flag on themselves" } const adminIsTargetUser = adminSlug === props.user.slug const isHeadlessUser = props.user.headless const canAlterDisabled = adminIsTargetUser ? badAdmin : {} const canAlterAdmin = () => { if (adminIsTargetUser) { return badAdmin } if (isHeadlessUser) { return { disabled: true, title: "Headless users cannot be admins" } } return {} } const mergedAdminProps = { ...isAdmin, ...canAlterAdmin() } const mergedDisabledProps = { ...isDisabled, ...canAlterDisabled } return <ModalForm title="Set User Flags" submitText="Update" onRequestClose={props.onRequestClose} {...formComponentProps}> <em className={cx('warning')}>Updating these values will log out the user</em> <Checkbox label="Admin" {...mergedAdminProps} /> <Checkbox label="Disabled" {...mergedDisabledProps} /> </ModalForm> } export const DeleteUserModal = (props: { user: UserAdminView, onRequestClose: () => void, }) => <ChallengeModalForm modalTitle="Delete User" warningText="This will remove the user from the system. All user information will be lost." submitText="Delete" challengeText={props.user.slug} handleSubmit={() => adminDeleteUser({ userSlug: props.user.slug })} onRequestClose={props.onRequestClose} /> export const DeleteGlobalAuthSchemeModal = (props: { schemeCode: string, uniqueUsers: number, onRequestClose: () => void, }) => <ChallengeModalForm modalTitle="Remove Users from Authentication Scheme" warningText={`This will unlink/remove this authentication scheme from all users.${ props.uniqueUsers == 0 ? "" : ` Note that this will effectively disable ${props.uniqueUsers} accounts.` }`} submitText="Remove All" challengeText={props.schemeCode} handleSubmit={() => deleteGlobalAuthScheme({ schemeName: props.schemeCode })} onRequestClose={props.onRequestClose} /> export const RecoverAccountModal = (props: { recoveryCode: string onRequestClose: () => void, }) => { const url = `${window.location.origin}/web/auth/recovery/login?code=${props.recoveryCode}` return <Modal title="Recovery URL" onRequestClose={props.onRequestClose}> <div className={cx('recovery-code-modal')}> <p> Below is the recovery URL. Provide this to the user, and they will be able to log in without the need to authenticate. </p> <InputWithCopyButton label="Recovery URL" value={url} /> <Button primary onClick={() => props.onRequestClose()}>Close</Button> </div> </Modal> } export const InviteUserModal = (props: { onRequestClose: () => void, }) => { const firstName = useFormField<string>("") const lastName = useFormField<string>("") const contactEmail = useFormField<string>("") const [url, setUrl] = React.useState<string>("") const [isDisabled, setDisabled] = React.useState<boolean>(false) const formComponentProps = useForm({ fields: [firstName, lastName, contactEmail], handleSubmit: () => { if (firstName.value.length == 0) { return new Promise((_resolve, reject) => reject(Error("Users should have at least a first name"))) } if (contactEmail.value.length == 0) { return new Promise((_resolve, reject) => reject(Error("Users must have an email address"))) } // TODO: this should create the user, then update the form with the new user/password combo // to share. const runSubmit = async () => { const result = await adminInviteUser({ firstName: firstName.value, lastName: lastName.value, email: contactEmail.value, }) const url = `${window.location.origin}/web/auth/recovery/login?code=${result.code}` setUrl(url) setDisabled(true) // lock the form -- we don't need to allow submits at this time. } return runSubmit() }, }) return ( <Modal title="Create New User" onRequestClose={props.onRequestClose}> <Form {...formComponentProps} loading={isDisabled} submitText={isDisabled ? undefined : "Submit"} > <Input label="First Name" {...firstName} disabled={isDisabled} /> <Input label="Last Name" {...lastName} disabled={isDisabled} /> <Input label="Email" {...contactEmail} disabled={isDisabled} /> </Form> {isDisabled && (<> <div className={cx('success-area')}> <p>The user can login with the link below to configure their account:</p> <InputWithCopyButton label="Recovery Code" value={url} /> <Button className={cx('success-close-button')} primary onClick={props.onRequestClose} >Close</Button> </div> </>) } </Modal> ) } export const RemoveTotpModal = (props: { user: UserAdminView, onRequestClose: () => void, }) => { const formComponentProps = useForm({ fields: [], onSuccess: () => props.onRequestClose(), handleSubmit: () => deleteTotpForUser({userSlug: props.user.slug}), }) return <ModalForm title="Disable Multi-Factor Authentication" submitText="Continue" onRequestClose={props.onRequestClose} {...formComponentProps}> <em className={cx('warning')}> Multi-factor Authentication provides an extra layer of security for this user. Removing this factor should only be done if the user has lost the device or the mechansim to authenticate. Are you sure you want to continue? </em> </ModalForm> }
the_stack
import { DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { EditorConfiguration, IEditorConstructionOptions } from 'vs/editor/browser/config/editorConfiguration'; import { IActiveCodeEditor, ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService'; import { View } from 'vs/editor/browser/view'; import { CodeEditorWidget, ICodeEditorWidgetOptions } from 'vs/editor/browser/widget/codeEditorWidget'; import * as editorOptions from 'vs/editor/common/config/editorOptions'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ILanguageService } from 'vs/editor/common/languages/language'; import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry'; import { ITextBufferFactory, ITextModel } from 'vs/editor/common/model'; import { IEditorWorkerService } from 'vs/editor/common/services/editorWorker'; import { ILanguageFeatureDebounceService, LanguageFeatureDebounceService } from 'vs/editor/common/services/languageFeatureDebounce'; import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures'; import { LanguageFeaturesService } from 'vs/editor/common/services/languageFeaturesService'; import { LanguageService } from 'vs/editor/common/services/languageService'; import { IModelService } from 'vs/editor/common/services/model'; import { ModelService } from 'vs/editor/common/services/modelService'; import { ITextResourcePropertiesService } from 'vs/editor/common/services/textResourceConfiguration'; import { ViewModel } from 'vs/editor/common/viewModel/viewModelImpl'; import { TestConfiguration } from 'vs/editor/test/browser/config/testConfiguration'; import { TestCodeEditorService, TestCommandService } from 'vs/editor/test/browser/editorTestServices'; import { TestLanguageConfigurationService } from 'vs/editor/test/common/modes/testLanguageConfigurationService'; import { TestEditorWorkerService } from 'vs/editor/test/common/services/testEditorWorkerService'; import { TestTextResourcePropertiesService } from 'vs/editor/test/common/services/testTextResourcePropertiesService'; import { instantiateTextModel } from 'vs/editor/test/common/testTextModel'; import { IAccessibilityService } from 'vs/platform/accessibility/common/accessibility'; import { TestAccessibilityService } from 'vs/platform/accessibility/test/common/testAccessibilityService'; import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService'; import { TestClipboardService } from 'vs/platform/clipboard/test/common/testClipboardService'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { IContextKeyService, IContextKeyServiceTarget } from 'vs/platform/contextkey/common/contextkey'; import { IDialogService } from 'vs/platform/dialogs/common/dialogs'; import { TestDialogService } from 'vs/platform/dialogs/test/common/testDialogService'; import { SyncDescriptor } from 'vs/platform/instantiation/common/descriptors'; import { BrandedService, IInstantiationService, ServiceIdentifier } from 'vs/platform/instantiation/common/instantiation'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { MockContextKeyService } from 'vs/platform/keybinding/test/common/mockKeybindingService'; import { ILogService, NullLogService } from 'vs/platform/log/common/log'; import { INotificationService } from 'vs/platform/notification/common/notification'; import { TestNotificationService } from 'vs/platform/notification/test/common/testNotificationService'; import { IOpenerService, NullOpenerService } from 'vs/platform/opener/common/opener'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { NullTelemetryServiceShape } from 'vs/platform/telemetry/common/telemetryUtils'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { TestThemeService } from 'vs/platform/theme/test/common/testThemeService'; import { IUndoRedoService } from 'vs/platform/undoRedo/common/undoRedo'; import { UndoRedoService } from 'vs/platform/undoRedo/common/undoRedoService'; export interface ITestCodeEditor extends IActiveCodeEditor { getViewModel(): ViewModel | undefined; registerAndInstantiateContribution<T extends IEditorContribution, Services extends BrandedService[]>(id: string, ctor: new (editor: ICodeEditor, ...services: Services) => T): T; registerDisposable(disposable: IDisposable): void; } export class TestCodeEditor extends CodeEditorWidget implements ICodeEditor { //#region testing overrides protected override _createConfiguration(isSimpleWidget: boolean, options: Readonly<IEditorConstructionOptions>): EditorConfiguration { return new TestConfiguration(options); } protected override _createView(viewModel: ViewModel): [View, boolean] { // Never create a view return [null! as View, false]; } private _hasTextFocus = false; public setHasTextFocus(hasTextFocus: boolean): void { this._hasTextFocus = hasTextFocus; } public override hasTextFocus(): boolean { return this._hasTextFocus; } //#endregion //#region Testing utils public getViewModel(): ViewModel | undefined { return this._modelData ? this._modelData.viewModel : undefined; } public registerAndInstantiateContribution<T extends IEditorContribution>(id: string, ctor: new (editor: ICodeEditor, ...services: BrandedService[]) => T): T { const r: T = this._instantiationService.createInstance(ctor, this); this._contributions[id] = r; return r; } public registerDisposable(disposable: IDisposable): void { this._register(disposable); } } class TestEditorDomElement { parentElement: IContextKeyServiceTarget | null = null; setAttribute(attr: string, value: string): void { } removeAttribute(attr: string): void { } hasAttribute(attr: string): boolean { return false; } getAttribute(attr: string): string | undefined { return undefined; } addEventListener(event: string): void { } removeEventListener(event: string): void { } } export interface TestCodeEditorCreationOptions extends editorOptions.IEditorOptions { /** * If the editor has text focus. * Defaults to true. */ hasTextFocus?: boolean; } export interface TestCodeEditorInstantiationOptions extends TestCodeEditorCreationOptions { /** * Services to use. */ serviceCollection?: ServiceCollection; } export function withTestCodeEditor(text: ITextModel | string | string[] | ITextBufferFactory, options: TestCodeEditorInstantiationOptions, callback: (editor: ITestCodeEditor, viewModel: ViewModel, instantiationService: TestInstantiationService) => void): void { return _withTestCodeEditor(text, options, callback); } export async function withAsyncTestCodeEditor(text: ITextModel | string | string[] | ITextBufferFactory, options: TestCodeEditorInstantiationOptions, callback: (editor: ITestCodeEditor, viewModel: ViewModel, instantiationService: TestInstantiationService) => Promise<void>): Promise<void> { return _withTestCodeEditor(text, options, callback); } function isTextModel(arg: ITextModel | string | string[] | ITextBufferFactory): arg is ITextModel { return Boolean(arg && (arg as ITextModel).uri); } function _withTestCodeEditor(arg: ITextModel | string | string[] | ITextBufferFactory, options: TestCodeEditorInstantiationOptions, callback: (editor: ITestCodeEditor, viewModel: ViewModel, instantiationService: TestInstantiationService) => void): void; function _withTestCodeEditor(arg: ITextModel | string | string[] | ITextBufferFactory, options: TestCodeEditorInstantiationOptions, callback: (editor: ITestCodeEditor, viewModel: ViewModel, instantiationService: TestInstantiationService) => Promise<void>): Promise<void>; function _withTestCodeEditor(arg: ITextModel | string | string[] | ITextBufferFactory, options: TestCodeEditorInstantiationOptions, callback: (editor: ITestCodeEditor, viewModel: ViewModel, instantiationService: TestInstantiationService) => Promise<void> | void): Promise<void> | void { const disposables = new DisposableStore(); const instantiationService = createCodeEditorServices(disposables, options.serviceCollection); delete options.serviceCollection; // create a model if necessary let model: ITextModel; if (isTextModel(arg)) { model = arg; } else { model = disposables.add(instantiateTextModel(instantiationService, Array.isArray(arg) ? arg.join('\n') : arg)); } const editor = disposables.add(instantiateTestCodeEditor(instantiationService, model, options)); const viewModel = editor.getViewModel()!; viewModel.setHasFocus(true); const result = callback(<ITestCodeEditor>editor, editor.getViewModel()!, instantiationService); if (result) { return result.then(() => disposables.dispose()); } disposables.dispose(); } export function createCodeEditorServices(disposables: DisposableStore, services: ServiceCollection = new ServiceCollection()): TestInstantiationService { const serviceIdentifiers: ServiceIdentifier<any>[] = []; const define = <T>(id: ServiceIdentifier<T>, ctor: new (...args: any[]) => T) => { if (!services.has(id)) { services.set(id, new SyncDescriptor(ctor)); } serviceIdentifiers.push(id); }; const defineInstance = <T>(id: ServiceIdentifier<T>, instance: T) => { if (!services.has(id)) { services.set(id, instance); } serviceIdentifiers.push(id); }; define(IAccessibilityService, TestAccessibilityService); define(IClipboardService, TestClipboardService); define(IEditorWorkerService, TestEditorWorkerService); defineInstance(IOpenerService, NullOpenerService); define(INotificationService, TestNotificationService); define(IDialogService, TestDialogService); define(IUndoRedoService, UndoRedoService); define(ILanguageService, LanguageService); define(ILanguageConfigurationService, TestLanguageConfigurationService); define(IConfigurationService, TestConfigurationService); define(ITextResourcePropertiesService, TestTextResourcePropertiesService); define(IThemeService, TestThemeService); define(ILogService, NullLogService); define(IModelService, ModelService); define(ICodeEditorService, TestCodeEditorService); define(IContextKeyService, MockContextKeyService); define(ICommandService, TestCommandService); define(ITelemetryService, NullTelemetryServiceShape); define(ILanguageFeatureDebounceService, LanguageFeatureDebounceService); define(ILanguageFeaturesService, LanguageFeaturesService); const instantiationService = new TestInstantiationService(services, true); disposables.add(toDisposable(() => { for (const id of serviceIdentifiers) { const instanceOrDescriptor = services.get(id); if (typeof instanceOrDescriptor.dispose === 'function') { instanceOrDescriptor.dispose(); } } })); return instantiationService; } export function createTestCodeEditor(model: ITextModel | undefined, options: TestCodeEditorInstantiationOptions = {}): ITestCodeEditor { const disposables = new DisposableStore(); const instantiationService = createCodeEditorServices(disposables, options.serviceCollection); delete options.serviceCollection; const editor = instantiateTestCodeEditor(instantiationService, model || null, options); editor.registerDisposable(disposables); return editor; } export function instantiateTestCodeEditor(instantiationService: IInstantiationService, model: ITextModel | null, options: TestCodeEditorCreationOptions = {}): ITestCodeEditor { const codeEditorWidgetOptions: ICodeEditorWidgetOptions = { contributions: [] }; const editor = instantiationService.createInstance( TestCodeEditor, <HTMLElement><any>new TestEditorDomElement(), options, codeEditorWidgetOptions ); if (typeof options.hasTextFocus === 'undefined') { options.hasTextFocus = true; } editor.setHasTextFocus(options.hasTextFocus); editor.setModel(model); const viewModel = editor.getViewModel(); viewModel?.setHasFocus(options.hasTextFocus); return <ITestCodeEditor>editor; }
the_stack
import {BufferGeometry, DoubleSide, Float32BufferAttribute, Material, MeshPhongMaterial, NearestFilter, RGBFormat, Texture, Uint32BufferAttribute} from 'three'; import {MapNodeGeometry} from '../geometries/MapNodeGeometry'; import {MapView} from '../MapView'; import {Martini} from './Martini'; import {MapHeightNode} from './MapHeightNode'; import {MapNode} from './MapNode.js'; import {CanvasUtils} from '../utils/CanvasUtils'; /** * Represents a height map tile node using the RTIN method from the paper "Right Triangulated Irregular Networks". * * Based off the library https://github.com/mapbox/martini (Mapbox's Awesome Right-Triangulated Irregular Networks, Improved) * * @param parentNode -The parent node of this node. * @param mapView - Map view object where this node is placed. * @param location - Position in the node tree relative to the parent. * @param level - Zoom level in the tile tree of the node. * @param x - X position of the node in the tile tree. * @param y - Y position of the node in the tile tree. * @param material -Material used to render this height node. * @param geometry - Geometry used to render this height node. */ export class MapMartiniHeightNode extends MapHeightNode { /** * Geometry size to be used for each martini height node. */ public static geometrySize: number = 16; /** * Empty texture used as a placeholder for missing textures. */ public static emptyTexture: Texture = new Texture(); /** * Base geometry appied before any custom geometru is used. */ public static geometry = new MapNodeGeometry(1, 1, 1, 1); /** * Elevation decoder configuration. * * Indicates how the pixels should be unpacked and transformed into height data. */ public elevationDecoder: any = { rScaler: 256, gScaler: 1, bScaler: 1 / 256, offset: -32768 }; /** * Original tile size of the images retrieved from the height provider. */ public static tileSize: number = 256; /** * Exageration (scale) of the terrain height. */ public exageration = 1.0; public meshMaxError: number | Function = 10; public material: MeshPhongMaterial public constructor(parentNode: MapHeightNode = null, mapView: MapView = null, location: number = MapNode.root, level: number = 0, x: number = 0, y: number = 0, {elevationDecoder = null, meshMaxError = 10, exageration = 1} = {}) { super(parentNode, mapView, location, level, x, y, MapMartiniHeightNode.geometry, MapMartiniHeightNode.prepareMaterial(new MeshPhongMaterial({ map: MapMartiniHeightNode.emptyTexture, color: 0xFFFFFF, side: DoubleSide }), level, exageration)); if (elevationDecoder) { this.elevationDecoder = elevationDecoder; } this.meshMaxError = meshMaxError; this.exageration = exageration; this.frustumCulled = false; } public static prepareMaterial(material: Material, level: number, exageration: number = 1.0): any { material.userData = { heightMap: {value: MapMartiniHeightNode.emptyTexture}, drawNormals: {value: 0}, drawBlack: {value: 0}, zoomlevel: {value: level}, computeNormals: {value: 1}, drawTexture: {value: 1} }; material.onBeforeCompile = (shader) => { // Pass uniforms from userData to the for (let i in material.userData) { shader.uniforms[i] = material.userData[i]; } // Vertex variables shader.vertexShader = ` uniform bool computeNormals; uniform float zoomlevel; uniform sampler2D heightMap; ` + shader.vertexShader; shader.fragmentShader = ` uniform bool drawNormals; uniform bool drawTexture; uniform bool drawBlack; ` + shader.fragmentShader; // Vertex depth logic shader.fragmentShader = shader.fragmentShader.replace('#include <dithering_fragment>', ` if(drawBlack) { gl_FragColor = vec4( 0.0,0.0,0.0, 1.0 ); } else if(drawNormals) { gl_FragColor = vec4( ( 0.5 * vNormal + 0.5 ), 1.0 ); } else if (!drawTexture) { gl_FragColor = vec4( 0.0,0.0,0.0, 0.0 ); }` ); shader.vertexShader = shader.vertexShader.replace('#include <fog_vertex>', ` #include <fog_vertex> // queried pixels: // +-----------+ // | | | | // | a | b | c | // | | | | // +-----------+ // | | | | // | d | e | f | // | | | | // +-----------+ // | | | | // | g | h | i | // | | | | // +-----------+ if (computeNormals) { float e = getElevation(vUv, 0.0); ivec2 size = textureSize(heightMap, 0); float offset = 1.0 / float(size.x); float a = getElevation(vUv + vec2(-offset, -offset), 0.0); float b = getElevation(vUv + vec2(0, -offset), 0.0); float c = getElevation(vUv + vec2(offset, -offset), 0.0); float d = getElevation(vUv + vec2(-offset, 0), 0.0); float f = getElevation(vUv + vec2(offset, 0), 0.0); float g = getElevation(vUv + vec2(-offset, offset), 0.0); float h = getElevation(vUv + vec2(0, offset), 0.0); float i = getElevation(vUv + vec2(offset,offset), 0.0); float normalLength = 500.0 / zoomlevel; vec3 v0 = vec3(0.0, 0.0, 0.0); vec3 v1 = vec3(0.0, normalLength, 0.0); vec3 v2 = vec3(normalLength, 0.0, 0.0); v0.z = (e + d + g + h) / 4.0; v1.z = (e+ b + a + d) / 4.0; v2.z = (e+ h + i + f) / 4.0; vNormal = (normalize(cross(v2 - v0, v1 - v0))).rbg; } ` ); }; return material; } public static getTerrain(imageData: Uint8ClampedArray, tileSize: number, elevation: any): Float32Array { const {rScaler, bScaler, gScaler, offset} = elevation; const gridSize = tileSize + 1; // From Martini demo // https://observablehq.com/@mourner/martin-real-time-rtin-terrain-mesh const terrain = new Float32Array(gridSize * gridSize); // Decode terrain values for (let i = 0, y = 0; y < tileSize; y++) { for (let x = 0; x < tileSize; x++, i++) { const k = i * 4; const r = imageData[k + 0]; const g = imageData[k + 1]; const b = imageData[k + 2]; terrain[i + y] = r * rScaler + g * gScaler + b * bScaler + offset; } } // Backfill bottom border for (let i = gridSize * (gridSize - 1), x = 0; x < gridSize - 1; x++, i++) { terrain[i] = terrain[i - gridSize]; } // Backfill right border for (let i = gridSize - 1, y = 0; y < gridSize; y++, i += gridSize) { terrain[i] = terrain[i - 1]; } return terrain; } /** * Get the attributes that compose the mesh. * * @param vertices - Vertices. * @param terrain - Terrain * @param tileSize - Size of each tile. * @param bounds - Array with the bound of the map. * @param exageration - Vertical exageration of the map scale. * @returns The position and UV coordinates of the mesh. */ public static getMeshAttributes(vertices: number[], terrain: Float32Array, tileSize: number, bounds: number[], exageration: number): {position: {value: Float32Array, size: number}, uv: {value: Float32Array, size: number}} // NORMAL: {}, - optional, but creates the high poly look with lighting} { const gridSize = tileSize + 1; const numOfVerticies = vertices.length / 2; // vec3. x, y in pixels, z in meters const positions = new Float32Array(numOfVerticies * 3); // vec2. 1 to 1 relationship with position. represents the uv on the texture image. 0,0 to 1,1. const texCoords = new Float32Array(numOfVerticies * 2); const [minX, minY, maxX, maxY] = bounds || [0, 0, tileSize, tileSize]; const xScale = (maxX - minX) / tileSize; const yScale = (maxY - minY) / tileSize; for (let i = 0; i < numOfVerticies; i++) { const x = vertices[i * 2]; const y = vertices[i * 2 + 1]; const pixelIdx = y * gridSize + x; positions[3 * i + 0] = x * xScale + minX; positions[3 * i + 1] = -terrain[pixelIdx] * exageration; positions[3 * i + 2] = -y * yScale + maxY; texCoords[2 * i + 0] = x / tileSize; texCoords[2 * i + 1] = y / tileSize; } return { position: {value: positions, size: 3}, uv: {value: texCoords, size: 2} }; } /** * Process the height texture received from the tile data provider. * * @param image - Image element received by the tile provider. */ public async onHeightImage(image: HTMLImageElement): Promise<void> { const tileSize = image.width; const gridSize = tileSize + 1; var canvas = CanvasUtils.createOffscreenCanvas(tileSize, tileSize); var context = canvas.getContext('2d'); context.imageSmoothingEnabled = false; context.drawImage(image, 0, 0, tileSize, tileSize, 0, 0, canvas.width, canvas.height); var imageData = context.getImageData(0, 0, canvas.width, canvas.height); var data = imageData.data; const terrain = MapMartiniHeightNode.getTerrain(data, tileSize, this.elevationDecoder); const martini = new Martini(gridSize); const tile = martini.createTile(terrain); const {vertices, triangles} = tile.getMesh(typeof this.meshMaxError === 'function' ? this.meshMaxError(this.level) : this.meshMaxError); const attributes = MapMartiniHeightNode.getMeshAttributes(vertices, terrain, tileSize, [-0.5, -0.5, 0.5, 0.5], this.exageration); this.geometry = new BufferGeometry(); this.geometry.setIndex(new Uint32BufferAttribute(triangles, 1)); this.geometry.setAttribute('position', new Float32BufferAttribute( attributes.position.value, attributes.position.size)); this.geometry.setAttribute('uv', new Float32BufferAttribute( attributes.uv.value, attributes.uv.size)); this.geometry.rotateX(Math.PI); var texture = new Texture(image); texture.generateMipmaps = false; texture.format = RGBFormat; texture.magFilter = NearestFilter; texture.minFilter = NearestFilter; texture.needsUpdate = true; this.material.userData.heightMap.value = texture; } /** * Load height texture from the server and create a geometry to match it. */ public loadHeightGeometry(): Promise<any> { if (this.mapView.heightProvider === null) { throw new Error('GeoThree: MapView.heightProvider provider is null.'); } return this.mapView.heightProvider.fetchTile(this.level, this.x, this.y).then(async(image) => { this.onHeightImage(image); }).finally(() => { this.heightLoaded = true; this.nodeReady(); }); } }
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; /** * <p></p> */ export interface AbortEnvironmentUpdateMessage { /** * <p>This specifies the ID of the environment with the in-progress update that you want to * cancel.</p> */ EnvironmentId?: string; /** * <p>This specifies the name of the environment with the in-progress update that you want to * cancel.</p> */ EnvironmentName?: string; } export namespace AbortEnvironmentUpdateMessage { /** * @internal */ export const filterSensitiveLog = (obj: AbortEnvironmentUpdateMessage): any => ({ ...obj, }); } /** * <p>The specified account does not have sufficient privileges for one or more AWS * services.</p> */ export interface InsufficientPrivilegesException extends __SmithyException, $MetadataBearer { name: "InsufficientPrivilegesException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace InsufficientPrivilegesException { /** * @internal */ export const filterSensitiveLog = (obj: InsufficientPrivilegesException): any => ({ ...obj, }); } export type ActionHistoryStatus = "Completed" | "Failed" | "Unknown"; export type ActionStatus = "Pending" | "Running" | "Scheduled" | "Unknown"; export type ActionType = "InstanceRefresh" | "PlatformUpdate" | "Unknown"; /** * <p>A lifecycle rule that deletes application versions after the specified number of * days.</p> */ export interface MaxAgeRule { /** * <p>Specify <code>true</code> to apply the rule, or <code>false</code> to disable * it.</p> */ Enabled: boolean | undefined; /** * <p>Specify the number of days to retain an application versions.</p> */ MaxAgeInDays?: number; /** * <p>Set to <code>true</code> to delete a version's source bundle from Amazon S3 when * Elastic Beanstalk deletes the application version.</p> */ DeleteSourceFromS3?: boolean; } export namespace MaxAgeRule { /** * @internal */ export const filterSensitiveLog = (obj: MaxAgeRule): any => ({ ...obj, }); } /** * <p>A lifecycle rule that deletes the oldest application version when the maximum count is * exceeded.</p> */ export interface MaxCountRule { /** * <p>Specify <code>true</code> to apply the rule, or <code>false</code> to disable * it.</p> */ Enabled: boolean | undefined; /** * <p>Specify the maximum number of application versions to retain.</p> */ MaxCount?: number; /** * <p>Set to <code>true</code> to delete a version's source bundle from Amazon S3 when * Elastic Beanstalk deletes the application version.</p> */ DeleteSourceFromS3?: boolean; } export namespace MaxCountRule { /** * @internal */ export const filterSensitiveLog = (obj: MaxCountRule): any => ({ ...obj, }); } /** * <p>The application version lifecycle settings for an application. Defines the rules that * Elastic Beanstalk applies to an application's versions in order to avoid hitting the * per-region limit for application versions.</p> * <p>When Elastic Beanstalk deletes an application version from its database, you can no * longer deploy that version to an environment. The source bundle remains in S3 unless you * configure the rule to delete it.</p> */ export interface ApplicationVersionLifecycleConfig { /** * <p>Specify a max count rule to restrict the number of application versions that are * retained for an application.</p> */ MaxCountRule?: MaxCountRule; /** * <p>Specify a max age rule to restrict the length of time that application versions are * retained for an application.</p> */ MaxAgeRule?: MaxAgeRule; } export namespace ApplicationVersionLifecycleConfig { /** * @internal */ export const filterSensitiveLog = (obj: ApplicationVersionLifecycleConfig): any => ({ ...obj, }); } /** * <p>The resource lifecycle configuration for an application. Defines lifecycle settings for * resources that belong to the application, and the service role that AWS Elastic Beanstalk assumes * in order to apply lifecycle settings. The version lifecycle configuration defines lifecycle * settings for application versions.</p> */ export interface ApplicationResourceLifecycleConfig { /** * <p>The ARN of an IAM service role that Elastic Beanstalk has permission to * assume.</p> * <p>The <code>ServiceRole</code> property is required the first time that you provide a * <code>VersionLifecycleConfig</code> for the application in one of the supporting calls * (<code>CreateApplication</code> or <code>UpdateApplicationResourceLifecycle</code>). After * you provide it once, in either one of the calls, Elastic Beanstalk persists the Service Role with the * application, and you don't need to specify it again in subsequent * <code>UpdateApplicationResourceLifecycle</code> calls. You can, however, specify it in * subsequent calls to change the Service Role to another value.</p> */ ServiceRole?: string; /** * <p>Defines lifecycle settings for application versions.</p> */ VersionLifecycleConfig?: ApplicationVersionLifecycleConfig; } export namespace ApplicationResourceLifecycleConfig { /** * @internal */ export const filterSensitiveLog = (obj: ApplicationResourceLifecycleConfig): any => ({ ...obj, }); } /** * <p>Describes the properties of an application.</p> */ export interface ApplicationDescription { /** * <p>The Amazon Resource Name (ARN) of the application.</p> */ ApplicationArn?: string; /** * <p>The name of the application.</p> */ ApplicationName?: string; /** * <p>User-defined description of the application.</p> */ Description?: string; /** * <p>The date when the application was created.</p> */ DateCreated?: Date; /** * <p>The date when the application was last modified.</p> */ DateUpdated?: Date; /** * <p>The names of the versions for this application.</p> */ Versions?: string[]; /** * <p>The names of the configuration templates associated with this application.</p> */ ConfigurationTemplates?: string[]; /** * <p>The lifecycle settings for the application.</p> */ ResourceLifecycleConfig?: ApplicationResourceLifecycleConfig; } export namespace ApplicationDescription { /** * @internal */ export const filterSensitiveLog = (obj: ApplicationDescription): any => ({ ...obj, }); } /** * <p>Result message containing a single description of an application.</p> */ export interface ApplicationDescriptionMessage { /** * <p> The <a>ApplicationDescription</a> of the application. </p> */ Application?: ApplicationDescription; } export namespace ApplicationDescriptionMessage { /** * @internal */ export const filterSensitiveLog = (obj: ApplicationDescriptionMessage): any => ({ ...obj, }); } /** * <p>Result message containing a list of application descriptions.</p> */ export interface ApplicationDescriptionsMessage { /** * <p>This parameter contains a list of <a>ApplicationDescription</a>.</p> */ Applications?: ApplicationDescription[]; } export namespace ApplicationDescriptionsMessage { /** * @internal */ export const filterSensitiveLog = (obj: ApplicationDescriptionsMessage): any => ({ ...obj, }); } /** * <p>Represents the average latency for the slowest X percent of requests over the last 10 * seconds.</p> */ export interface Latency { /** * <p>The average latency for the slowest 0.1 percent of requests over the last 10 * seconds.</p> */ P999?: number; /** * <p>The average latency for the slowest 1 percent of requests over the last 10 * seconds.</p> */ P99?: number; /** * <p>The average latency for the slowest 5 percent of requests over the last 10 * seconds.</p> */ P95?: number; /** * <p>The average latency for the slowest 10 percent of requests over the last 10 * seconds.</p> */ P90?: number; /** * <p>The average latency for the slowest 15 percent of requests over the last 10 * seconds.</p> */ P85?: number; /** * <p>The average latency for the slowest 25 percent of requests over the last 10 * seconds.</p> */ P75?: number; /** * <p>The average latency for the slowest 50 percent of requests over the last 10 * seconds.</p> */ P50?: number; /** * <p>The average latency for the slowest 90 percent of requests over the last 10 * seconds.</p> */ P10?: number; } export namespace Latency { /** * @internal */ export const filterSensitiveLog = (obj: Latency): any => ({ ...obj, }); } /** * <p>Represents the percentage of requests over the last 10 seconds that resulted in each * type of status code response. For more information, see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">Status Code * Definitions</a>.</p> */ export interface StatusCodes { /** * <p>The percentage of requests over the last 10 seconds that resulted in a 2xx (200, 201, * etc.) status code.</p> */ Status2xx?: number; /** * <p>The percentage of requests over the last 10 seconds that resulted in a 3xx (300, 301, * etc.) status code.</p> */ Status3xx?: number; /** * <p>The percentage of requests over the last 10 seconds that resulted in a 4xx (400, 401, * etc.) status code.</p> */ Status4xx?: number; /** * <p>The percentage of requests over the last 10 seconds that resulted in a 5xx (500, 501, * etc.) status code.</p> */ Status5xx?: number; } export namespace StatusCodes { /** * @internal */ export const filterSensitiveLog = (obj: StatusCodes): any => ({ ...obj, }); } /** * <p>Application request metrics for an AWS Elastic Beanstalk environment.</p> */ export interface ApplicationMetrics { /** * <p>The amount of time that the metrics cover (usually 10 seconds). For example, you might * have 5 requests (<code>request_count</code>) within the most recent time slice of 10 seconds * (<code>duration</code>).</p> */ Duration?: number; /** * <p>Average number of requests handled by the web server per second over the last 10 * seconds.</p> */ RequestCount?: number; /** * <p>Represents the percentage of requests over the last 10 seconds that resulted in each * type of status code response.</p> */ StatusCodes?: StatusCodes; /** * <p>Represents the average latency for the slowest X percent of requests over the last 10 * seconds. Latencies are in seconds with one millisecond resolution.</p> */ Latency?: Latency; } export namespace ApplicationMetrics { /** * @internal */ export const filterSensitiveLog = (obj: ApplicationMetrics): any => ({ ...obj, }); } export interface ApplicationResourceLifecycleDescriptionMessage { /** * <p>The name of the application.</p> */ ApplicationName?: string; /** * <p>The lifecycle configuration.</p> */ ResourceLifecycleConfig?: ApplicationResourceLifecycleConfig; } export namespace ApplicationResourceLifecycleDescriptionMessage { /** * @internal */ export const filterSensitiveLog = (obj: ApplicationResourceLifecycleDescriptionMessage): any => ({ ...obj, }); } export type SourceRepository = "CodeCommit" | "S3"; export type SourceType = "Git" | "Zip"; /** * <p>Location of the source code for an application version.</p> */ export interface SourceBuildInformation { /** * <p>The type of repository.</p> * <ul> * <li> * <p> * <code>Git</code> * </p> * </li> * <li> * <p> * <code>Zip</code> * </p> * </li> * </ul> */ SourceType: SourceType | string | undefined; /** * <p>Location where the repository is stored.</p> * <ul> * <li> * <p> * <code>CodeCommit</code> * </p> * </li> * <li> * <p> * <code>S3</code> * </p> * </li> * </ul> */ SourceRepository: SourceRepository | string | undefined; /** * <p>The location of the source code, as a formatted string, depending on the value of <code>SourceRepository</code> * </p> * <ul> * <li> * <p>For <code>CodeCommit</code>, * the format is the repository name and commit ID, separated by a forward slash. * For example, * <code>my-git-repo/265cfa0cf6af46153527f55d6503ec030551f57a</code>.</p> * </li> * <li> * <p>For <code>S3</code>, * the format is the S3 bucket name and object key, separated by a forward slash. * For example, * <code>my-s3-bucket/Folders/my-source-file</code>.</p> * </li> * </ul> */ SourceLocation: string | undefined; } export namespace SourceBuildInformation { /** * @internal */ export const filterSensitiveLog = (obj: SourceBuildInformation): any => ({ ...obj, }); } /** * <p>The bucket and key of an item stored in Amazon S3.</p> */ export interface S3Location { /** * <p>The Amazon S3 bucket where the data is located.</p> */ S3Bucket?: string; /** * <p>The Amazon S3 key where the data is located.</p> */ S3Key?: string; } export namespace S3Location { /** * @internal */ export const filterSensitiveLog = (obj: S3Location): any => ({ ...obj, }); } export type ApplicationVersionStatus = "Building" | "Failed" | "Processed" | "Processing" | "Unprocessed"; /** * <p>Describes the properties of an application version.</p> */ export interface ApplicationVersionDescription { /** * <p>The Amazon Resource Name (ARN) of the application version.</p> */ ApplicationVersionArn?: string; /** * <p>The name of the application to which the application version belongs.</p> */ ApplicationName?: string; /** * <p>The description of the application version.</p> */ Description?: string; /** * <p>A unique identifier for the application version.</p> */ VersionLabel?: string; /** * <p>If the version's source code was retrieved from AWS CodeCommit, the location of the * source code for the application version.</p> */ SourceBuildInformation?: SourceBuildInformation; /** * <p>Reference to the artifact from the AWS CodeBuild build.</p> */ BuildArn?: string; /** * <p>The storage location of the application version's source bundle in Amazon S3.</p> */ SourceBundle?: S3Location; /** * <p>The creation date of the application version.</p> */ DateCreated?: Date; /** * <p>The last modified date of the application version.</p> */ DateUpdated?: Date; /** * <p>The processing status of the application version. Reflects the state of the application * version during its creation. Many of the values are only applicable if you specified * <code>True</code> for the <code>Process</code> parameter of the * <code>CreateApplicationVersion</code> action. The following list describes the possible * values.</p> * <ul> * <li> * <p> * <code>Unprocessed</code> – Application version wasn't pre-processed or validated. * Elastic Beanstalk will validate configuration files during deployment of the application version to an * environment.</p> * </li> * <li> * <p> * <code>Processing</code> – Elastic Beanstalk is currently processing the application version.</p> * </li> * <li> * <p> * <code>Building</code> – Application version is currently undergoing an AWS CodeBuild build.</p> * </li> * <li> * <p> * <code>Processed</code> – Elastic Beanstalk was successfully pre-processed and validated.</p> * </li> * <li> * <p> * <code>Failed</code> – Either the AWS CodeBuild build failed or configuration files didn't * pass validation. This application version isn't usable.</p> * </li> * </ul> */ Status?: ApplicationVersionStatus | string; } export namespace ApplicationVersionDescription { /** * @internal */ export const filterSensitiveLog = (obj: ApplicationVersionDescription): any => ({ ...obj, }); } /** * <p>Result message wrapping a single description of an application version.</p> */ export interface ApplicationVersionDescriptionMessage { /** * <p> The <a>ApplicationVersionDescription</a> of the application version. * </p> */ ApplicationVersion?: ApplicationVersionDescription; } export namespace ApplicationVersionDescriptionMessage { /** * @internal */ export const filterSensitiveLog = (obj: ApplicationVersionDescriptionMessage): any => ({ ...obj, }); } /** * <p>Result message wrapping a list of application version descriptions.</p> */ export interface ApplicationVersionDescriptionsMessage { /** * <p>List of <code>ApplicationVersionDescription</code> objects sorted in order of * creation.</p> */ ApplicationVersions?: ApplicationVersionDescription[]; /** * <p>In a paginated request, the token that you can pass in a subsequent request to get the * next response page.</p> */ NextToken?: string; } export namespace ApplicationVersionDescriptionsMessage { /** * @internal */ export const filterSensitiveLog = (obj: ApplicationVersionDescriptionsMessage): any => ({ ...obj, }); } /** * <p>Request to execute a scheduled managed action immediately.</p> */ export interface ApplyEnvironmentManagedActionRequest { /** * <p>The name of the target environment.</p> */ EnvironmentName?: string; /** * <p>The environment ID of the target environment.</p> */ EnvironmentId?: string; /** * <p>The action ID of the scheduled managed action to execute.</p> */ ActionId: string | undefined; } export namespace ApplyEnvironmentManagedActionRequest { /** * @internal */ export const filterSensitiveLog = (obj: ApplyEnvironmentManagedActionRequest): any => ({ ...obj, }); } /** * <p>The result message containing information about the managed action.</p> */ export interface ApplyEnvironmentManagedActionResult { /** * <p>The action ID of the managed action.</p> */ ActionId?: string; /** * <p>A description of the managed action.</p> */ ActionDescription?: string; /** * <p>The type of managed action.</p> */ ActionType?: ActionType | string; /** * <p>The status of the managed action.</p> */ Status?: string; } export namespace ApplyEnvironmentManagedActionResult { /** * @internal */ export const filterSensitiveLog = (obj: ApplyEnvironmentManagedActionResult): any => ({ ...obj, }); } /** * <p>A generic service exception has occurred.</p> */ export interface ElasticBeanstalkServiceException extends __SmithyException, $MetadataBearer { name: "ElasticBeanstalkServiceException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace ElasticBeanstalkServiceException { /** * @internal */ export const filterSensitiveLog = (obj: ElasticBeanstalkServiceException): any => ({ ...obj, }); } /** * <p>Cannot modify the managed action in its current state.</p> */ export interface ManagedActionInvalidStateException extends __SmithyException, $MetadataBearer { name: "ManagedActionInvalidStateException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace ManagedActionInvalidStateException { /** * @internal */ export const filterSensitiveLog = (obj: ManagedActionInvalidStateException): any => ({ ...obj, }); } /** * <p>Request to add or change the operations role used by an environment.</p> */ export interface AssociateEnvironmentOperationsRoleMessage { /** * <p>The name of the environment to which to set the operations role.</p> */ EnvironmentName: string | undefined; /** * <p>The Amazon Resource Name (ARN) of an existing IAM role to be used as the environment's * operations role.</p> */ OperationsRole: string | undefined; } export namespace AssociateEnvironmentOperationsRoleMessage { /** * @internal */ export const filterSensitiveLog = (obj: AssociateEnvironmentOperationsRoleMessage): any => ({ ...obj, }); } /** * <p>Describes an Auto Scaling launch configuration.</p> */ export interface AutoScalingGroup { /** * <p>The name of the <code>AutoScalingGroup</code> . </p> */ Name?: string; } export namespace AutoScalingGroup { /** * @internal */ export const filterSensitiveLog = (obj: AutoScalingGroup): any => ({ ...obj, }); } /** * <p>Describes the solution stack.</p> */ export interface SolutionStackDescription { /** * <p>The name of the solution stack.</p> */ SolutionStackName?: string; /** * <p>The permitted file types allowed for a solution stack.</p> */ PermittedFileTypes?: string[]; } export namespace SolutionStackDescription { /** * @internal */ export const filterSensitiveLog = (obj: SolutionStackDescription): any => ({ ...obj, }); } /** * <p>Results message indicating whether a CNAME is available.</p> */ export interface CheckDNSAvailabilityMessage { /** * <p>The prefix used when this CNAME is reserved.</p> */ CNAMEPrefix: string | undefined; } export namespace CheckDNSAvailabilityMessage { /** * @internal */ export const filterSensitiveLog = (obj: CheckDNSAvailabilityMessage): any => ({ ...obj, }); } /** * <p>Indicates if the specified CNAME is available.</p> */ export interface CheckDNSAvailabilityResultMessage { /** * <p>Indicates if the specified CNAME is available:</p> * <ul> * <li> * <p> * <code>true</code> : The CNAME is available.</p> * </li> * <li> * <p> * <code>false</code> : The CNAME is not available.</p> * </li> * </ul> */ Available?: boolean; /** * <p>The fully qualified CNAME to reserve when <a>CreateEnvironment</a> is called * with the provided prefix.</p> */ FullyQualifiedCNAME?: string; } export namespace CheckDNSAvailabilityResultMessage { /** * @internal */ export const filterSensitiveLog = (obj: CheckDNSAvailabilityResultMessage): any => ({ ...obj, }); } /** * <p>Request to create or update a group of environments.</p> */ export interface ComposeEnvironmentsMessage { /** * <p>The name of the application to which the specified source bundles belong.</p> */ ApplicationName?: string; /** * <p>The name of the group to which the target environments belong. Specify a group name * only if the environment name defined in each target environment's manifest ends with a + * (plus) character. See <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-cfg-manifest.html">Environment Manifest * (env.yaml)</a> for details.</p> */ GroupName?: string; /** * <p>A list of version labels, specifying one or more application source bundles that belong * to the target application. Each source bundle must include an environment manifest that * specifies the name of the environment and the name of the solution stack to use, and * optionally can specify environment links to create.</p> */ VersionLabels?: string[]; } export namespace ComposeEnvironmentsMessage { /** * @internal */ export const filterSensitiveLog = (obj: ComposeEnvironmentsMessage): any => ({ ...obj, }); } /** * <p>A link to another environment, defined in the environment's manifest. Links provide * connection information in system properties that can be used to connect to another environment * in the same group. See <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-cfg-manifest.html">Environment Manifest * (env.yaml)</a> for details.</p> */ export interface EnvironmentLink { /** * <p>The name of the link.</p> */ LinkName?: string; /** * <p>The name of the linked environment (the dependency).</p> */ EnvironmentName?: string; } export namespace EnvironmentLink { /** * @internal */ export const filterSensitiveLog = (obj: EnvironmentLink): any => ({ ...obj, }); } export type EnvironmentHealth = "Green" | "Grey" | "Red" | "Yellow"; export type EnvironmentHealthStatus = | "Degraded" | "Info" | "NoData" | "Ok" | "Pending" | "Severe" | "Suspended" | "Unknown" | "Warning"; /** * <p>Describes the properties of a Listener for the LoadBalancer.</p> */ export interface Listener { /** * <p>The protocol that is used by the Listener.</p> */ Protocol?: string; /** * <p>The port that is used by the Listener.</p> */ Port?: number; } export namespace Listener { /** * @internal */ export const filterSensitiveLog = (obj: Listener): any => ({ ...obj, }); } /** * <p>Describes the details of a LoadBalancer.</p> */ export interface LoadBalancerDescription { /** * <p>The name of the LoadBalancer.</p> */ LoadBalancerName?: string; /** * <p>The domain name of the LoadBalancer.</p> */ Domain?: string; /** * <p>A list of Listeners used by the LoadBalancer.</p> */ Listeners?: Listener[]; } export namespace LoadBalancerDescription { /** * @internal */ export const filterSensitiveLog = (obj: LoadBalancerDescription): any => ({ ...obj, }); } /** * <p>Describes the AWS resources in use by this environment. This data is not live * data.</p> */ export interface EnvironmentResourcesDescription { /** * <p>Describes the LoadBalancer.</p> */ LoadBalancer?: LoadBalancerDescription; } export namespace EnvironmentResourcesDescription { /** * @internal */ export const filterSensitiveLog = (obj: EnvironmentResourcesDescription): any => ({ ...obj, }); } export type EnvironmentStatus = | "Aborting" | "Launching" | "LinkingFrom" | "LinkingTo" | "Ready" | "Terminated" | "Terminating" | "Updating"; /** * <p>Describes the properties of an environment tier</p> */ export interface EnvironmentTier { /** * <p>The name of this environment tier.</p> * <p>Valid values:</p> * <ul> * <li> * <p>For <i>Web server tier</i> – <code>WebServer</code> * </p> * </li> * <li> * <p>For <i>Worker tier</i> – <code>Worker</code> * </p> * </li> * </ul> */ Name?: string; /** * <p>The type of this environment tier.</p> * <p>Valid values:</p> * <ul> * <li> * <p>For <i>Web server tier</i> – <code>Standard</code> * </p> * </li> * <li> * <p>For <i>Worker tier</i> – <code>SQS/HTTP</code> * </p> * </li> * </ul> */ Type?: string; /** * <p>The version of this environment tier. When you don't set a value to it, Elastic Beanstalk uses the * latest compatible worker tier version.</p> * <note> * <p>This member is deprecated. Any specific version that you set may become out of date. * We recommend leaving it unspecified.</p> * </note> */ Version?: string; } export namespace EnvironmentTier { /** * @internal */ export const filterSensitiveLog = (obj: EnvironmentTier): any => ({ ...obj, }); } /** * <p>Describes the properties of an environment.</p> */ export interface EnvironmentDescription { /** * <p>The name of this environment.</p> */ EnvironmentName?: string; /** * <p>The ID of this environment.</p> */ EnvironmentId?: string; /** * <p>The name of the application associated with this environment.</p> */ ApplicationName?: string; /** * <p>The application version deployed in this environment.</p> */ VersionLabel?: string; /** * <p> The name of the <code>SolutionStack</code> deployed with this environment. </p> */ SolutionStackName?: string; /** * <p>The ARN of the platform version.</p> */ PlatformArn?: string; /** * <p>The name of the configuration template used to originally launch this * environment.</p> */ TemplateName?: string; /** * <p>Describes this environment.</p> */ Description?: string; /** * <p>For load-balanced, autoscaling environments, the URL to the LoadBalancer. For * single-instance environments, the IP address of the instance.</p> */ EndpointURL?: string; /** * <p>The URL to the CNAME for this environment.</p> */ CNAME?: string; /** * <p>The creation date for this environment.</p> */ DateCreated?: Date; /** * <p>The last modified date for this environment.</p> */ DateUpdated?: Date; /** * <p>The current operational status of the environment:</p> * * <ul> * <li> * <p> * <code>Launching</code>: Environment is in the process of initial deployment.</p> * </li> * <li> * <p> * <code>Updating</code>: Environment is in the process of updating its configuration * settings or application version.</p> * </li> * <li> * <p> * <code>Ready</code>: Environment is available to have an action performed on it, such as * update or terminate.</p> * </li> * <li> * <p> * <code>Terminating</code>: Environment is in the shut-down process.</p> * </li> * <li> * <p> * <code>Terminated</code>: Environment is not running.</p> * </li> * </ul> */ Status?: EnvironmentStatus | string; /** * <p>Indicates if there is an in-progress environment configuration update or application * version deployment that you can cancel.</p> * <p> * <code>true:</code> There is an update in progress. </p> * <p> * <code>false:</code> There are no updates currently in progress. </p> */ AbortableOperationInProgress?: boolean; /** * <p>Describes the health status of the environment. AWS Elastic Beanstalk indicates the * failure levels for a running environment:</p> * <ul> * <li> * <p> * <code>Red</code>: Indicates the environment is not responsive. Occurs when three or more * consecutive failures occur for an environment.</p> * </li> * <li> * <p> * <code>Yellow</code>: Indicates that something is wrong. Occurs when two consecutive * failures occur for an environment.</p> * </li> * <li> * <p> * <code>Green</code>: Indicates the environment is healthy and fully functional.</p> * </li> * <li> * <p> * <code>Grey</code>: Default health for a new environment. The environment is not fully * launched and health checks have not started or health checks are suspended during an * <code>UpdateEnvironment</code> or <code>RestartEnvironment</code> request.</p> * </li> * </ul> * <p> Default: <code>Grey</code> * </p> */ Health?: EnvironmentHealth | string; /** * <p>Returns the health status of the application running in your environment. For more * information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/health-enhanced-status.html">Health Colors and * Statuses</a>.</p> */ HealthStatus?: EnvironmentHealthStatus | string; /** * <p>The description of the AWS resources used by this environment.</p> */ Resources?: EnvironmentResourcesDescription; /** * <p>Describes the current tier of this environment.</p> */ Tier?: EnvironmentTier; /** * <p>A list of links to other environments in the same group.</p> */ EnvironmentLinks?: EnvironmentLink[]; /** * <p>The environment's Amazon Resource Name (ARN), which can be used in other API requests that require an ARN.</p> */ EnvironmentArn?: string; /** * <p>The Amazon Resource Name (ARN) of the environment's operations role. For more information, * see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-operationsrole.html">Operations roles</a> in the <i>AWS Elastic Beanstalk Developer Guide</i>.</p> */ OperationsRole?: string; } export namespace EnvironmentDescription { /** * @internal */ export const filterSensitiveLog = (obj: EnvironmentDescription): any => ({ ...obj, }); } /** * <p>Result message containing a list of environment descriptions.</p> */ export interface EnvironmentDescriptionsMessage { /** * <p> Returns an <a>EnvironmentDescription</a> list. </p> */ Environments?: EnvironmentDescription[]; /** * <p>In a paginated request, the token that you can pass in a subsequent request to get the * next response page.</p> */ NextToken?: string; } export namespace EnvironmentDescriptionsMessage { /** * @internal */ export const filterSensitiveLog = (obj: EnvironmentDescriptionsMessage): any => ({ ...obj, }); } /** * <p>The specified account has reached its limit of environments.</p> */ export interface TooManyEnvironmentsException extends __SmithyException, $MetadataBearer { name: "TooManyEnvironmentsException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace TooManyEnvironmentsException { /** * @internal */ export const filterSensitiveLog = (obj: TooManyEnvironmentsException): any => ({ ...obj, }); } /** * <p>Describes a tag applied to a resource in an environment.</p> */ export interface Tag { /** * <p>The key of the tag.</p> */ Key?: string; /** * <p>The value of the tag.</p> */ Value?: string; } export namespace Tag { /** * @internal */ export const filterSensitiveLog = (obj: Tag): any => ({ ...obj, }); } /** * <p>Request to create an application.</p> */ export interface CreateApplicationMessage { /** * <p>The name of the application. Must be unique within your account.</p> */ ApplicationName: string | undefined; /** * <p>Your description of the application.</p> */ Description?: string; /** * <p>Specifies an application resource lifecycle configuration to prevent your application * from accumulating too many versions.</p> */ ResourceLifecycleConfig?: ApplicationResourceLifecycleConfig; /** * <p>Specifies the tags applied to the application.</p> * <p>Elastic Beanstalk applies these tags only to the application. Environments that you create in the * application don't inherit the tags.</p> */ Tags?: Tag[]; } export namespace CreateApplicationMessage { /** * @internal */ export const filterSensitiveLog = (obj: CreateApplicationMessage): any => ({ ...obj, }); } /** * <p>The specified account has reached its limit of applications.</p> */ export interface TooManyApplicationsException extends __SmithyException, $MetadataBearer { name: "TooManyApplicationsException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace TooManyApplicationsException { /** * @internal */ export const filterSensitiveLog = (obj: TooManyApplicationsException): any => ({ ...obj, }); } /** * <p>AWS CodeBuild is not available in the specified region.</p> */ export interface CodeBuildNotInServiceRegionException extends __SmithyException, $MetadataBearer { name: "CodeBuildNotInServiceRegionException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace CodeBuildNotInServiceRegionException { /** * @internal */ export const filterSensitiveLog = (obj: CodeBuildNotInServiceRegionException): any => ({ ...obj, }); } export enum ComputeType { BUILD_GENERAL1_LARGE = "BUILD_GENERAL1_LARGE", BUILD_GENERAL1_MEDIUM = "BUILD_GENERAL1_MEDIUM", BUILD_GENERAL1_SMALL = "BUILD_GENERAL1_SMALL", } /** * <p>Settings for an AWS CodeBuild build.</p> */ export interface BuildConfiguration { /** * <p>The name of the artifact of the CodeBuild build. * If provided, Elastic Beanstalk stores the build artifact in the S3 location * <i>S3-bucket</i>/resources/<i>application-name</i>/codebuild/codebuild-<i>version-label</i>-<i>artifact-name</i>.zip. * If not provided, Elastic Beanstalk stores the build artifact in the S3 location * <i>S3-bucket</i>/resources/<i>application-name</i>/codebuild/codebuild-<i>version-label</i>.zip. * </p> */ ArtifactName?: string; /** * <p>The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that enables AWS CodeBuild to interact with dependent AWS services on behalf of the AWS account.</p> */ CodeBuildServiceRole: string | undefined; /** * <p>Information about the compute resources the build project will use.</p> * <ul> * <li> * <p> * <code>BUILD_GENERAL1_SMALL: Use up to 3 GB memory and 2 vCPUs for builds</code> * </p> * </li> * <li> * <p> * <code>BUILD_GENERAL1_MEDIUM: Use up to 7 GB memory and 4 vCPUs for builds</code> * </p> * </li> * <li> * <p> * <code>BUILD_GENERAL1_LARGE: Use up to 15 GB memory and 8 vCPUs for builds</code> * </p> * </li> * </ul> */ ComputeType?: ComputeType | string; /** * <p>The ID of the Docker image to use for this build project.</p> */ Image: string | undefined; /** * <p>How long in minutes, from 5 to 480 (8 hours), for AWS CodeBuild to wait until timing out any related build that does not get marked as completed. The default is 60 minutes.</p> */ TimeoutInMinutes?: number; } export namespace BuildConfiguration { /** * @internal */ export const filterSensitiveLog = (obj: BuildConfiguration): any => ({ ...obj, }); } /** * <p></p> */ export interface CreateApplicationVersionMessage { /** * <p> The name of the application. If no application is found with this name, and * <code>AutoCreateApplication</code> is <code>false</code>, returns an * <code>InvalidParameterValue</code> error. </p> */ ApplicationName: string | undefined; /** * <p>A label identifying this version.</p> * <p>Constraint: Must be unique per application. If an application version already exists * with this label for the specified application, AWS Elastic Beanstalk returns an * <code>InvalidParameterValue</code> error. </p> */ VersionLabel: string | undefined; /** * <p>A description of this application version.</p> */ Description?: string; /** * <p>Specify a commit in an AWS CodeCommit Git repository to use as the source code for the * application version.</p> */ SourceBuildInformation?: SourceBuildInformation; /** * <p>The Amazon S3 bucket and key that identify the location of the source bundle for this * version.</p> * <note> * <p>The Amazon S3 bucket must be in the same region as the * environment.</p> * </note> * <p>Specify a source bundle in S3 or a commit in an AWS CodeCommit repository (with * <code>SourceBuildInformation</code>), but not both. If neither <code>SourceBundle</code> nor * <code>SourceBuildInformation</code> are provided, Elastic Beanstalk uses a sample * application.</p> */ SourceBundle?: S3Location; /** * <p>Settings for an AWS CodeBuild build.</p> */ BuildConfiguration?: BuildConfiguration; /** * <p>Set to <code>true</code> to create an application with the specified name if it doesn't * already exist.</p> */ AutoCreateApplication?: boolean; /** * <p>Pre-processes and validates the environment manifest (<code>env.yaml</code>) and * configuration files (<code>*.config</code> files in the <code>.ebextensions</code> folder) in * the source bundle. Validating configuration files can identify issues prior to deploying the * application version to an environment.</p> * <p>You must turn processing on for application versions that you create using AWS * CodeBuild or AWS CodeCommit. For application versions built from a source bundle in Amazon S3, * processing is optional.</p> * <note> * <p>The <code>Process</code> option validates Elastic Beanstalk configuration files. It * doesn't validate your application's configuration files, like proxy server or Docker * configuration.</p> * </note> */ Process?: boolean; /** * <p>Specifies the tags applied to the application version.</p> * <p>Elastic Beanstalk applies these tags only to the application version. Environments that use the * application version don't inherit the tags.</p> */ Tags?: Tag[]; } export namespace CreateApplicationVersionMessage { /** * @internal */ export const filterSensitiveLog = (obj: CreateApplicationVersionMessage): any => ({ ...obj, }); } /** * <p>The specified S3 bucket does not belong to the S3 region in which the service is * running. The following regions are supported:</p> * <ul> * <li> * <p>IAD/us-east-1</p> * </li> * <li> * <p>PDX/us-west-2</p> * </li> * <li> * <p>DUB/eu-west-1</p> * </li> * </ul> */ export interface S3LocationNotInServiceRegionException extends __SmithyException, $MetadataBearer { name: "S3LocationNotInServiceRegionException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace S3LocationNotInServiceRegionException { /** * @internal */ export const filterSensitiveLog = (obj: S3LocationNotInServiceRegionException): any => ({ ...obj, }); } /** * <p>The specified account has reached its limit of application versions.</p> */ export interface TooManyApplicationVersionsException extends __SmithyException, $MetadataBearer { name: "TooManyApplicationVersionsException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace TooManyApplicationVersionsException { /** * @internal */ export const filterSensitiveLog = (obj: TooManyApplicationVersionsException): any => ({ ...obj, }); } export type ConfigurationDeploymentStatus = "deployed" | "failed" | "pending"; /** * <p>A specification identifying an individual configuration option along with its current * value. For a list of possible namespaces and option values, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options.html">Option Values</a> in the * <i>AWS Elastic Beanstalk Developer Guide</i>. </p> */ export interface ConfigurationOptionSetting { /** * <p>A unique resource name for the option setting. Use it for a time–based scaling configuration option.</p> */ ResourceName?: string; /** * <p>A unique namespace that identifies the option's associated AWS resource.</p> */ Namespace?: string; /** * <p>The name of the configuration option.</p> */ OptionName?: string; /** * <p>The current value for the configuration option.</p> */ Value?: string; } export namespace ConfigurationOptionSetting { /** * @internal */ export const filterSensitiveLog = (obj: ConfigurationOptionSetting): any => ({ ...obj, }); } /** * <p>Describes the settings for a configuration set.</p> */ export interface ConfigurationSettingsDescription { /** * <p>The name of the solution stack this configuration set uses.</p> */ SolutionStackName?: string; /** * <p>The ARN of the platform version.</p> */ PlatformArn?: string; /** * <p>The name of the application associated with this configuration set.</p> */ ApplicationName?: string; /** * <p> If not <code>null</code>, the name of the configuration template for this * configuration set. </p> */ TemplateName?: string; /** * <p>Describes this configuration set.</p> */ Description?: string; /** * <p> If not <code>null</code>, the name of the environment for this configuration set. * </p> */ EnvironmentName?: string; /** * <p> If this configuration set is associated with an environment, the * <code>DeploymentStatus</code> parameter indicates the deployment status of this * configuration set: </p> * <ul> * <li> * <p> * <code>null</code>: This configuration is not associated with a running * environment.</p> * </li> * <li> * <p> * <code>pending</code>: This is a draft configuration that is not deployed to the associated * environment but is in the process of deploying.</p> * </li> * <li> * <p> * <code>deployed</code>: This is the configuration that is currently deployed to the * associated running environment.</p> * </li> * <li> * <p> * <code>failed</code>: This is a draft configuration that failed to successfully * deploy.</p> * </li> * </ul> */ DeploymentStatus?: ConfigurationDeploymentStatus | string; /** * <p>The date (in UTC time) when this configuration set was created.</p> */ DateCreated?: Date; /** * <p>The date (in UTC time) when this configuration set was last modified.</p> */ DateUpdated?: Date; /** * <p>A list of the configuration options and their values in this configuration * set.</p> */ OptionSettings?: ConfigurationOptionSetting[]; } export namespace ConfigurationSettingsDescription { /** * @internal */ export const filterSensitiveLog = (obj: ConfigurationSettingsDescription): any => ({ ...obj, }); } /** * <p>A specification for an environment configuration.</p> */ export interface SourceConfiguration { /** * <p>The name of the application associated with the configuration.</p> */ ApplicationName?: string; /** * <p>The name of the configuration template.</p> */ TemplateName?: string; } export namespace SourceConfiguration { /** * @internal */ export const filterSensitiveLog = (obj: SourceConfiguration): any => ({ ...obj, }); } /** * <p>Request to create a configuration template.</p> */ export interface CreateConfigurationTemplateMessage { /** * <p>The name of the Elastic Beanstalk application to associate with this configuration * template.</p> */ ApplicationName: string | undefined; /** * <p>The name of the configuration template.</p> * <p>Constraint: This name must be unique per application.</p> */ TemplateName: string | undefined; /** * <p>The name of an Elastic Beanstalk solution stack (platform version) that this configuration uses. For * example, <code>64bit Amazon Linux 2013.09 running Tomcat 7 Java 7</code>. A solution stack * specifies the operating system, runtime, and application server for a configuration template. * It also determines the set of configuration options as well as the possible and default * values. For more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts.platforms.html">Supported Platforms</a> in the * <i>AWS Elastic Beanstalk Developer Guide</i>.</p> * <p>You must specify <code>SolutionStackName</code> if you don't specify * <code>PlatformArn</code>, <code>EnvironmentId</code>, or * <code>SourceConfiguration</code>.</p> * <p>Use the <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/api/API_ListAvailableSolutionStacks.html"> * <code>ListAvailableSolutionStacks</code> * </a> API to obtain a list of available * solution stacks.</p> */ SolutionStackName?: string; /** * <p>The Amazon Resource Name (ARN) of the custom platform. For more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/custom-platforms.html"> Custom * Platforms</a> in the <i>AWS Elastic Beanstalk Developer Guide</i>.</p> * <note> * * <p>If you specify <code>PlatformArn</code>, then don't specify * <code>SolutionStackName</code>.</p> * </note> */ PlatformArn?: string; /** * <p>An Elastic Beanstalk configuration template to base this one on. If specified, Elastic Beanstalk uses the configuration values from the specified * configuration template to create a new configuration.</p> * <p>Values specified in <code>OptionSettings</code> override any values obtained from the * <code>SourceConfiguration</code>.</p> * <p>You must specify <code>SourceConfiguration</code> if you don't specify * <code>PlatformArn</code>, <code>EnvironmentId</code>, or * <code>SolutionStackName</code>.</p> * <p>Constraint: If both solution stack name and source configuration are specified, the * solution stack of the source configuration template must match the specified solution stack * name.</p> */ SourceConfiguration?: SourceConfiguration; /** * <p>The ID of an environment whose settings you want to use to create the configuration * template. You must specify <code>EnvironmentId</code> if you don't specify * <code>PlatformArn</code>, <code>SolutionStackName</code>, or * <code>SourceConfiguration</code>.</p> */ EnvironmentId?: string; /** * <p>An optional description for this configuration.</p> */ Description?: string; /** * <p>Option values for the Elastic Beanstalk configuration, such as the instance type. If specified, these * values override the values obtained from the solution stack or the source configuration * template. For a complete list of Elastic Beanstalk configuration options, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options.html">Option Values</a> in the * <i>AWS Elastic Beanstalk Developer Guide</i>.</p> */ OptionSettings?: ConfigurationOptionSetting[]; /** * <p>Specifies the tags applied to the configuration template.</p> */ Tags?: Tag[]; } export namespace CreateConfigurationTemplateMessage { /** * @internal */ export const filterSensitiveLog = (obj: CreateConfigurationTemplateMessage): any => ({ ...obj, }); } /** * <p>The specified account has reached its limit of Amazon S3 buckets.</p> */ export interface TooManyBucketsException extends __SmithyException, $MetadataBearer { name: "TooManyBucketsException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace TooManyBucketsException { /** * @internal */ export const filterSensitiveLog = (obj: TooManyBucketsException): any => ({ ...obj, }); } /** * <p>The specified account has reached its limit of configuration templates.</p> */ export interface TooManyConfigurationTemplatesException extends __SmithyException, $MetadataBearer { name: "TooManyConfigurationTemplatesException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace TooManyConfigurationTemplatesException { /** * @internal */ export const filterSensitiveLog = (obj: TooManyConfigurationTemplatesException): any => ({ ...obj, }); } /** * <p>A specification identifying an individual configuration option.</p> */ export interface OptionSpecification { /** * <p>A unique resource name for a time-based scaling configuration option.</p> */ ResourceName?: string; /** * <p>A unique namespace identifying the option's associated AWS resource.</p> */ Namespace?: string; /** * <p>The name of the configuration option.</p> */ OptionName?: string; } export namespace OptionSpecification { /** * @internal */ export const filterSensitiveLog = (obj: OptionSpecification): any => ({ ...obj, }); } /** * <p></p> */ export interface CreateEnvironmentMessage { /** * <p>The name of the application that is associated with this environment.</p> */ ApplicationName: string | undefined; /** * <p>A unique name for the environment.</p> * <p>Constraint: Must be from 4 to 40 characters in length. The name can contain only * letters, numbers, and hyphens. It can't start or end with a hyphen. This name must be unique * within a region in your account. If the specified name already exists in the region, Elastic Beanstalk returns an * <code>InvalidParameterValue</code> error. </p> * <p>If you don't specify the <code>CNAMEPrefix</code> parameter, the environment name becomes part of * the CNAME, and therefore part of the visible URL for your application.</p> */ EnvironmentName?: string; /** * <p>The name of the group to which the target environment belongs. Specify a group name * only if the environment's name is specified in an environment manifest and not with the * environment name parameter. See <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-cfg-manifest.html">Environment Manifest * (env.yaml)</a> for details.</p> */ GroupName?: string; /** * <p>Your description for this environment.</p> */ Description?: string; /** * <p>If specified, the environment attempts to use this value as the prefix for the CNAME in * your Elastic Beanstalk environment URL. If not specified, the CNAME is generated automatically by * appending a random alphanumeric string to the environment name.</p> */ CNAMEPrefix?: string; /** * <p>Specifies the tier to use in creating this environment. The environment tier that you * choose determines whether Elastic Beanstalk provisions resources to support a web application that handles * HTTP(S) requests or a web application that handles background-processing tasks.</p> */ Tier?: EnvironmentTier; /** * <p>Specifies the tags applied to resources in the environment.</p> */ Tags?: Tag[]; /** * <p>The name of the application version to deploy.</p> * <p>Default: If not specified, Elastic Beanstalk attempts to deploy the sample application.</p> */ VersionLabel?: string; /** * <p>The name of the Elastic Beanstalk configuration template to use with the environment.</p> * <note> * <p>If you specify <code>TemplateName</code>, then don't specify * <code>SolutionStackName</code>.</p> * </note> */ TemplateName?: string; /** * <p>The name of an Elastic Beanstalk solution stack (platform version) to use with the environment. If * specified, Elastic Beanstalk sets the configuration values to the default values associated with the * specified solution stack. For a list of current solution stacks, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/platforms/platforms-supported.html">Elastic Beanstalk Supported Platforms</a> in the <i>AWS Elastic Beanstalk * Platforms</i> guide.</p> * <note> * <p>If you specify <code>SolutionStackName</code>, don't specify <code>PlatformArn</code> or * <code>TemplateName</code>.</p> * </note> */ SolutionStackName?: string; /** * <p>The Amazon Resource Name (ARN) of the custom platform to use with the environment. For * more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/custom-platforms.html">Custom Platforms</a> in the * <i>AWS Elastic Beanstalk Developer Guide</i>.</p> * <note> * * <p>If you specify <code>PlatformArn</code>, don't specify * <code>SolutionStackName</code>.</p> * </note> */ PlatformArn?: string; /** * <p>If specified, AWS Elastic Beanstalk sets the specified configuration options to the * requested value in the configuration set for the new environment. These override the values * obtained from the solution stack or the configuration template.</p> */ OptionSettings?: ConfigurationOptionSetting[]; /** * <p>A list of custom user-defined configuration options to remove from the configuration * set for this new environment.</p> */ OptionsToRemove?: OptionSpecification[]; /** * <p>The Amazon Resource Name (ARN) of an existing IAM role to be used as the environment's * operations role. If specified, Elastic Beanstalk uses the operations role for permissions to downstream * services during this call and during subsequent calls acting on this environment. To specify * an operations role, you must have the <code>iam:PassRole</code> permission for the role. For * more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/iam-operationsrole.html">Operations roles</a> in the * <i>AWS Elastic Beanstalk Developer Guide</i>.</p> */ OperationsRole?: string; } export namespace CreateEnvironmentMessage { /** * @internal */ export const filterSensitiveLog = (obj: CreateEnvironmentMessage): any => ({ ...obj, }); } /** * <p>Request to create a new platform version.</p> */ export interface CreatePlatformVersionRequest { /** * <p>The name of your custom platform.</p> */ PlatformName: string | undefined; /** * <p>The number, such as 1.0.2, for the new platform version.</p> */ PlatformVersion: string | undefined; /** * <p>The location of the platform definition archive in Amazon S3.</p> */ PlatformDefinitionBundle: S3Location | undefined; /** * <p>The name of the builder environment.</p> */ EnvironmentName?: string; /** * <p>The configuration option settings to apply to the builder environment.</p> */ OptionSettings?: ConfigurationOptionSetting[]; /** * <p>Specifies the tags applied to the new platform version.</p> * <p>Elastic Beanstalk applies these tags only to the platform version. Environments that you create using * the platform version don't inherit the tags.</p> */ Tags?: Tag[]; } export namespace CreatePlatformVersionRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreatePlatformVersionRequest): any => ({ ...obj, }); } /** * <p>The builder used to build the custom platform.</p> */ export interface Builder { /** * <p>The ARN of the builder.</p> */ ARN?: string; } export namespace Builder { /** * @internal */ export const filterSensitiveLog = (obj: Builder): any => ({ ...obj, }); } export type PlatformStatus = "Creating" | "Deleted" | "Deleting" | "Failed" | "Ready"; /** * <p>Summary information about a platform version.</p> */ export interface PlatformSummary { /** * <p>The ARN of the platform version.</p> */ PlatformArn?: string; /** * <p>The AWS account ID of the person who created the platform version.</p> */ PlatformOwner?: string; /** * <p>The status of the platform version. You can create an environment from the platform * version once it is ready.</p> */ PlatformStatus?: PlatformStatus | string; /** * <p>The category of platform version.</p> */ PlatformCategory?: string; /** * <p>The operating system used by the platform version.</p> */ OperatingSystemName?: string; /** * <p>The version of the operating system used by the platform version.</p> */ OperatingSystemVersion?: string; /** * <p>The tiers in which the platform version runs.</p> */ SupportedTierList?: string[]; /** * <p>The additions associated with the platform version.</p> */ SupportedAddonList?: string[]; /** * <p>The state of the platform version in its lifecycle.</p> * <p>Possible values: <code>recommended</code> | empty</p> * <p>If an empty value is returned, the platform version is supported but isn't the recommended * one for its branch.</p> */ PlatformLifecycleState?: string; /** * <p>The version string of the platform version.</p> */ PlatformVersion?: string; /** * <p>The platform branch to which the platform version belongs.</p> */ PlatformBranchName?: string; /** * <p>The state of the platform version's branch in its lifecycle.</p> * <p>Possible values: <code>beta</code> | <code>supported</code> | <code>deprecated</code> | * <code>retired</code> * </p> */ PlatformBranchLifecycleState?: string; } export namespace PlatformSummary { /** * @internal */ export const filterSensitiveLog = (obj: PlatformSummary): any => ({ ...obj, }); } export interface CreatePlatformVersionResult { /** * <p>Detailed information about the new version of the custom platform.</p> */ PlatformSummary?: PlatformSummary; /** * <p>The builder used to create the custom platform.</p> */ Builder?: Builder; } export namespace CreatePlatformVersionResult { /** * @internal */ export const filterSensitiveLog = (obj: CreatePlatformVersionResult): any => ({ ...obj, }); } /** * <p>You have exceeded the maximum number of allowed platforms associated with the account.</p> */ export interface TooManyPlatformsException extends __SmithyException, $MetadataBearer { name: "TooManyPlatformsException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace TooManyPlatformsException { /** * @internal */ export const filterSensitiveLog = (obj: TooManyPlatformsException): any => ({ ...obj, }); } /** * <p>Results of a <a>CreateStorageLocationResult</a> call.</p> */ export interface CreateStorageLocationResultMessage { /** * <p>The name of the Amazon S3 bucket created.</p> */ S3Bucket?: string; } export namespace CreateStorageLocationResultMessage { /** * @internal */ export const filterSensitiveLog = (obj: CreateStorageLocationResultMessage): any => ({ ...obj, }); } /** * <p>The specified account does not have a subscription to Amazon S3.</p> */ export interface S3SubscriptionRequiredException extends __SmithyException, $MetadataBearer { name: "S3SubscriptionRequiredException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace S3SubscriptionRequiredException { /** * @internal */ export const filterSensitiveLog = (obj: S3SubscriptionRequiredException): any => ({ ...obj, }); } /** * <p>Request to delete an application.</p> */ export interface DeleteApplicationMessage { /** * <p>The name of the application to delete.</p> */ ApplicationName: string | undefined; /** * <p>When set to true, running environments will be terminated before deleting the * application.</p> */ TerminateEnvByForce?: boolean; } export namespace DeleteApplicationMessage { /** * @internal */ export const filterSensitiveLog = (obj: DeleteApplicationMessage): any => ({ ...obj, }); } /** * <p>Unable to perform the specified operation because another operation that effects an * element in this activity is already in progress.</p> */ export interface OperationInProgressException extends __SmithyException, $MetadataBearer { name: "OperationInProgressException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace OperationInProgressException { /** * @internal */ export const filterSensitiveLog = (obj: OperationInProgressException): any => ({ ...obj, }); } /** * <p>Request to delete an application version.</p> */ export interface DeleteApplicationVersionMessage { /** * <p>The name of the application to which the version belongs.</p> */ ApplicationName: string | undefined; /** * <p>The label of the version to delete.</p> */ VersionLabel: string | undefined; /** * <p>Set to <code>true</code> to delete the source bundle from your storage bucket. * Otherwise, the application version is deleted only from Elastic Beanstalk and the source * bundle remains in Amazon S3.</p> */ DeleteSourceBundle?: boolean; } export namespace DeleteApplicationVersionMessage { /** * @internal */ export const filterSensitiveLog = (obj: DeleteApplicationVersionMessage): any => ({ ...obj, }); } /** * <p>Unable to delete the Amazon S3 source bundle associated with the application version. * The application version was deleted successfully.</p> */ export interface SourceBundleDeletionException extends __SmithyException, $MetadataBearer { name: "SourceBundleDeletionException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace SourceBundleDeletionException { /** * @internal */ export const filterSensitiveLog = (obj: SourceBundleDeletionException): any => ({ ...obj, }); } /** * <p>Request to delete a configuration template.</p> */ export interface DeleteConfigurationTemplateMessage { /** * <p>The name of the application to delete the configuration template from.</p> */ ApplicationName: string | undefined; /** * <p>The name of the configuration template to delete.</p> */ TemplateName: string | undefined; } export namespace DeleteConfigurationTemplateMessage { /** * @internal */ export const filterSensitiveLog = (obj: DeleteConfigurationTemplateMessage): any => ({ ...obj, }); } /** * <p>Request to delete a draft environment configuration.</p> */ export interface DeleteEnvironmentConfigurationMessage { /** * <p>The name of the application the environment is associated with.</p> */ ApplicationName: string | undefined; /** * <p>The name of the environment to delete the draft configuration from.</p> */ EnvironmentName: string | undefined; } export namespace DeleteEnvironmentConfigurationMessage { /** * @internal */ export const filterSensitiveLog = (obj: DeleteEnvironmentConfigurationMessage): any => ({ ...obj, }); } export interface DeletePlatformVersionRequest { /** * <p>The ARN of the version of the custom platform.</p> */ PlatformArn?: string; } export namespace DeletePlatformVersionRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeletePlatformVersionRequest): any => ({ ...obj, }); } export interface DeletePlatformVersionResult { /** * <p>Detailed information about the version of the custom platform.</p> */ PlatformSummary?: PlatformSummary; } export namespace DeletePlatformVersionResult { /** * @internal */ export const filterSensitiveLog = (obj: DeletePlatformVersionResult): any => ({ ...obj, }); } /** * <p>You cannot delete the platform version because there are still environments running on it.</p> */ export interface PlatformVersionStillReferencedException extends __SmithyException, $MetadataBearer { name: "PlatformVersionStillReferencedException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace PlatformVersionStillReferencedException { /** * @internal */ export const filterSensitiveLog = (obj: PlatformVersionStillReferencedException): any => ({ ...obj, }); } /** * <p>The AWS Elastic Beanstalk quota information for a single resource type in an AWS account. It * reflects the resource's limits for this account.</p> */ export interface ResourceQuota { /** * <p>The maximum number of instances of this Elastic Beanstalk resource type that an AWS account can * use.</p> */ Maximum?: number; } export namespace ResourceQuota { /** * @internal */ export const filterSensitiveLog = (obj: ResourceQuota): any => ({ ...obj, }); } /** * <p>A set of per-resource AWS Elastic Beanstalk quotas associated with an AWS account. They reflect * Elastic Beanstalk resource limits for this account.</p> */ export interface ResourceQuotas { /** * <p>The quota for applications in the AWS account.</p> */ ApplicationQuota?: ResourceQuota; /** * <p>The quota for application versions in the AWS account.</p> */ ApplicationVersionQuota?: ResourceQuota; /** * <p>The quota for environments in the AWS account.</p> */ EnvironmentQuota?: ResourceQuota; /** * <p>The quota for configuration templates in the AWS account.</p> */ ConfigurationTemplateQuota?: ResourceQuota; /** * <p>The quota for custom platforms in the AWS account.</p> */ CustomPlatformQuota?: ResourceQuota; } export namespace ResourceQuotas { /** * @internal */ export const filterSensitiveLog = (obj: ResourceQuotas): any => ({ ...obj, }); } export interface DescribeAccountAttributesResult { /** * <p>The Elastic Beanstalk resource quotas associated with the calling AWS account.</p> */ ResourceQuotas?: ResourceQuotas; } export namespace DescribeAccountAttributesResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAccountAttributesResult): any => ({ ...obj, }); } /** * <p>Request to describe one or more applications.</p> */ export interface DescribeApplicationsMessage { /** * <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to only include * those with the specified names.</p> */ ApplicationNames?: string[]; } export namespace DescribeApplicationsMessage { /** * @internal */ export const filterSensitiveLog = (obj: DescribeApplicationsMessage): any => ({ ...obj, }); } /** * <p>Request to describe application versions.</p> */ export interface DescribeApplicationVersionsMessage { /** * <p>Specify an application name to show only application versions for that * application.</p> */ ApplicationName?: string; /** * <p>Specify a version label to show a specific application version.</p> */ VersionLabels?: string[]; /** * <p>For a paginated request. Specify a maximum number of application versions to include in * each response.</p> * <p>If no <code>MaxRecords</code> is specified, all available application versions are * retrieved in a single response.</p> */ MaxRecords?: number; /** * <p>For a paginated request. Specify a token from a previous response page to retrieve the next response page. All other * parameter values must be identical to the ones specified in the initial request.</p> * <p>If no <code>NextToken</code> is specified, the first page is retrieved.</p> */ NextToken?: string; } export namespace DescribeApplicationVersionsMessage { /** * @internal */ export const filterSensitiveLog = (obj: DescribeApplicationVersionsMessage): any => ({ ...obj, }); } /** * <p>A regular expression representing a restriction on a string configuration option * value.</p> */ export interface OptionRestrictionRegex { /** * <p>The regular expression pattern that a string configuration option value with this * restriction must match.</p> */ Pattern?: string; /** * <p>A unique name representing this regular expression.</p> */ Label?: string; } export namespace OptionRestrictionRegex { /** * @internal */ export const filterSensitiveLog = (obj: OptionRestrictionRegex): any => ({ ...obj, }); } export type ConfigurationOptionValueType = "List" | "Scalar"; /** * <p>Describes the possible values for a configuration option.</p> */ export interface ConfigurationOptionDescription { /** * <p>A unique namespace identifying the option's associated AWS resource.</p> */ Namespace?: string; /** * <p>The name of the configuration option.</p> */ Name?: string; /** * <p>The default value for this configuration option.</p> */ DefaultValue?: string; /** * <p>An indication of which action is required if the value for this configuration option * changes:</p> * <ul> * <li> * <p> * <code>NoInterruption</code> : There is no interruption to the environment or application * availability.</p> * </li> * <li> * <p> * <code>RestartEnvironment</code> : The environment is entirely restarted, all AWS resources * are deleted and recreated, and the environment is unavailable during the * process.</p> * </li> * <li> * <p> * <code>RestartApplicationServer</code> : The environment is available the entire time. * However, a short application outage occurs when the application servers on the running * Amazon EC2 instances are restarted.</p> * </li> * </ul> */ ChangeSeverity?: string; /** * <p>An indication of whether the user defined this configuration option:</p> * <ul> * <li> * <p> * <code>true</code> : This configuration option was defined by the user. It is a valid * choice for specifying if this as an <code>Option to Remove</code> when updating * configuration settings. </p> * </li> * <li> * <p> * <code>false</code> : This configuration was not defined by the user.</p> * </li> * </ul> * <p> Constraint: You can remove only <code>UserDefined</code> options from a configuration. </p> * <p> Valid Values: <code>true</code> | <code>false</code> * </p> */ UserDefined?: boolean; /** * <p>An indication of which type of values this option has and whether it is allowable to * select one or more than one of the possible values:</p> * <ul> * <li> * <p> * <code>Scalar</code> : Values for this option are a single selection from the possible * values, or an unformatted string, or numeric value governed by the * <code>MIN/MAX/Regex</code> constraints.</p> * </li> * <li> * <p> * <code>List</code> : Values for this option are multiple selections from the possible * values.</p> * </li> * <li> * <p> * <code>Boolean</code> : Values for this option are either <code>true</code> or * <code>false</code> .</p> * </li> * <li> * <p> * <code>Json</code> : Values for this option are a JSON representation of a * <code>ConfigDocument</code>.</p> * </li> * </ul> */ ValueType?: ConfigurationOptionValueType | string; /** * <p>If specified, values for the configuration option are selected from this * list.</p> */ ValueOptions?: string[]; /** * <p>If specified, the configuration option must be a numeric value greater than this * value.</p> */ MinValue?: number; /** * <p>If specified, the configuration option must be a numeric value less than this * value.</p> */ MaxValue?: number; /** * <p>If specified, the configuration option must be a string value no longer than this * value.</p> */ MaxLength?: number; /** * <p>If specified, the configuration option must be a string value that satisfies this * regular expression.</p> */ Regex?: OptionRestrictionRegex; } export namespace ConfigurationOptionDescription { /** * @internal */ export const filterSensitiveLog = (obj: ConfigurationOptionDescription): any => ({ ...obj, }); } /** * <p>Describes the settings for a specified configuration set.</p> */ export interface ConfigurationOptionsDescription { /** * <p>The name of the solution stack these configuration options belong to.</p> */ SolutionStackName?: string; /** * <p>The ARN of the platform version.</p> */ PlatformArn?: string; /** * <p> A list of <a>ConfigurationOptionDescription</a>. </p> */ Options?: ConfigurationOptionDescription[]; } export namespace ConfigurationOptionsDescription { /** * @internal */ export const filterSensitiveLog = (obj: ConfigurationOptionsDescription): any => ({ ...obj, }); } /** * <p>Result message containing a list of application version descriptions.</p> */ export interface DescribeConfigurationOptionsMessage { /** * <p>The name of the application associated with the configuration template or environment. * Only needed if you want to describe the configuration options associated with either the * configuration template or environment.</p> */ ApplicationName?: string; /** * <p>The name of the configuration template whose configuration options you want to * describe.</p> */ TemplateName?: string; /** * <p>The name of the environment whose configuration options you want to describe.</p> */ EnvironmentName?: string; /** * <p>The name of the solution stack whose configuration options you want to * describe.</p> */ SolutionStackName?: string; /** * <p>The ARN of the custom platform.</p> */ PlatformArn?: string; /** * <p>If specified, restricts the descriptions to only the specified options.</p> */ Options?: OptionSpecification[]; } export namespace DescribeConfigurationOptionsMessage { /** * @internal */ export const filterSensitiveLog = (obj: DescribeConfigurationOptionsMessage): any => ({ ...obj, }); } /** * <p>The results from a request to change the configuration settings of an * environment.</p> */ export interface ConfigurationSettingsDescriptions { /** * <p> A list of <a>ConfigurationSettingsDescription</a>. </p> */ ConfigurationSettings?: ConfigurationSettingsDescription[]; } export namespace ConfigurationSettingsDescriptions { /** * @internal */ export const filterSensitiveLog = (obj: ConfigurationSettingsDescriptions): any => ({ ...obj, }); } /** * <p>Result message containing all of the configuration settings for a specified solution * stack or configuration template.</p> */ export interface DescribeConfigurationSettingsMessage { /** * <p>The application for the environment or configuration template.</p> */ ApplicationName: string | undefined; /** * <p>The name of the configuration template to describe.</p> * <p> Conditional: You must specify either this parameter or an EnvironmentName, but not * both. If you specify both, AWS Elastic Beanstalk returns an * <code>InvalidParameterCombination</code> error. If you do not specify either, AWS Elastic * Beanstalk returns a <code>MissingRequiredParameter</code> error. </p> */ TemplateName?: string; /** * <p>The name of the environment to describe.</p> * <p> Condition: You must specify either this or a TemplateName, but not both. If you * specify both, AWS Elastic Beanstalk returns an <code>InvalidParameterCombination</code> error. * If you do not specify either, AWS Elastic Beanstalk returns * <code>MissingRequiredParameter</code> error. </p> */ EnvironmentName?: string; } export namespace DescribeConfigurationSettingsMessage { /** * @internal */ export const filterSensitiveLog = (obj: DescribeConfigurationSettingsMessage): any => ({ ...obj, }); } export enum EnvironmentHealthAttribute { All = "All", ApplicationMetrics = "ApplicationMetrics", Causes = "Causes", Color = "Color", HealthStatus = "HealthStatus", InstancesHealth = "InstancesHealth", RefreshedAt = "RefreshedAt", Status = "Status", } /** * <p>See the example below to learn how to create a request body.</p> */ export interface DescribeEnvironmentHealthRequest { /** * <p>Specify the environment by name.</p> * <p>You must specify either this or an EnvironmentName, or both.</p> */ EnvironmentName?: string; /** * <p>Specify the environment by ID.</p> * <p>You must specify either this or an EnvironmentName, or both.</p> */ EnvironmentId?: string; /** * <p>Specify the response elements to return. To retrieve all attributes, set to * <code>All</code>. If no attribute names are specified, returns the name of the * environment.</p> */ AttributeNames?: (EnvironmentHealthAttribute | string)[]; } export namespace DescribeEnvironmentHealthRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEnvironmentHealthRequest): any => ({ ...obj, }); } /** * <p>Represents summary information about the health of an instance. For more information, * see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/health-enhanced-status.html">Health Colors and Statuses</a>.</p> */ export interface InstanceHealthSummary { /** * <p> * <b>Grey.</b> AWS Elastic Beanstalk and the health agent are * reporting no data on an instance.</p> */ NoData?: number; /** * <p> * <b>Grey.</b> AWS Elastic Beanstalk and the health agent are * reporting an insufficient amount of data on an instance.</p> */ Unknown?: number; /** * <p> * <b>Grey.</b> An operation is in progress on an instance within the * command timeout.</p> */ Pending?: number; /** * <p> * <b>Green.</b> An instance is passing health checks and the health * agent is not reporting any problems.</p> */ Ok?: number; /** * <p> * <b>Green.</b> An operation is in progress on an instance.</p> */ Info?: number; /** * <p> * <b>Yellow.</b> The health agent is reporting a moderate number of * request failures or other issues for an instance or environment.</p> */ Warning?: number; /** * <p> * <b>Red.</b> The health agent is reporting a high number of request * failures or other issues for an instance or environment.</p> */ Degraded?: number; /** * <p> * <b>Red.</b> The health agent is reporting a very high number of * request failures or other issues for an instance or environment.</p> */ Severe?: number; } export namespace InstanceHealthSummary { /** * @internal */ export const filterSensitiveLog = (obj: InstanceHealthSummary): any => ({ ...obj, }); } /** * <p>Health details for an AWS Elastic Beanstalk environment.</p> */ export interface DescribeEnvironmentHealthResult { /** * <p>The environment's name.</p> */ EnvironmentName?: string; /** * <p>The <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/health-enhanced-status.html">health status</a> of the * environment. For example, <code>Ok</code>.</p> */ HealthStatus?: string; /** * <p>The environment's operational status. <code>Ready</code>, <code>Launching</code>, * <code>Updating</code>, <code>Terminating</code>, or <code>Terminated</code>.</p> */ Status?: EnvironmentHealth | string; /** * <p>The <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/health-enhanced-status.html">health color</a> of the * environment.</p> */ Color?: string; /** * <p>Descriptions of the data that contributed to the environment's current health * status.</p> */ Causes?: string[]; /** * <p>Application request metrics for the environment.</p> */ ApplicationMetrics?: ApplicationMetrics; /** * <p>Summary health information for the instances in the environment.</p> */ InstancesHealth?: InstanceHealthSummary; /** * <p>The date and time that the health information was retrieved.</p> */ RefreshedAt?: Date; } export namespace DescribeEnvironmentHealthResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEnvironmentHealthResult): any => ({ ...obj, }); } /** * <p>One or more input parameters is not valid. Please correct the input parameters and try * the operation again.</p> */ export interface InvalidRequestException extends __SmithyException, $MetadataBearer { name: "InvalidRequestException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace InvalidRequestException { /** * @internal */ export const filterSensitiveLog = (obj: InvalidRequestException): any => ({ ...obj, }); } /** * <p>Request to list completed and failed managed actions.</p> */ export interface DescribeEnvironmentManagedActionHistoryRequest { /** * <p>The environment ID of the target environment.</p> */ EnvironmentId?: string; /** * <p>The name of the target environment.</p> */ EnvironmentName?: string; /** * <p>The pagination token returned by a previous request.</p> */ NextToken?: string; /** * <p>The maximum number of items to return for a single request.</p> */ MaxItems?: number; } export namespace DescribeEnvironmentManagedActionHistoryRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEnvironmentManagedActionHistoryRequest): any => ({ ...obj, }); } export type FailureType = | "CancellationFailed" | "InternalFailure" | "InvalidEnvironmentState" | "PermissionsError" | "RollbackFailed" | "RollbackSuccessful" | "UpdateCancelled"; /** * <p>The record of a completed or failed managed action.</p> */ export interface ManagedActionHistoryItem { /** * <p>A unique identifier for the managed action.</p> */ ActionId?: string; /** * <p>The type of the managed action.</p> */ ActionType?: ActionType | string; /** * <p>A description of the managed action.</p> */ ActionDescription?: string; /** * <p>If the action failed, the type of failure.</p> */ FailureType?: FailureType | string; /** * <p>The status of the action.</p> */ Status?: ActionHistoryStatus | string; /** * <p>If the action failed, a description of the failure.</p> */ FailureDescription?: string; /** * <p>The date and time that the action started executing.</p> */ ExecutedTime?: Date; /** * <p>The date and time that the action finished executing.</p> */ FinishedTime?: Date; } export namespace ManagedActionHistoryItem { /** * @internal */ export const filterSensitiveLog = (obj: ManagedActionHistoryItem): any => ({ ...obj, }); } /** * <p>A result message containing a list of completed and failed managed actions.</p> */ export interface DescribeEnvironmentManagedActionHistoryResult { /** * <p>A list of completed and failed managed actions.</p> */ ManagedActionHistoryItems?: ManagedActionHistoryItem[]; /** * <p>A pagination token that you pass to <a>DescribeEnvironmentManagedActionHistory</a> to get the next page of * results.</p> */ NextToken?: string; } export namespace DescribeEnvironmentManagedActionHistoryResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEnvironmentManagedActionHistoryResult): any => ({ ...obj, }); } /** * <p>Request to list an environment's upcoming and in-progress managed actions.</p> */ export interface DescribeEnvironmentManagedActionsRequest { /** * <p>The name of the target environment.</p> */ EnvironmentName?: string; /** * <p>The environment ID of the target environment.</p> */ EnvironmentId?: string; /** * <p>To show only actions with a particular status, specify a status.</p> */ Status?: ActionStatus | string; } export namespace DescribeEnvironmentManagedActionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEnvironmentManagedActionsRequest): any => ({ ...obj, }); } /** * <p>The record of an upcoming or in-progress managed action.</p> */ export interface ManagedAction { /** * <p>A unique identifier for the managed action.</p> */ ActionId?: string; /** * <p>A description of the managed action.</p> */ ActionDescription?: string; /** * <p>The type of managed action.</p> */ ActionType?: ActionType | string; /** * <p>The status of the managed action. If the action is <code>Scheduled</code>, you can * apply it immediately with <a>ApplyEnvironmentManagedAction</a>.</p> */ Status?: ActionStatus | string; /** * <p>The start time of the maintenance window in which the managed action will * execute.</p> */ WindowStartTime?: Date; } export namespace ManagedAction { /** * @internal */ export const filterSensitiveLog = (obj: ManagedAction): any => ({ ...obj, }); } /** * <p>The result message containing a list of managed actions.</p> */ export interface DescribeEnvironmentManagedActionsResult { /** * <p>A list of upcoming and in-progress managed actions.</p> */ ManagedActions?: ManagedAction[]; } export namespace DescribeEnvironmentManagedActionsResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEnvironmentManagedActionsResult): any => ({ ...obj, }); } /** * <p>Request to describe the resources in an environment.</p> */ export interface DescribeEnvironmentResourcesMessage { /** * <p>The ID of the environment to retrieve AWS resource usage data.</p> * <p> Condition: You must specify either this or an EnvironmentName, or both. If you do not * specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error. * </p> */ EnvironmentId?: string; /** * <p>The name of the environment to retrieve AWS resource usage data.</p> * <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not * specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error. * </p> */ EnvironmentName?: string; } export namespace DescribeEnvironmentResourcesMessage { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEnvironmentResourcesMessage): any => ({ ...obj, }); } /** * <p>The description of an Amazon EC2 instance.</p> */ export interface Instance { /** * <p>The ID of the Amazon EC2 instance.</p> */ Id?: string; } export namespace Instance { /** * @internal */ export const filterSensitiveLog = (obj: Instance): any => ({ ...obj, }); } /** * <p>Describes an Auto Scaling launch configuration.</p> */ export interface LaunchConfiguration { /** * <p>The name of the launch configuration.</p> */ Name?: string; } export namespace LaunchConfiguration { /** * @internal */ export const filterSensitiveLog = (obj: LaunchConfiguration): any => ({ ...obj, }); } /** * <p>Describes an Amazon EC2 launch template.</p> */ export interface LaunchTemplate { /** * <p>The ID of the launch template.</p> */ Id?: string; } export namespace LaunchTemplate { /** * @internal */ export const filterSensitiveLog = (obj: LaunchTemplate): any => ({ ...obj, }); } /** * <p>Describes a LoadBalancer.</p> */ export interface LoadBalancer { /** * <p>The name of the LoadBalancer.</p> */ Name?: string; } export namespace LoadBalancer { /** * @internal */ export const filterSensitiveLog = (obj: LoadBalancer): any => ({ ...obj, }); } /** * <p>Describes a queue.</p> */ export interface Queue { /** * <p>The name of the queue.</p> */ Name?: string; /** * <p>The URL of the queue.</p> */ URL?: string; } export namespace Queue { /** * @internal */ export const filterSensitiveLog = (obj: Queue): any => ({ ...obj, }); } /** * <p>Describes a trigger.</p> */ export interface Trigger { /** * <p>The name of the trigger.</p> */ Name?: string; } export namespace Trigger { /** * @internal */ export const filterSensitiveLog = (obj: Trigger): any => ({ ...obj, }); } /** * <p>Describes the AWS resources in use by this environment. This data is live.</p> */ export interface EnvironmentResourceDescription { /** * <p>The name of the environment.</p> */ EnvironmentName?: string; /** * <p> The <code>AutoScalingGroups</code> used by this environment. </p> */ AutoScalingGroups?: AutoScalingGroup[]; /** * <p>The Amazon EC2 instances used by this environment.</p> */ Instances?: Instance[]; /** * <p>The Auto Scaling launch configurations in use by this environment.</p> */ LaunchConfigurations?: LaunchConfiguration[]; /** * <p>The Amazon EC2 launch templates in use by this environment.</p> */ LaunchTemplates?: LaunchTemplate[]; /** * <p>The LoadBalancers in use by this environment.</p> */ LoadBalancers?: LoadBalancer[]; /** * <p>The <code>AutoScaling</code> triggers in use by this environment. </p> */ Triggers?: Trigger[]; /** * <p>The queues used by this environment.</p> */ Queues?: Queue[]; } export namespace EnvironmentResourceDescription { /** * @internal */ export const filterSensitiveLog = (obj: EnvironmentResourceDescription): any => ({ ...obj, }); } /** * <p>Result message containing a list of environment resource descriptions.</p> */ export interface EnvironmentResourceDescriptionsMessage { /** * <p> A list of <a>EnvironmentResourceDescription</a>. </p> */ EnvironmentResources?: EnvironmentResourceDescription; } export namespace EnvironmentResourceDescriptionsMessage { /** * @internal */ export const filterSensitiveLog = (obj: EnvironmentResourceDescriptionsMessage): any => ({ ...obj, }); } /** * <p>Request to describe one or more environments.</p> */ export interface DescribeEnvironmentsMessage { /** * <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only * those that are associated with this application.</p> */ ApplicationName?: string; /** * <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only * those that are associated with this application version.</p> */ VersionLabel?: string; /** * <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only * those that have the specified IDs.</p> */ EnvironmentIds?: string[]; /** * <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only * those that have the specified names.</p> */ EnvironmentNames?: string[]; /** * <p>Indicates whether to include deleted environments:</p> * <p> * <code>true</code>: Environments that have been deleted after * <code>IncludedDeletedBackTo</code> are displayed.</p> * <p> * <code>false</code>: Do not include deleted environments.</p> */ IncludeDeleted?: boolean; /** * <p> If specified when <code>IncludeDeleted</code> is set to <code>true</code>, then * environments deleted after this date are displayed. </p> */ IncludedDeletedBackTo?: Date; /** * <p>For a paginated request. Specify a maximum number of environments to include in * each response.</p> * <p>If no <code>MaxRecords</code> is specified, all available environments are * retrieved in a single response.</p> */ MaxRecords?: number; /** * <p>For a paginated request. Specify a token from a previous response page to retrieve the next response page. All other * parameter values must be identical to the ones specified in the initial request.</p> * <p>If no <code>NextToken</code> is specified, the first page is retrieved.</p> */ NextToken?: string; } export namespace DescribeEnvironmentsMessage { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEnvironmentsMessage): any => ({ ...obj, }); } export type EventSeverity = "DEBUG" | "ERROR" | "FATAL" | "INFO" | "TRACE" | "WARN"; /** * <p>Request to retrieve a list of events for an environment.</p> */ export interface DescribeEventsMessage { /** * <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only * those associated with this application.</p> */ ApplicationName?: string; /** * <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those * associated with this application version.</p> */ VersionLabel?: string; /** * <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that * are associated with this environment configuration.</p> */ TemplateName?: string; /** * <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those * associated with this environment.</p> */ EnvironmentId?: string; /** * <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those * associated with this environment.</p> */ EnvironmentName?: string; /** * <p>The ARN of a custom platform version. If specified, AWS Elastic Beanstalk restricts the * returned descriptions to those associated with this custom platform version.</p> */ PlatformArn?: string; /** * <p>If specified, AWS Elastic Beanstalk restricts the described events to include only * those associated with this request ID.</p> */ RequestId?: string; /** * <p>If specified, limits the events returned from this call to include only those with the * specified severity or higher.</p> */ Severity?: EventSeverity | string; /** * <p>If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that * occur on or after this time.</p> */ StartTime?: Date; /** * <p> If specified, AWS Elastic Beanstalk restricts the returned descriptions to those that * occur up to, but not including, the <code>EndTime</code>. </p> */ EndTime?: Date; /** * <p>Specifies the maximum number of events that can be returned, beginning with the most * recent event.</p> */ MaxRecords?: number; /** * <p>Pagination token. If specified, the events return the next batch of results.</p> */ NextToken?: string; } export namespace DescribeEventsMessage { /** * @internal */ export const filterSensitiveLog = (obj: DescribeEventsMessage): any => ({ ...obj, }); } /** * <p>Describes an event.</p> */ export interface EventDescription { /** * <p>The date when the event occurred.</p> */ EventDate?: Date; /** * <p>The event message.</p> */ Message?: string; /** * <p>The application associated with the event.</p> */ ApplicationName?: string; /** * <p>The release label for the application version associated with this event.</p> */ VersionLabel?: string; /** * <p>The name of the configuration associated with this event.</p> */ TemplateName?: string; /** * <p>The name of the environment associated with this event.</p> */ EnvironmentName?: string; /** * <p>The ARN of the platform version.</p> */ PlatformArn?: string; /** * <p>The web service request ID for the activity of this event.</p> */ RequestId?: string; /** * <p>The severity level of this event.</p> */ Severity?: EventSeverity | string; } export namespace EventDescription { /** * @internal */ export const filterSensitiveLog = (obj: EventDescription): any => ({ ...obj, }); } /** * <p>Result message wrapping a list of event descriptions.</p> */ export interface EventDescriptionsMessage { /** * <p> A list of <a>EventDescription</a>. </p> */ Events?: EventDescription[]; /** * <p> If returned, this indicates that there are more results to obtain. Use this token in * the next <a>DescribeEvents</a> call to get the next batch of events. </p> */ NextToken?: string; } export namespace EventDescriptionsMessage { /** * @internal */ export const filterSensitiveLog = (obj: EventDescriptionsMessage): any => ({ ...obj, }); } export enum InstancesHealthAttribute { All = "All", ApplicationMetrics = "ApplicationMetrics", AvailabilityZone = "AvailabilityZone", Causes = "Causes", Color = "Color", Deployment = "Deployment", HealthStatus = "HealthStatus", InstanceType = "InstanceType", LaunchedAt = "LaunchedAt", RefreshedAt = "RefreshedAt", System = "System", } /** * <p>Parameters for a call to <code>DescribeInstancesHealth</code>.</p> */ export interface DescribeInstancesHealthRequest { /** * <p>Specify the AWS Elastic Beanstalk environment by name.</p> */ EnvironmentName?: string; /** * <p>Specify the AWS Elastic Beanstalk environment by ID.</p> */ EnvironmentId?: string; /** * <p>Specifies the response elements you wish to receive. To retrieve all attributes, set to * <code>All</code>. If no attribute names are specified, returns a list of * instances.</p> */ AttributeNames?: (InstancesHealthAttribute | string)[]; /** * <p>Specify the pagination token returned by a previous call.</p> */ NextToken?: string; } export namespace DescribeInstancesHealthRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeInstancesHealthRequest): any => ({ ...obj, }); } /** * <p>Information about an application version deployment.</p> */ export interface Deployment { /** * <p>The version label of the application version in the deployment.</p> */ VersionLabel?: string; /** * <p>The ID of the deployment. This number increases by one each time that you deploy source * code or change instance configuration settings.</p> */ DeploymentId?: number; /** * <p>The status of the deployment:</p> * <ul> * <li> * <p> * <code>In Progress</code> : The deployment is in progress.</p> * </li> * <li> * <p> * <code>Deployed</code> : The deployment succeeded.</p> * </li> * <li> * <p> * <code>Failed</code> : The deployment failed.</p> * </li> * </ul> */ Status?: string; /** * <p>For in-progress deployments, the time that the deployment started.</p> * <p>For completed deployments, the time that the deployment ended.</p> */ DeploymentTime?: Date; } export namespace Deployment { /** * @internal */ export const filterSensitiveLog = (obj: Deployment): any => ({ ...obj, }); } /** * <p>CPU utilization metrics for an instance.</p> */ export interface CPUUtilization { /** * <p>Percentage of time that the CPU has spent in the <code>User</code> state over the last * 10 seconds.</p> */ User?: number; /** * <p>Available on Linux environments only.</p> * <p>Percentage of time that the CPU has spent in the <code>Nice</code> state over the last * 10 seconds.</p> */ Nice?: number; /** * <p>Available on Linux environments only.</p> * <p>Percentage of time that the CPU has spent in the <code>System</code> state over the * last 10 seconds.</p> */ System?: number; /** * <p>Percentage of time that the CPU has spent in the <code>Idle</code> state over the last * 10 seconds.</p> */ Idle?: number; /** * <p>Available on Linux environments only.</p> * <p>Percentage of time that the CPU has spent in the <code>I/O Wait</code> state over the * last 10 seconds.</p> */ IOWait?: number; /** * <p>Available on Linux environments only.</p> * <p>Percentage of time that the CPU has spent in the <code>IRQ</code> state over the last * 10 seconds.</p> */ IRQ?: number; /** * <p>Available on Linux environments only.</p> * <p>Percentage of time that the CPU has spent in the <code>SoftIRQ</code> state over the * last 10 seconds.</p> */ SoftIRQ?: number; /** * <p>Available on Windows environments only.</p> * <p>Percentage of time that the CPU has spent in the <code>Privileged</code> state over the * last 10 seconds.</p> */ Privileged?: number; } export namespace CPUUtilization { /** * @internal */ export const filterSensitiveLog = (obj: CPUUtilization): any => ({ ...obj, }); } /** * <p>CPU utilization and load average metrics for an Amazon EC2 instance.</p> */ export interface SystemStatus { /** * <p>CPU utilization metrics for the instance.</p> */ CPUUtilization?: CPUUtilization; /** * <p>Load average in the last 1-minute, 5-minute, and 15-minute periods. * For more information, see * <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/health-enhanced-metrics.html#health-enhanced-metrics-os">Operating System Metrics</a>.</p> */ LoadAverage?: number[]; } export namespace SystemStatus { /** * @internal */ export const filterSensitiveLog = (obj: SystemStatus): any => ({ ...obj, }); } /** * <p>Detailed health information about an Amazon EC2 instance in your Elastic Beanstalk * environment.</p> */ export interface SingleInstanceHealth { /** * <p>The ID of the Amazon EC2 instance.</p> */ InstanceId?: string; /** * <p>Returns the health status of the specified instance. For more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/health-enhanced-status.html">Health * Colors and Statuses</a>.</p> */ HealthStatus?: string; /** * <p>Represents the color indicator that gives you information about the health of the EC2 * instance. For more information, see <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/health-enhanced-status.html">Health Colors and * Statuses</a>.</p> */ Color?: string; /** * <p>Represents the causes, which provide more information about the current health * status.</p> */ Causes?: string[]; /** * <p>The time at which the EC2 instance was launched.</p> */ LaunchedAt?: Date; /** * <p>Request metrics from your application.</p> */ ApplicationMetrics?: ApplicationMetrics; /** * <p>Operating system metrics from the instance.</p> */ System?: SystemStatus; /** * <p>Information about the most recent deployment to an instance.</p> */ Deployment?: Deployment; /** * <p>The availability zone in which the instance runs.</p> */ AvailabilityZone?: string; /** * <p>The instance's type.</p> */ InstanceType?: string; } export namespace SingleInstanceHealth { /** * @internal */ export const filterSensitiveLog = (obj: SingleInstanceHealth): any => ({ ...obj, }); } /** * <p>Detailed health information about the Amazon EC2 instances in an AWS Elastic Beanstalk * environment.</p> */ export interface DescribeInstancesHealthResult { /** * <p>Detailed health information about each instance.</p> * <p>The output differs slightly between Linux and Windows environments. There is a difference * in the members that are supported under the <code><CPUUtilization></code> type.</p> */ InstanceHealthList?: SingleInstanceHealth[]; /** * <p>The date and time that the health information was retrieved.</p> */ RefreshedAt?: Date; /** * <p>Pagination token for the next page of results, if available.</p> */ NextToken?: string; } export namespace DescribeInstancesHealthResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribeInstancesHealthResult): any => ({ ...obj, }); } export interface DescribePlatformVersionRequest { /** * <p>The ARN of the platform version.</p> */ PlatformArn?: string; } export namespace DescribePlatformVersionRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribePlatformVersionRequest): any => ({ ...obj, }); } /** * <p>A custom AMI available to platforms.</p> */ export interface CustomAmi { /** * <p>The type of virtualization used to create the custom AMI.</p> */ VirtualizationType?: string; /** * <p>THe ID of the image used to create the custom AMI.</p> */ ImageId?: string; } export namespace CustomAmi { /** * @internal */ export const filterSensitiveLog = (obj: CustomAmi): any => ({ ...obj, }); } /** * <p>A framework supported by the platform.</p> */ export interface PlatformFramework { /** * <p>The name of the framework.</p> */ Name?: string; /** * <p>The version of the framework.</p> */ Version?: string; } export namespace PlatformFramework { /** * @internal */ export const filterSensitiveLog = (obj: PlatformFramework): any => ({ ...obj, }); } /** * <p>A programming language supported by the platform.</p> */ export interface PlatformProgrammingLanguage { /** * <p>The name of the programming language.</p> */ Name?: string; /** * <p>The version of the programming language.</p> */ Version?: string; } export namespace PlatformProgrammingLanguage { /** * @internal */ export const filterSensitiveLog = (obj: PlatformProgrammingLanguage): any => ({ ...obj, }); } /** * <p>Detailed information about a platform version.</p> */ export interface PlatformDescription { /** * <p>The ARN of the platform version.</p> */ PlatformArn?: string; /** * <p>The AWS account ID of the person who created the platform version.</p> */ PlatformOwner?: string; /** * <p>The name of the platform version.</p> */ PlatformName?: string; /** * <p>The version of the platform version.</p> */ PlatformVersion?: string; /** * <p>The name of the solution stack used by the platform version.</p> */ SolutionStackName?: string; /** * <p>The status of the platform version.</p> */ PlatformStatus?: PlatformStatus | string; /** * <p>The date when the platform version was created.</p> */ DateCreated?: Date; /** * <p>The date when the platform version was last updated.</p> */ DateUpdated?: Date; /** * <p>The category of the platform version.</p> */ PlatformCategory?: string; /** * <p>The description of the platform version.</p> */ Description?: string; /** * <p>Information about the maintainer of the platform version.</p> */ Maintainer?: string; /** * <p>The operating system used by the platform version.</p> */ OperatingSystemName?: string; /** * <p>The version of the operating system used by the platform version.</p> */ OperatingSystemVersion?: string; /** * <p>The programming languages supported by the platform version.</p> */ ProgrammingLanguages?: PlatformProgrammingLanguage[]; /** * <p>The frameworks supported by the platform version.</p> */ Frameworks?: PlatformFramework[]; /** * <p>The custom AMIs supported by the platform version.</p> */ CustomAmiList?: CustomAmi[]; /** * <p>The tiers supported by the platform version.</p> */ SupportedTierList?: string[]; /** * <p>The additions supported by the platform version.</p> */ SupportedAddonList?: string[]; /** * <p>The state of the platform version in its lifecycle.</p> * <p>Possible values: <code>Recommended</code> | <code>null</code> * </p> * <p>If a null value is returned, the platform version isn't the recommended one for its * branch. Each platform branch has a single recommended platform version, typically the most * recent one.</p> */ PlatformLifecycleState?: string; /** * <p>The platform branch to which the platform version belongs.</p> */ PlatformBranchName?: string; /** * <p>The state of the platform version's branch in its lifecycle.</p> * <p>Possible values: <code>Beta</code> | <code>Supported</code> | <code>Deprecated</code> | * <code>Retired</code> * </p> */ PlatformBranchLifecycleState?: string; } export namespace PlatformDescription { /** * @internal */ export const filterSensitiveLog = (obj: PlatformDescription): any => ({ ...obj, }); } export interface DescribePlatformVersionResult { /** * <p>Detailed information about the platform version.</p> */ PlatformDescription?: PlatformDescription; } export namespace DescribePlatformVersionResult { /** * @internal */ export const filterSensitiveLog = (obj: DescribePlatformVersionResult): any => ({ ...obj, }); } /** * <p>Request to disassociate the operations role from an environment.</p> */ export interface DisassociateEnvironmentOperationsRoleMessage { /** * <p>The name of the environment from which to disassociate the operations role.</p> */ EnvironmentName: string | undefined; } export namespace DisassociateEnvironmentOperationsRoleMessage { /** * @internal */ export const filterSensitiveLog = (obj: DisassociateEnvironmentOperationsRoleMessage): any => ({ ...obj, }); } /** * <p>A list of available AWS Elastic Beanstalk solution stacks.</p> */ export interface ListAvailableSolutionStacksResultMessage { /** * <p>A list of available solution stacks.</p> */ SolutionStacks?: string[]; /** * <p> A list of available solution stacks and their <a>SolutionStackDescription</a>. </p> */ SolutionStackDetails?: SolutionStackDescription[]; } export namespace ListAvailableSolutionStacksResultMessage { /** * @internal */ export const filterSensitiveLog = (obj: ListAvailableSolutionStacksResultMessage): any => ({ ...obj, }); } /** * <p>Describes criteria to restrict a list of results.</p> * <p>For operators that apply a single value to the attribute, the filter is evaluated as * follows: <code>Attribute Operator Values[1]</code> * </p> * <p>Some operators, e.g. <code>in</code>, can apply multiple values. In this case, the filter * is evaluated as a logical union (OR) of applications of the operator to the attribute with * each one of the values: <code>(Attribute Operator Values[1]) OR (Attribute Operator Values[2]) * OR ...</code> * </p> * <p>The valid values for attributes of <code>SearchFilter</code> depend on the API action. For * valid values, see the reference page for the API action you're calling that takes a * <code>SearchFilter</code> parameter.</p> */ export interface SearchFilter { /** * <p>The result attribute to which the filter values are applied. Valid values vary by API * action.</p> */ Attribute?: string; /** * <p>The operator to apply to the <code>Attribute</code> with each of the <code>Values</code>. * Valid values vary by <code>Attribute</code>.</p> */ Operator?: string; /** * <p>The list of values applied to the <code>Attribute</code> and <code>Operator</code> * attributes. Number of values and valid values vary by <code>Attribute</code>.</p> */ Values?: string[]; } export namespace SearchFilter { /** * @internal */ export const filterSensitiveLog = (obj: SearchFilter): any => ({ ...obj, }); } export interface ListPlatformBranchesRequest { /** * <p>Criteria for restricting the resulting list of platform branches. The filter is evaluated * as a logical conjunction (AND) of the separate <code>SearchFilter</code> terms.</p> * <p>The following list shows valid attribute values for each of the <code>SearchFilter</code> * terms. Most operators take a single value. The <code>in</code> and <code>not_in</code> * operators can take multiple values.</p> * <ul> * <li> * <p> * <code>Attribute = BranchName</code>:</p> * <ul> * <li> * <p> * <code>Operator</code>: <code>=</code> | <code>!=</code> | <code>begins_with</code> * | <code>ends_with</code> | <code>contains</code> | <code>in</code> | * <code>not_in</code> * </p> * </li> * </ul> * </li> * <li> * <p> * <code>Attribute = LifecycleState</code>:</p> * <ul> * <li> * <p> * <code>Operator</code>: <code>=</code> | <code>!=</code> | <code>in</code> | * <code>not_in</code> * </p> * </li> * <li> * <p> * <code>Values</code>: <code>beta</code> | <code>supported</code> | * <code>deprecated</code> | <code>retired</code> * </p> * </li> * </ul> * </li> * <li> * <p> * <code>Attribute = PlatformName</code>:</p> * <ul> * <li> * <p> * <code>Operator</code>: <code>=</code> | <code>!=</code> | <code>begins_with</code> * | <code>ends_with</code> | <code>contains</code> | <code>in</code> | * <code>not_in</code> * </p> * </li> * </ul> * </li> * <li> * <p> * <code>Attribute = TierType</code>:</p> * <ul> * <li> * <p> * <code>Operator</code>: <code>=</code> | <code>!=</code> * </p> * </li> * <li> * <p> * <code>Values</code>: <code>WebServer/Standard</code> | <code>Worker/SQS/HTTP</code> * </p> * </li> * </ul> * </li> * </ul> * <p>Array size: limited to 10 <code>SearchFilter</code> objects.</p> * <p>Within each <code>SearchFilter</code> item, the <code>Values</code> array is limited to 10 * items.</p> */ Filters?: SearchFilter[]; /** * <p>The maximum number of platform branch values returned in one call.</p> */ MaxRecords?: number; /** * <p>For a paginated request. Specify a token from a previous response page to retrieve the * next response page. All other parameter values must be identical to the ones specified in the * initial request.</p> * <p>If no <code>NextToken</code> is specified, the first page is retrieved.</p> */ NextToken?: string; } export namespace ListPlatformBranchesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListPlatformBranchesRequest): any => ({ ...obj, }); } /** * <p>Summary information about a platform branch.</p> */ export interface PlatformBranchSummary { /** * <p>The name of the platform to which this platform branch belongs.</p> */ PlatformName?: string; /** * <p>The name of the platform branch.</p> */ BranchName?: string; /** * <p>The support life cycle state of the platform branch.</p> * <p>Possible values: <code>beta</code> | <code>supported</code> | <code>deprecated</code> | * <code>retired</code> * </p> */ LifecycleState?: string; /** * <p>An ordinal number that designates the order in which platform branches have been added to * a platform. This can be helpful, for example, if your code calls the * <code>ListPlatformBranches</code> action and then displays a list of platform * branches.</p> * <p>A larger <code>BranchOrder</code> value designates a newer platform branch within the * platform.</p> */ BranchOrder?: number; /** * <p>The environment tiers that platform versions in this branch support.</p> * <p>Possible values: <code>WebServer/Standard</code> | <code>Worker/SQS/HTTP</code> * </p> */ SupportedTierList?: string[]; } export namespace PlatformBranchSummary { /** * @internal */ export const filterSensitiveLog = (obj: PlatformBranchSummary): any => ({ ...obj, }); } export interface ListPlatformBranchesResult { /** * <p>Summary information about the platform branches.</p> */ PlatformBranchSummaryList?: PlatformBranchSummary[]; /** * <p>In a paginated request, if this value isn't <code>null</code>, it's the token that you can * pass in a subsequent request to get the next response page.</p> */ NextToken?: string; } export namespace ListPlatformBranchesResult { /** * @internal */ export const filterSensitiveLog = (obj: ListPlatformBranchesResult): any => ({ ...obj, }); } /** * <p>Describes criteria to restrict the results when listing platform versions.</p> * <p>The filter is evaluated as follows: <code>Type Operator Values[1]</code> * </p> */ export interface PlatformFilter { /** * <p>The platform version attribute to which the filter values are applied.</p> * <p>Valid values: <code>PlatformName</code> | <code>PlatformVersion</code> | * <code>PlatformStatus</code> | <code>PlatformBranchName</code> | * <code>PlatformLifecycleState</code> | <code>PlatformOwner</code> | * <code>SupportedTier</code> | <code>SupportedAddon</code> | * <code>ProgrammingLanguageName</code> | <code>OperatingSystemName</code> * </p> */ Type?: string; /** * <p>The operator to apply to the <code>Type</code> with each of the * <code>Values</code>.</p> * <p>Valid values: <code>=</code> | <code>!=</code> | * <code><</code> | <code><=</code> | * <code>></code> | <code>>=</code> | * <code>contains</code> | <code>begins_with</code> | <code>ends_with</code> * </p> */ Operator?: string; /** * <p>The list of values applied to the filtering platform version attribute. Only one value is supported * for all current operators.</p> * <p>The following list shows valid filter values for some filter attributes.</p> * <ul> * <li> * <p> * <code>PlatformStatus</code>: <code>Creating</code> | <code>Failed</code> | * <code>Ready</code> | <code>Deleting</code> | <code>Deleted</code> * </p> * </li> * <li> * <p> * <code>PlatformLifecycleState</code>: <code>recommended</code> * </p> * </li> * <li> * <p> * <code>SupportedTier</code>: <code>WebServer/Standard</code> | * <code>Worker/SQS/HTTP</code> * </p> * </li> * <li> * <p> * <code>SupportedAddon</code>: <code>Log/S3</code> | <code>Monitoring/Healthd</code> | * <code>WorkerDaemon/SQSD</code> * </p> * </li> * </ul> */ Values?: string[]; } export namespace PlatformFilter { /** * @internal */ export const filterSensitiveLog = (obj: PlatformFilter): any => ({ ...obj, }); } export interface ListPlatformVersionsRequest { /** * <p>Criteria for restricting the resulting list of platform versions. The filter is * interpreted as a logical conjunction (AND) of the separate <code>PlatformFilter</code> * terms.</p> */ Filters?: PlatformFilter[]; /** * <p>The maximum number of platform version values returned in one call.</p> */ MaxRecords?: number; /** * <p>For a paginated request. Specify a token from a previous response page to retrieve the * next response page. All other parameter values must be identical to the ones specified in the * initial request.</p> * <p>If no <code>NextToken</code> is specified, the first page is retrieved.</p> */ NextToken?: string; } export namespace ListPlatformVersionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListPlatformVersionsRequest): any => ({ ...obj, }); } export interface ListPlatformVersionsResult { /** * <p>Summary information about the platform versions.</p> */ PlatformSummaryList?: PlatformSummary[]; /** * <p>In a paginated request, if this value isn't <code>null</code>, it's the token that you can * pass in a subsequent request to get the next response page.</p> */ NextToken?: string; } export namespace ListPlatformVersionsResult { /** * @internal */ export const filterSensitiveLog = (obj: ListPlatformVersionsResult): any => ({ ...obj, }); } export interface ListTagsForResourceMessage { /** * <p>The Amazon Resource Name (ARN) of the resouce for which a tag list is requested.</p> * <p>Must be the ARN of an Elastic Beanstalk resource.</p> */ ResourceArn: string | undefined; } export namespace ListTagsForResourceMessage { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceMessage): any => ({ ...obj, }); } /** * <p>A resource doesn't exist for the specified Amazon Resource Name (ARN).</p> */ export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer { name: "ResourceNotFoundException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace ResourceNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({ ...obj, }); } export interface ResourceTagsDescriptionMessage { /** * <p>The Amazon Resource Name (ARN) of the resource for which a tag list was requested.</p> */ ResourceArn?: string; /** * <p>A list of tag key-value pairs.</p> */ ResourceTags?: Tag[]; } export namespace ResourceTagsDescriptionMessage { /** * @internal */ export const filterSensitiveLog = (obj: ResourceTagsDescriptionMessage): any => ({ ...obj, }); } /** * <p>The type of the specified Amazon Resource Name (ARN) isn't supported for this operation.</p> */ export interface ResourceTypeNotSupportedException extends __SmithyException, $MetadataBearer { name: "ResourceTypeNotSupportedException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace ResourceTypeNotSupportedException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceTypeNotSupportedException): any => ({ ...obj, }); } /** * <p></p> */ export interface RebuildEnvironmentMessage { /** * <p>The ID of the environment to rebuild.</p> * <p> Condition: You must specify either this or an EnvironmentName, or both. If you do not * specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error. * </p> */ EnvironmentId?: string; /** * <p>The name of the environment to rebuild.</p> * <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not * specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error. * </p> */ EnvironmentName?: string; } export namespace RebuildEnvironmentMessage { /** * @internal */ export const filterSensitiveLog = (obj: RebuildEnvironmentMessage): any => ({ ...obj, }); } export type EnvironmentInfoType = "bundle" | "tail"; /** * <p>Request to retrieve logs from an environment and store them in your Elastic Beanstalk * storage bucket.</p> */ export interface RequestEnvironmentInfoMessage { /** * <p>The ID of the environment of the requested data.</p> * <p>If no such environment is found, <code>RequestEnvironmentInfo</code> returns an * <code>InvalidParameterValue</code> error. </p> * <p>Condition: You must specify either this or an EnvironmentName, or both. If you do not * specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error. * </p> */ EnvironmentId?: string; /** * <p>The name of the environment of the requested data.</p> * <p>If no such environment is found, <code>RequestEnvironmentInfo</code> returns an * <code>InvalidParameterValue</code> error. </p> * <p>Condition: You must specify either this or an EnvironmentId, or both. If you do not * specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error. * </p> */ EnvironmentName?: string; /** * <p>The type of information to request.</p> */ InfoType: EnvironmentInfoType | string | undefined; } export namespace RequestEnvironmentInfoMessage { /** * @internal */ export const filterSensitiveLog = (obj: RequestEnvironmentInfoMessage): any => ({ ...obj, }); } /** * <p></p> */ export interface RestartAppServerMessage { /** * <p>The ID of the environment to restart the server for.</p> * <p> Condition: You must specify either this or an EnvironmentName, or both. If you do not * specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error. * </p> */ EnvironmentId?: string; /** * <p>The name of the environment to restart the server for.</p> * <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not * specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error. * </p> */ EnvironmentName?: string; } export namespace RestartAppServerMessage { /** * @internal */ export const filterSensitiveLog = (obj: RestartAppServerMessage): any => ({ ...obj, }); } /** * <p>Request to download logs retrieved with <a>RequestEnvironmentInfo</a>.</p> */ export interface RetrieveEnvironmentInfoMessage { /** * <p>The ID of the data's environment.</p> * <p>If no such environment is found, returns an <code>InvalidParameterValue</code> * error.</p> * <p>Condition: You must specify either this or an EnvironmentName, or both. If you do not * specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> * error.</p> */ EnvironmentId?: string; /** * <p>The name of the data's environment.</p> * <p> If no such environment is found, returns an <code>InvalidParameterValue</code> error. </p> * <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not * specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error. * </p> */ EnvironmentName?: string; /** * <p>The type of information to retrieve.</p> */ InfoType: EnvironmentInfoType | string | undefined; } export namespace RetrieveEnvironmentInfoMessage { /** * @internal */ export const filterSensitiveLog = (obj: RetrieveEnvironmentInfoMessage): any => ({ ...obj, }); } /** * <p>The information retrieved from the Amazon EC2 instances.</p> */ export interface EnvironmentInfoDescription { /** * <p>The type of information retrieved.</p> */ InfoType?: EnvironmentInfoType | string; /** * <p>The Amazon EC2 Instance ID for this information.</p> */ Ec2InstanceId?: string; /** * <p>The time stamp when this information was retrieved.</p> */ SampleTimestamp?: Date; /** * <p>The retrieved information. Currently contains a presigned Amazon S3 URL. The files are * deleted after 15 minutes.</p> * <p>Anyone in possession of this URL can access the files before they are deleted. Make the * URL available only to trusted parties.</p> */ Message?: string; } export namespace EnvironmentInfoDescription { /** * @internal */ export const filterSensitiveLog = (obj: EnvironmentInfoDescription): any => ({ ...obj, }); } /** * <p>Result message containing a description of the requested environment info.</p> */ export interface RetrieveEnvironmentInfoResultMessage { /** * <p> The <a>EnvironmentInfoDescription</a> of the environment. </p> */ EnvironmentInfo?: EnvironmentInfoDescription[]; } export namespace RetrieveEnvironmentInfoResultMessage { /** * @internal */ export const filterSensitiveLog = (obj: RetrieveEnvironmentInfoResultMessage): any => ({ ...obj, }); } /** * <p>Swaps the CNAMEs of two environments.</p> */ export interface SwapEnvironmentCNAMEsMessage { /** * <p>The ID of the source environment.</p> * <p> Condition: You must specify at least the <code>SourceEnvironmentID</code> or the * <code>SourceEnvironmentName</code>. You may also specify both. If you specify the * <code>SourceEnvironmentId</code>, you must specify the * <code>DestinationEnvironmentId</code>. </p> */ SourceEnvironmentId?: string; /** * <p>The name of the source environment.</p> * <p> Condition: You must specify at least the <code>SourceEnvironmentID</code> or the * <code>SourceEnvironmentName</code>. You may also specify both. If you specify the * <code>SourceEnvironmentName</code>, you must specify the * <code>DestinationEnvironmentName</code>. </p> */ SourceEnvironmentName?: string; /** * <p>The ID of the destination environment.</p> * <p> Condition: You must specify at least the <code>DestinationEnvironmentID</code> or the * <code>DestinationEnvironmentName</code>. You may also specify both. You must specify the * <code>SourceEnvironmentId</code> with the <code>DestinationEnvironmentId</code>. </p> */ DestinationEnvironmentId?: string; /** * <p>The name of the destination environment.</p> * <p> Condition: You must specify at least the <code>DestinationEnvironmentID</code> or the * <code>DestinationEnvironmentName</code>. You may also specify both. You must specify the * <code>SourceEnvironmentName</code> with the <code>DestinationEnvironmentName</code>. * </p> */ DestinationEnvironmentName?: string; } export namespace SwapEnvironmentCNAMEsMessage { /** * @internal */ export const filterSensitiveLog = (obj: SwapEnvironmentCNAMEsMessage): any => ({ ...obj, }); } /** * <p>Request to terminate an environment.</p> */ export interface TerminateEnvironmentMessage { /** * <p>The ID of the environment to terminate.</p> * <p> Condition: You must specify either this or an EnvironmentName, or both. If you do not * specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error. * </p> */ EnvironmentId?: string; /** * <p>The name of the environment to terminate.</p> * <p> Condition: You must specify either this or an EnvironmentId, or both. If you do not * specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error. * </p> */ EnvironmentName?: string; /** * <p>Indicates whether the associated AWS resources should shut down when the environment is * terminated:</p> * <ul> * <li> * <p> * <code>true</code>: The specified environment as well as the associated AWS resources, such * as Auto Scaling group and LoadBalancer, are terminated.</p> * </li> * <li> * <p> * <code>false</code>: AWS Elastic Beanstalk resource management is removed from the * environment, but the AWS resources continue to operate.</p> * </li> * </ul> * <p> For more information, see the <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/ug/"> AWS Elastic Beanstalk User Guide. </a> * </p> * <p> Default: <code>true</code> * </p> * <p> Valid Values: <code>true</code> | <code>false</code> * </p> */ TerminateResources?: boolean; /** * <p>Terminates the target environment even if another environment in the same group is * dependent on it.</p> */ ForceTerminate?: boolean; } export namespace TerminateEnvironmentMessage { /** * @internal */ export const filterSensitiveLog = (obj: TerminateEnvironmentMessage): any => ({ ...obj, }); } /** * <p>Request to update an application.</p> */ export interface UpdateApplicationMessage { /** * <p>The name of the application to update. If no such application is found, * <code>UpdateApplication</code> returns an <code>InvalidParameterValue</code> error. * </p> */ ApplicationName: string | undefined; /** * <p>A new description for the application.</p> * <p>Default: If not specified, AWS Elastic Beanstalk does not update the * description.</p> */ Description?: string; } export namespace UpdateApplicationMessage { /** * @internal */ export const filterSensitiveLog = (obj: UpdateApplicationMessage): any => ({ ...obj, }); } export interface UpdateApplicationResourceLifecycleMessage { /** * <p>The name of the application.</p> */ ApplicationName: string | undefined; /** * <p>The lifecycle configuration.</p> */ ResourceLifecycleConfig: ApplicationResourceLifecycleConfig | undefined; } export namespace UpdateApplicationResourceLifecycleMessage { /** * @internal */ export const filterSensitiveLog = (obj: UpdateApplicationResourceLifecycleMessage): any => ({ ...obj, }); } /** * <p></p> */ export interface UpdateApplicationVersionMessage { /** * <p>The name of the application associated with this version.</p> * <p> If no application is found with this name, <code>UpdateApplication</code> returns an * <code>InvalidParameterValue</code> error.</p> */ ApplicationName: string | undefined; /** * <p>The name of the version to update.</p> * <p>If no application version is found with this label, <code>UpdateApplication</code> * returns an <code>InvalidParameterValue</code> error. </p> */ VersionLabel: string | undefined; /** * <p>A new description for this version.</p> */ Description?: string; } export namespace UpdateApplicationVersionMessage { /** * @internal */ export const filterSensitiveLog = (obj: UpdateApplicationVersionMessage): any => ({ ...obj, }); } /** * <p>The result message containing the options for the specified solution stack.</p> */ export interface UpdateConfigurationTemplateMessage { /** * <p>The name of the application associated with the configuration template to * update.</p> * <p> If no application is found with this name, <code>UpdateConfigurationTemplate</code> * returns an <code>InvalidParameterValue</code> error. </p> */ ApplicationName: string | undefined; /** * <p>The name of the configuration template to update.</p> * <p> If no configuration template is found with this name, * <code>UpdateConfigurationTemplate</code> returns an <code>InvalidParameterValue</code> * error. </p> */ TemplateName: string | undefined; /** * <p>A new description for the configuration.</p> */ Description?: string; /** * <p>A list of configuration option settings to update with the new specified option * value.</p> */ OptionSettings?: ConfigurationOptionSetting[]; /** * <p>A list of configuration options to remove from the configuration set.</p> * <p> Constraint: You can remove only <code>UserDefined</code> configuration options. * </p> */ OptionsToRemove?: OptionSpecification[]; } export namespace UpdateConfigurationTemplateMessage { /** * @internal */ export const filterSensitiveLog = (obj: UpdateConfigurationTemplateMessage): any => ({ ...obj, }); } /** * <p>Request to update an environment.</p> */ export interface UpdateEnvironmentMessage { /** * <p>The name of the application with which the environment is associated.</p> */ ApplicationName?: string; /** * <p>The ID of the environment to update.</p> * <p>If no environment with this ID exists, AWS Elastic Beanstalk returns an * <code>InvalidParameterValue</code> error.</p> * <p>Condition: You must specify either this or an EnvironmentName, or both. If you do not * specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error. * </p> */ EnvironmentId?: string; /** * <p>The name of the environment to update. If no environment with this name exists, AWS * Elastic Beanstalk returns an <code>InvalidParameterValue</code> error. </p> * <p>Condition: You must specify either this or an EnvironmentId, or both. If you do not * specify either, AWS Elastic Beanstalk returns <code>MissingRequiredParameter</code> error. * </p> */ EnvironmentName?: string; /** * <p>The name of the group to which the target environment belongs. Specify a group name * only if the environment's name is specified in an environment manifest and not with the * environment name or environment ID parameters. See <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environment-cfg-manifest.html">Environment Manifest * (env.yaml)</a> for details.</p> */ GroupName?: string; /** * <p>If this parameter is specified, AWS Elastic Beanstalk updates the description of this * environment.</p> */ Description?: string; /** * <p>This specifies the tier to use to update the environment.</p> * <p>Condition: At this time, if you change the tier version, name, or type, AWS Elastic * Beanstalk returns <code>InvalidParameterValue</code> error. </p> */ Tier?: EnvironmentTier; /** * <p>If this parameter is specified, AWS Elastic Beanstalk deploys the named application * version to the environment. If no such application version is found, returns an * <code>InvalidParameterValue</code> error. </p> */ VersionLabel?: string; /** * <p>If this parameter is specified, AWS Elastic Beanstalk deploys this configuration * template to the environment. If no such configuration template is found, AWS Elastic Beanstalk * returns an <code>InvalidParameterValue</code> error. </p> */ TemplateName?: string; /** * <p>This specifies the platform version that the environment will run after the environment * is updated.</p> */ SolutionStackName?: string; /** * <p>The ARN of the platform, if used.</p> */ PlatformArn?: string; /** * <p>If specified, AWS Elastic Beanstalk updates the configuration set associated with the * running environment and sets the specified configuration options to the requested * value.</p> */ OptionSettings?: ConfigurationOptionSetting[]; /** * <p>A list of custom user-defined configuration options to remove from the configuration * set for this environment.</p> */ OptionsToRemove?: OptionSpecification[]; } export namespace UpdateEnvironmentMessage { /** * @internal */ export const filterSensitiveLog = (obj: UpdateEnvironmentMessage): any => ({ ...obj, }); } /** * <p>The number of tags in the resource would exceed the number of tags that each resource * can have.</p> * <p>To calculate this, the operation considers both the number of tags the resource already has * and the tags this operation would add if it succeeded.</p> */ export interface TooManyTagsException extends __SmithyException, $MetadataBearer { name: "TooManyTagsException"; $fault: "client"; /** * <p>The exception error message.</p> */ message?: string; } export namespace TooManyTagsException { /** * @internal */ export const filterSensitiveLog = (obj: TooManyTagsException): any => ({ ...obj, }); } export interface UpdateTagsForResourceMessage { /** * <p>The Amazon Resource Name (ARN) of the resouce to be updated.</p> * <p>Must be the ARN of an Elastic Beanstalk resource.</p> */ ResourceArn: string | undefined; /** * <p>A list of tags to add or update. If a key of an existing tag is added, the tag's value is * updated.</p> * <p>Specify at least one of these parameters: <code>TagsToAdd</code>, * <code>TagsToRemove</code>.</p> */ TagsToAdd?: Tag[]; /** * <p>A list of tag keys to remove. If a tag key doesn't exist, it is silently ignored.</p> * <p>Specify at least one of these parameters: <code>TagsToAdd</code>, * <code>TagsToRemove</code>.</p> */ TagsToRemove?: string[]; } export namespace UpdateTagsForResourceMessage { /** * @internal */ export const filterSensitiveLog = (obj: UpdateTagsForResourceMessage): any => ({ ...obj, }); } export type ValidationSeverity = "error" | "warning"; /** * <p>An error or warning for a desired configuration option value.</p> */ export interface ValidationMessage { /** * <p>A message describing the error or warning.</p> */ Message?: string; /** * <p>An indication of the severity of this message:</p> * <ul> * <li> * <p> * <code>error</code>: This message indicates that this is not a valid setting for an * option.</p> * </li> * <li> * <p> * <code>warning</code>: This message is providing information you should take into * account.</p> * </li> * </ul> */ Severity?: ValidationSeverity | string; /** * <p>The namespace to which the option belongs.</p> */ Namespace?: string; /** * <p>The name of the option.</p> */ OptionName?: string; } export namespace ValidationMessage { /** * @internal */ export const filterSensitiveLog = (obj: ValidationMessage): any => ({ ...obj, }); } /** * <p>Provides a list of validation messages.</p> */ export interface ConfigurationSettingsValidationMessages { /** * <p> A list of <a>ValidationMessage</a>. </p> */ Messages?: ValidationMessage[]; } export namespace ConfigurationSettingsValidationMessages { /** * @internal */ export const filterSensitiveLog = (obj: ConfigurationSettingsValidationMessages): any => ({ ...obj, }); } /** * <p>A list of validation messages for a specified configuration template.</p> */ export interface ValidateConfigurationSettingsMessage { /** * <p>The name of the application that the configuration template or environment belongs * to.</p> */ ApplicationName: string | undefined; /** * <p>The name of the configuration template to validate the settings against.</p> * <p>Condition: You cannot specify both this and an environment name.</p> */ TemplateName?: string; /** * <p>The name of the environment to validate the settings against.</p> * <p>Condition: You cannot specify both this and a configuration template name.</p> */ EnvironmentName?: string; /** * <p>A list of the options and desired values to evaluate.</p> */ OptionSettings: ConfigurationOptionSetting[] | undefined; } export namespace ValidateConfigurationSettingsMessage { /** * @internal */ export const filterSensitiveLog = (obj: ValidateConfigurationSettingsMessage): any => ({ ...obj, }); }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; /** * Provides a WorkSpaces directory in AWS WorkSpaces Service. * * > **NOTE:** AWS WorkSpaces service requires [`workspaces_DefaultRole`](https://docs.aws.amazon.com/workspaces/latest/adminguide/workspaces-access-control.html#create-default-role) IAM role to operate normally. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const workspaces = aws.iam.getPolicyDocument({ * statements: [{ * actions: ["sts:AssumeRole"], * principals: [{ * type: "Service", * identifiers: ["workspaces.amazonaws.com"], * }], * }], * }); * const workspacesDefault = new aws.iam.Role("workspacesDefault", {assumeRolePolicy: workspaces.then(workspaces => workspaces.json)}); * const workspacesDefaultServiceAccess = new aws.iam.RolePolicyAttachment("workspacesDefaultServiceAccess", { * role: workspacesDefault.name, * policyArn: "arn:aws:iam::aws:policy/AmazonWorkSpacesServiceAccess", * }); * const workspacesDefaultSelfServiceAccess = new aws.iam.RolePolicyAttachment("workspacesDefaultSelfServiceAccess", { * role: workspacesDefault.name, * policyArn: "arn:aws:iam::aws:policy/AmazonWorkSpacesSelfServiceAccess", * }); * const exampleVpc = new aws.ec2.Vpc("exampleVpc", {cidrBlock: "10.0.0.0/16"}); * const exampleC = new aws.ec2.Subnet("exampleC", { * vpcId: exampleVpc.id, * availabilityZone: "us-east-1c", * cidrBlock: "10.0.2.0/24", * }); * const exampleD = new aws.ec2.Subnet("exampleD", { * vpcId: exampleVpc.id, * availabilityZone: "us-east-1d", * cidrBlock: "10.0.3.0/24", * }); * const exampleDirectory = new aws.workspaces.Directory("exampleDirectory", { * directoryId: exampleDirectoryservice / directoryDirectory.id, * subnetIds: [ * exampleC.id, * exampleD.id, * ], * tags: { * Example: true, * }, * selfServicePermissions: { * changeComputeType: true, * increaseVolumeSize: true, * rebuildWorkspace: true, * restartWorkspace: true, * switchRunningMode: true, * }, * workspaceAccessProperties: { * deviceTypeAndroid: "ALLOW", * deviceTypeChromeos: "ALLOW", * deviceTypeIos: "ALLOW", * deviceTypeLinux: "DENY", * deviceTypeOsx: "ALLOW", * deviceTypeWeb: "DENY", * deviceTypeWindows: "DENY", * deviceTypeZeroclient: "DENY", * }, * workspaceCreationProperties: { * customSecurityGroupId: aws_security_group.example.id, * defaultOu: "OU=AWS,DC=Workgroup,DC=Example,DC=com", * enableInternetAccess: true, * enableMaintenanceMode: true, * userEnabledAsLocalAdministrator: true, * }, * }, { * dependsOn: [ * workspacesDefaultServiceAccess, * workspacesDefaultSelfServiceAccess, * ], * }); * const exampleA = new aws.ec2.Subnet("exampleA", { * vpcId: exampleVpc.id, * availabilityZone: "us-east-1a", * cidrBlock: "10.0.0.0/24", * }); * const exampleB = new aws.ec2.Subnet("exampleB", { * vpcId: exampleVpc.id, * availabilityZone: "us-east-1b", * cidrBlock: "10.0.1.0/24", * }); * const exampleDirectoryservice_directoryDirectory = new aws.directoryservice.Directory("exampleDirectoryservice/directoryDirectory", { * name: "corp.example.com", * password: "#S1ncerely", * size: "Small", * vpcSettings: { * vpcId: exampleVpc.id, * subnetIds: [ * exampleA.id, * exampleB.id, * ], * }, * }); * ``` * ### IP Groups * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const exampleIpGroup = new aws.workspaces.IpGroup("exampleIpGroup", {}); * const exampleDirectory = new aws.workspaces.Directory("exampleDirectory", { * directoryId: aws_directory_service_directory.example.id, * ipGroupIds: [exampleIpGroup.id], * }); * ``` * * ## Import * * Workspaces directory can be imported using the directory ID, e.g. * * ```sh * $ pulumi import aws:workspaces/directory:Directory main d-4444444444 * ``` */ export class Directory extends pulumi.CustomResource { /** * Get an existing Directory resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: DirectoryState, opts?: pulumi.CustomResourceOptions): Directory { return new Directory(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:workspaces/directory:Directory'; /** * Returns true if the given object is an instance of Directory. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Directory { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Directory.__pulumiType; } /** * The directory alias. */ public /*out*/ readonly alias!: pulumi.Output<string>; /** * The user name for the service account. */ public /*out*/ readonly customerUserName!: pulumi.Output<string>; /** * The directory identifier for registration in WorkSpaces service. */ public readonly directoryId!: pulumi.Output<string>; /** * The name of the directory. */ public /*out*/ readonly directoryName!: pulumi.Output<string>; /** * The directory type. */ public /*out*/ readonly directoryType!: pulumi.Output<string>; /** * The IP addresses of the DNS servers for the directory. */ public /*out*/ readonly dnsIpAddresses!: pulumi.Output<string[]>; /** * The identifier of the IAM role. This is the role that allows Amazon WorkSpaces to make calls to other services, such as Amazon EC2, on your behalf. */ public /*out*/ readonly iamRoleId!: pulumi.Output<string>; /** * The identifiers of the IP access control groups associated with the directory. */ public readonly ipGroupIds!: pulumi.Output<string[]>; /** * The registration code for the directory. This is the code that users enter in their Amazon WorkSpaces client application to connect to the directory. */ public /*out*/ readonly registrationCode!: pulumi.Output<string>; /** * Permissions to enable or disable self-service capabilities. Defined below. */ public readonly selfServicePermissions!: pulumi.Output<outputs.workspaces.DirectorySelfServicePermissions>; /** * The identifiers of the subnets where the directory resides. */ public readonly subnetIds!: pulumi.Output<string[]>; /** * A map of tags assigned to the WorkSpaces directory. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * A map of tags assigned to the resource, including those inherited from the provider . */ public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * Specifies which devices and operating systems users can use to access their WorkSpaces. Defined below. */ public readonly workspaceAccessProperties!: pulumi.Output<outputs.workspaces.DirectoryWorkspaceAccessProperties>; /** * Default properties that are used for creating WorkSpaces. Defined below. */ public readonly workspaceCreationProperties!: pulumi.Output<outputs.workspaces.DirectoryWorkspaceCreationProperties>; /** * The identifier of the security group that is assigned to new WorkSpaces. */ public /*out*/ readonly workspaceSecurityGroupId!: pulumi.Output<string>; /** * Create a Directory resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: DirectoryArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: DirectoryArgs | DirectoryState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as DirectoryState | undefined; inputs["alias"] = state ? state.alias : undefined; inputs["customerUserName"] = state ? state.customerUserName : undefined; inputs["directoryId"] = state ? state.directoryId : undefined; inputs["directoryName"] = state ? state.directoryName : undefined; inputs["directoryType"] = state ? state.directoryType : undefined; inputs["dnsIpAddresses"] = state ? state.dnsIpAddresses : undefined; inputs["iamRoleId"] = state ? state.iamRoleId : undefined; inputs["ipGroupIds"] = state ? state.ipGroupIds : undefined; inputs["registrationCode"] = state ? state.registrationCode : undefined; inputs["selfServicePermissions"] = state ? state.selfServicePermissions : undefined; inputs["subnetIds"] = state ? state.subnetIds : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; inputs["workspaceAccessProperties"] = state ? state.workspaceAccessProperties : undefined; inputs["workspaceCreationProperties"] = state ? state.workspaceCreationProperties : undefined; inputs["workspaceSecurityGroupId"] = state ? state.workspaceSecurityGroupId : undefined; } else { const args = argsOrState as DirectoryArgs | undefined; if ((!args || args.directoryId === undefined) && !opts.urn) { throw new Error("Missing required property 'directoryId'"); } inputs["directoryId"] = args ? args.directoryId : undefined; inputs["ipGroupIds"] = args ? args.ipGroupIds : undefined; inputs["selfServicePermissions"] = args ? args.selfServicePermissions : undefined; inputs["subnetIds"] = args ? args.subnetIds : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["workspaceAccessProperties"] = args ? args.workspaceAccessProperties : undefined; inputs["workspaceCreationProperties"] = args ? args.workspaceCreationProperties : undefined; inputs["alias"] = undefined /*out*/; inputs["customerUserName"] = undefined /*out*/; inputs["directoryName"] = undefined /*out*/; inputs["directoryType"] = undefined /*out*/; inputs["dnsIpAddresses"] = undefined /*out*/; inputs["iamRoleId"] = undefined /*out*/; inputs["registrationCode"] = undefined /*out*/; inputs["tagsAll"] = undefined /*out*/; inputs["workspaceSecurityGroupId"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Directory.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Directory resources. */ export interface DirectoryState { /** * The directory alias. */ alias?: pulumi.Input<string>; /** * The user name for the service account. */ customerUserName?: pulumi.Input<string>; /** * The directory identifier for registration in WorkSpaces service. */ directoryId?: pulumi.Input<string>; /** * The name of the directory. */ directoryName?: pulumi.Input<string>; /** * The directory type. */ directoryType?: pulumi.Input<string>; /** * The IP addresses of the DNS servers for the directory. */ dnsIpAddresses?: pulumi.Input<pulumi.Input<string>[]>; /** * The identifier of the IAM role. This is the role that allows Amazon WorkSpaces to make calls to other services, such as Amazon EC2, on your behalf. */ iamRoleId?: pulumi.Input<string>; /** * The identifiers of the IP access control groups associated with the directory. */ ipGroupIds?: pulumi.Input<pulumi.Input<string>[]>; /** * The registration code for the directory. This is the code that users enter in their Amazon WorkSpaces client application to connect to the directory. */ registrationCode?: pulumi.Input<string>; /** * Permissions to enable or disable self-service capabilities. Defined below. */ selfServicePermissions?: pulumi.Input<inputs.workspaces.DirectorySelfServicePermissions>; /** * The identifiers of the subnets where the directory resides. */ subnetIds?: pulumi.Input<pulumi.Input<string>[]>; /** * A map of tags assigned to the WorkSpaces directory. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A map of tags assigned to the resource, including those inherited from the provider . */ tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Specifies which devices and operating systems users can use to access their WorkSpaces. Defined below. */ workspaceAccessProperties?: pulumi.Input<inputs.workspaces.DirectoryWorkspaceAccessProperties>; /** * Default properties that are used for creating WorkSpaces. Defined below. */ workspaceCreationProperties?: pulumi.Input<inputs.workspaces.DirectoryWorkspaceCreationProperties>; /** * The identifier of the security group that is assigned to new WorkSpaces. */ workspaceSecurityGroupId?: pulumi.Input<string>; } /** * The set of arguments for constructing a Directory resource. */ export interface DirectoryArgs { /** * The directory identifier for registration in WorkSpaces service. */ directoryId: pulumi.Input<string>; /** * The identifiers of the IP access control groups associated with the directory. */ ipGroupIds?: pulumi.Input<pulumi.Input<string>[]>; /** * Permissions to enable or disable self-service capabilities. Defined below. */ selfServicePermissions?: pulumi.Input<inputs.workspaces.DirectorySelfServicePermissions>; /** * The identifiers of the subnets where the directory resides. */ subnetIds?: pulumi.Input<pulumi.Input<string>[]>; /** * A map of tags assigned to the WorkSpaces directory. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Specifies which devices and operating systems users can use to access their WorkSpaces. Defined below. */ workspaceAccessProperties?: pulumi.Input<inputs.workspaces.DirectoryWorkspaceAccessProperties>; /** * Default properties that are used for creating WorkSpaces. Defined below. */ workspaceCreationProperties?: pulumi.Input<inputs.workspaces.DirectoryWorkspaceCreationProperties>; }
the_stack
interface BigInt { /** * Returns a string representation of an object. * @param radix Specifies a radix for converting numeric values to strings. */ toString(radix?: number): string; /** Returns a string representation appropriate to the host environment's current locale. */ toLocaleString(): string; /** Returns the primitive value of the specified object. */ valueOf(): bigint; readonly [Symbol.toStringTag]: "BigInt"; } interface BigIntConstructor { (value?: any): bigint; readonly prototype: BigInt; /** * Interprets the low bits of a BigInt as a 2's-complement signed integer. * All higher bits are discarded. * @param bits The number of low bits to use * @param int The BigInt whose bits to extract */ asIntN(bits: number, int: bigint): bigint; /** * Interprets the low bits of a BigInt as an unsigned integer. * All higher bits are discarded. * @param bits The number of low bits to use * @param int The BigInt whose bits to extract */ asUintN(bits: number, int: bigint): bigint; } declare var BigInt: BigIntConstructor; /** * A typed array of 64-bit signed integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated, an exception is raised. */ interface BigInt64Array { /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** The ArrayBuffer instance referenced by the array. */ readonly buffer: ArrayBufferLike; /** The length in bytes of the array. */ readonly byteLength: number; /** The offset in bytes of the array. */ readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; /** Yields index, value pairs for every entry in the array. */ entries(): IterableIterator<[number, bigint]>; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in the array until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: bigint, start?: number, end?: number): this; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: bigint, index: number, array: BigInt64Array) => any, thisArg?: any): BigInt64Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): bigint | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: bigint, index: number, array: BigInt64Array) => void, thisArg?: any): void; /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. * @param fromIndex The position in this array at which to begin searching for searchElement. */ includes(searchElement: bigint, fromIndex?: number): boolean; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: bigint, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** Yields each index in the array. */ keys(): IterableIterator<number>; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: bigint, fromIndex?: number): number; /** The length of the array. */ readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: bigint, index: number, array: BigInt64Array) => bigint, thisArg?: any): BigInt64Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array) => bigint): bigint; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array) => U, initialValue: U): U; /** Reverses the elements in the array. */ reverse(): this; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: ArrayLike<bigint>, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): BigInt64Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in the array until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: bigint, index: number, array: BigInt64Array) => boolean, thisArg?: any): boolean; /** * Sorts the array. * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. */ sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this; /** * Gets a new BigInt64Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin?: number, end?: number): BigInt64Array; /** Converts the array to a string by using the current locale. */ toLocaleString(): string; /** Returns a string representation of the array. */ toString(): string; /** Yields each value in the array. */ values(): IterableIterator<bigint>; [Symbol.iterator](): IterableIterator<bigint>; readonly [Symbol.toStringTag]: "BigInt64Array"; [index: number]: bigint; } interface BigInt64ArrayConstructor { readonly prototype: BigInt64Array; new(length?: number): BigInt64Array; new(array: Iterable<bigint>): BigInt64Array; new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigInt64Array; /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: bigint[]): BigInt64Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<bigint>): BigInt64Array; from<U>(arrayLike: ArrayLike<U>, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigInt64Array; } declare var BigInt64Array: BigInt64ArrayConstructor; /** * A typed array of 64-bit unsigned integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated, an exception is raised. */ interface BigUint64Array { /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** The ArrayBuffer instance referenced by the array. */ readonly buffer: ArrayBufferLike; /** The length in bytes of the array. */ readonly byteLength: number; /** The offset in bytes of the array. */ readonly byteOffset: number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; /** Yields index, value pairs for every entry in the array. */ entries(): IterableIterator<[number, bigint]>; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in the array until the callbackfn returns false, * or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every(callbackfn: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: bigint, start?: number, end?: number): this; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param callbackfn A function that accepts up to three arguments. The filter method calls * the callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ filter(callbackfn: (value: bigint, index: number, array: BigUint64Array) => any, thisArg?: any): BigUint64Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): bigint | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex(predicate: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: bigint, index: number, array: BigUint64Array) => void, thisArg?: any): void; /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. * @param fromIndex The position in this array at which to begin searching for searchElement. */ includes(searchElement: bigint, fromIndex?: number): boolean; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: bigint, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** Yields each index in the array. */ keys(): IterableIterator<number>; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: bigint, fromIndex?: number): number; /** The length of the array. */ readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map(callbackfn: (value: bigint, index: number, array: BigUint64Array) => bigint, thisArg?: any): BigUint64Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array) => bigint): bigint; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array) => U, initialValue: U): U; /** Reverses the elements in the array. */ reverse(): this; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: ArrayLike<bigint>, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. */ slice(start?: number, end?: number): BigUint64Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls the * callbackfn function for each element in the array until the callbackfn returns true, or until * the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some(callbackfn: (value: bigint, index: number, array: BigUint64Array) => boolean, thisArg?: any): boolean; /** * Sorts the array. * @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order. */ sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this; /** * Gets a new BigUint64Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin?: number, end?: number): BigUint64Array; /** Converts the array to a string by using the current locale. */ toLocaleString(): string; /** Returns a string representation of the array. */ toString(): string; /** Yields each value in the array. */ values(): IterableIterator<bigint>; [Symbol.iterator](): IterableIterator<bigint>; readonly [Symbol.toStringTag]: "BigUint64Array"; [index: number]: bigint; } interface BigUint64ArrayConstructor { readonly prototype: BigUint64Array; new(length?: number): BigUint64Array; new(array: Iterable<bigint>): BigUint64Array; new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): BigUint64Array; /** The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: bigint[]): BigUint64Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like or iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from(arrayLike: ArrayLike<bigint>): BigUint64Array; from<U>(arrayLike: ArrayLike<U>, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigUint64Array; } declare var BigUint64Array: BigUint64ArrayConstructor; interface DataView { /** * Gets the BigInt64 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getBigInt64(byteOffset: number, littleEndian?: boolean): bigint; /** * Gets the BigUint64 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. */ getBigUint64(byteOffset: number, littleEndian?: boolean): bigint; /** * Stores a BigInt64 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setBigInt64(byteOffset: number, value: bigint, littleEndian?: boolean): void; /** * Stores a BigUint64 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void; }
the_stack
import { BabelFileMetadata, parseSync, transformFromAstSync, } from "@babel/core"; import { getTwConfigPath, getTwConfigCache } from "../tailwindConfig"; import xwindplugin from "../babel"; import { resolveXwindConfig } from "../xwindConfig"; import { getHash } from "../utils"; import fs from "fs"; import initTailwindClasses from "../classes/tailwind"; import { Module } from "webpack"; import { composer } from "@xwind/class-utilities"; interface LoaderOptions { config?: string; babel?: { presets?: any[]; plugins?: any[]; }; } const cache = new Map<string, string>(); let $classesHash = ""; let $getTailwindCSS: ReturnType<typeof initTailwindClasses>; export default function loader( this: LoaderContext, source: string | Buffer, sourceMap?: RawSourceMap ): string | Buffer | void | undefined { this.async(); const loaderOptions: LoaderOptions = typeof this.query === "string" ? {} : this.query; const twConfigPath = getTwConfigPath( loaderOptions.config ?? "./tailwind.config.js" ); //remove from cache cache.delete(this.resourcePath); if (typeof source !== "string") { this.callback(null, source, sourceMap); return; } //no need to transform file if it doesn't include xwind if (source.indexOf("xwind") === -1) { this.callback(null, source, sourceMap); return; } const transformResult = transform(source, sourceMap, { resourcePath: this.resourcePath, babelOptions: loaderOptions.babel ?? {}, }); this.addDependency(twConfigPath); this.callback(null, transformResult.code, transformResult.map ?? undefined); if (!transformResult.metadata?.xwind) { return; } const xwindClasses = transformResult.metadata.xwind; const { isNewTwConfig, twConfig } = getTwConfigCache(twConfigPath); const xwindConfig = resolveXwindConfig(twConfigPath, twConfig); if (xwindConfig.mode !== "classes") { return; } cache.set(this.resourcePath, xwindClasses); const classes = composer( [...cache.values()], twConfig.separator ).sort((a, b) => (a > b ? 0 : -1)); const newHash = getHash(classes.join()); if ($classesHash === newHash) { return; } $classesHash = newHash; if (!$getTailwindCSS || isNewTwConfig) { $getTailwindCSS = initTailwindClasses( twConfig, xwindConfig.classes.includeBase ?? true ); } const css = $getTailwindCSS(classes); const output = xwindConfig.classes.output; if (!fs.existsSync(output)) { this.emitError(`Output css file does not exist. path:${output}`); return; } fs.writeFileSync(output, css); } function transform( source: string, sourceMap: RawSourceMap | undefined, { babelOptions, resourcePath, }: { babelOptions: object; resourcePath: string; } ) { const ast = parseSync(source, { ...babelOptions, filename: resourcePath, caller: { name: "xwind" }, }); if (!ast) { throw new Error(`XWIND: could not parse ${resourcePath}.`); } const transformResult = transformFromAstSync(ast, source, { filename: resourcePath, plugins: [xwindplugin], babelrc: false, configFile: false, sourceMaps: true, sourceFileName: resourcePath, inputSourceMap: sourceMap, }); if (!transformResult || !transformResult.code) { throw new Error(`XWIND: could not transform ${resourcePath}.`); } interface Metadata extends BabelFileMetadata { xwind?: string; } const metadata: Metadata | undefined = transformResult?.metadata; return { code: transformResult.code, metadata, map: transformResult.map, }; } export interface StartOfSourceMap { file?: string; sourceRoot?: string; } export interface RawSourceMap extends StartOfSourceMap { version: string | number; sources: string[]; names: string[]; sourcesContent?: string[]; mappings: string; } type loaderCallback = ( err: Error | null, content: string | Buffer, sourceMap?: RawSourceMap, // Optional: The third argument must be a source map that is parsable by this module. meta?: any // Optional: The fourth option, ignored by webpack, can be anything (e.g. some metadata). ) => void; interface LoaderContext { /** * Loader API version. Currently 2. * This is useful for providing backwards compatibility. * Using the version you can specify custom logic or fallbacks for breaking changes. */ version: string; /** * The directory of the module. Can be used as context for resolving other stuff. * In the example: /abc because resource.js is in this directory */ context: string; /** * Starting with webpack 4, the formerly `this.options.context` is provided as `this.rootContext`. */ rootContext: string; /** * The resolved request string. * In the example: "/abc/loader1.js?xyz!/abc/node_modules/loader2/index.js!/abc/resource.js?rrr" */ request: string; /** * A string or any object. The query of the request for the current loader. */ query: string | Object; /** * Extracts given loader options. Optionally, accepts JSON schema as an argument. */ getOptions(schema?: string): Object; /** * A function that can be called synchronously or asynchronously in order to return multiple results. */ callback: loaderCallback; /** * Make this loader async. */ async(): loaderCallback; /** * A data object shared between the pitch and the normal phase. */ data?: Object; /** * Make this loader result cacheable. By default it's not cacheable. * A cacheable loader must have a deterministic result, when inputs and dependencies haven't changed. * This means the loader shouldn't have other dependencies than specified with this.addDependency. * Most loaders are deterministic and cacheable. */ cacheable(flag?: boolean): void; /** * An array of all the loaders. It is writeable in the pitch phase. * loaders = [{request: string, path: string, query: string, module: function}] * * In the example: * [ * { request: "/abc/loader1.js?xyz", * path: "/abc/loader1.js", * query: "?xyz", * module: [Function] * }, * { request: "/abc/node_modules/loader2/index.js", * path: "/abc/node_modules/loader2/index.js", * query: "", * module: [Function] * } * ] */ loaders: any[]; /** * The index in the loaders array of the current loader. * In the example: in loader1: 0, in loader2: 1 */ loaderIndex: number; /** * The resource part of the request, including query. * In the example: "/abc/resource.js?rrr" */ resource: string; /** * The resource file. * In the example: "/abc/resource.js" */ resourcePath: string; /** * The query of the resource. * In the example: "?rrr" */ resourceQuery: string; /** * Target of compilation. Passed from configuration options. * Example values: "web", "node" */ target: | "web" | "webworker" | "async-node" | "node" | "electron-main" | "electron-renderer" | "node-webkit" | string; /** * This boolean is set to true when this is compiled by webpack. * * Loaders were originally designed to also work as Babel transforms. * Therefore if you write a loader that works for both, you can use this property to know if * there is access to additional loaderContext and webpack features. */ webpack: boolean; /** * Should a SourceMap be generated. */ sourceMap: boolean; /** * Emit a warning. */ emitWarning(message: string | Error): void; /** * Emit a error. */ emitError(message: string | Error): void; /** * Resolves the given request to a module, applies all configured loaders and calls * back with the generated source, the sourceMap and the module instance (usually an * instance of NormalModule). Use this function if you need to know the source code * of another module to generate the result. */ loadModule( request: string, callback: ( err: Error | null, source: string, sourceMap: RawSourceMap, module: Module ) => void ): any; /** * Resolve a request like a require expression. */ resolve( context: string, request: string, callback: (err: Error, result: string) => void ): any; /** * Creates a resolve function similar to this.resolve. * Any options under webpack resolve options are possible. They are merged with the configured resolve options. Note that "..." can be used in arrays to extend the value from resolve options, e.g. { extensions: [".sass", "..."] }. * options.dependencyType is an additional option. It allows us to specify the type of dependency, which is used to resolve byDependency from the resolve options. * All dependencies of the resolving operation are automatically added as dependencies to the current module */ getResolve(options: any): string; /** * Adds a file as dependency of the loader result in order to make them watchable. * For example, html-loader uses this technique as it finds src and src-set attributes. * Then, it sets the url's for those attributes as dependencies of the html file that is parsed. */ addDependency(file: string): void; /** * addDependency Alias */ dependency(file: string): void; /** * Add a directory as dependency of the loader result. */ addContextDependency(directory: string): void; /** * Remove all dependencies of the loader result. Even initial dependencies and these of other loaders. Consider using pitch. */ clearDependencies(): void; /** * Emit a file. This is webpack-specific. */ emitFile(name: string, content: string | Buffer, sourceMap: any): void; /** Flag if HMR is enabled */ hot: boolean; /** * Access to the compilation's inputFileSystem property. */ fs: any; /** * Which mode is webpack running. */ mode: "production" | "development" | "none"; }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; /** * Imports a disk image from S3 as a Snapshot. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.ebs.SnapshotImport("example", { * diskContainer: { * format: "VHD", * userBucket: { * s3Bucket: "disk-images", * s3Key: "source.vhd", * }, * }, * roleName: "disk-image-import", * tags: { * Name: "HelloWorld", * }, * }); * ``` */ export class SnapshotImport extends pulumi.CustomResource { /** * Get an existing SnapshotImport resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: SnapshotImportState, opts?: pulumi.CustomResourceOptions): SnapshotImport { return new SnapshotImport(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:ebs/snapshotImport:SnapshotImport'; /** * Returns true if the given object is an instance of SnapshotImport. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is SnapshotImport { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === SnapshotImport.__pulumiType; } /** * Amazon Resource Name (ARN) of the EBS Snapshot. */ public /*out*/ readonly arn!: pulumi.Output<string>; /** * The client-specific data. Detailed below. */ public readonly clientData!: pulumi.Output<outputs.ebs.SnapshotImportClientData | undefined>; /** * The data encryption key identifier for the snapshot. */ public /*out*/ readonly dataEncryptionKeyId!: pulumi.Output<string>; /** * The description of the disk image being imported. */ public readonly description!: pulumi.Output<string>; /** * Information about the disk container. Detailed below. */ public readonly diskContainer!: pulumi.Output<outputs.ebs.SnapshotImportDiskContainer>; /** * Specifies whether the destination snapshot of the imported image should be encrypted. The default KMS key for EBS is used unless you specify a non-default KMS key using KmsKeyId. */ public readonly encrypted!: pulumi.Output<boolean | undefined>; /** * An identifier for the symmetric KMS key to use when creating the encrypted snapshot. This parameter is only required if you want to use a non-default KMS key; if this parameter is not specified, the default KMS key for EBS is used. If a KmsKeyId is specified, the Encrypted flag must also be set. */ public readonly kmsKeyId!: pulumi.Output<string | undefined>; /** * Value from an Amazon-maintained list (`amazon`, `aws-marketplace`, `microsoft`) of snapshot owners. */ public /*out*/ readonly ownerAlias!: pulumi.Output<string>; /** * The AWS account ID of the EBS snapshot owner. */ public /*out*/ readonly ownerId!: pulumi.Output<string>; /** * The name of the IAM Role the VM Import/Export service will assume. This role needs certain permissions. See https://docs.aws.amazon.com/vm-import/latest/userguide/vmie_prereqs.html#vmimport-role. Default: `vmimport` */ public readonly roleName!: pulumi.Output<string | undefined>; /** * A map of tags to assign to the snapshot. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * The size of the drive in GiBs. */ public /*out*/ readonly volumeSize!: pulumi.Output<number>; /** * Create a SnapshotImport resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: SnapshotImportArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: SnapshotImportArgs | SnapshotImportState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as SnapshotImportState | undefined; inputs["arn"] = state ? state.arn : undefined; inputs["clientData"] = state ? state.clientData : undefined; inputs["dataEncryptionKeyId"] = state ? state.dataEncryptionKeyId : undefined; inputs["description"] = state ? state.description : undefined; inputs["diskContainer"] = state ? state.diskContainer : undefined; inputs["encrypted"] = state ? state.encrypted : undefined; inputs["kmsKeyId"] = state ? state.kmsKeyId : undefined; inputs["ownerAlias"] = state ? state.ownerAlias : undefined; inputs["ownerId"] = state ? state.ownerId : undefined; inputs["roleName"] = state ? state.roleName : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; inputs["volumeSize"] = state ? state.volumeSize : undefined; } else { const args = argsOrState as SnapshotImportArgs | undefined; if ((!args || args.diskContainer === undefined) && !opts.urn) { throw new Error("Missing required property 'diskContainer'"); } inputs["clientData"] = args ? args.clientData : undefined; inputs["description"] = args ? args.description : undefined; inputs["diskContainer"] = args ? args.diskContainer : undefined; inputs["encrypted"] = args ? args.encrypted : undefined; inputs["kmsKeyId"] = args ? args.kmsKeyId : undefined; inputs["roleName"] = args ? args.roleName : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["arn"] = undefined /*out*/; inputs["dataEncryptionKeyId"] = undefined /*out*/; inputs["ownerAlias"] = undefined /*out*/; inputs["ownerId"] = undefined /*out*/; inputs["tagsAll"] = undefined /*out*/; inputs["volumeSize"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(SnapshotImport.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering SnapshotImport resources. */ export interface SnapshotImportState { /** * Amazon Resource Name (ARN) of the EBS Snapshot. */ arn?: pulumi.Input<string>; /** * The client-specific data. Detailed below. */ clientData?: pulumi.Input<inputs.ebs.SnapshotImportClientData>; /** * The data encryption key identifier for the snapshot. */ dataEncryptionKeyId?: pulumi.Input<string>; /** * The description of the disk image being imported. */ description?: pulumi.Input<string>; /** * Information about the disk container. Detailed below. */ diskContainer?: pulumi.Input<inputs.ebs.SnapshotImportDiskContainer>; /** * Specifies whether the destination snapshot of the imported image should be encrypted. The default KMS key for EBS is used unless you specify a non-default KMS key using KmsKeyId. */ encrypted?: pulumi.Input<boolean>; /** * An identifier for the symmetric KMS key to use when creating the encrypted snapshot. This parameter is only required if you want to use a non-default KMS key; if this parameter is not specified, the default KMS key for EBS is used. If a KmsKeyId is specified, the Encrypted flag must also be set. */ kmsKeyId?: pulumi.Input<string>; /** * Value from an Amazon-maintained list (`amazon`, `aws-marketplace`, `microsoft`) of snapshot owners. */ ownerAlias?: pulumi.Input<string>; /** * The AWS account ID of the EBS snapshot owner. */ ownerId?: pulumi.Input<string>; /** * The name of the IAM Role the VM Import/Export service will assume. This role needs certain permissions. See https://docs.aws.amazon.com/vm-import/latest/userguide/vmie_prereqs.html#vmimport-role. Default: `vmimport` */ roleName?: pulumi.Input<string>; /** * A map of tags to assign to the snapshot. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The size of the drive in GiBs. */ volumeSize?: pulumi.Input<number>; } /** * The set of arguments for constructing a SnapshotImport resource. */ export interface SnapshotImportArgs { /** * The client-specific data. Detailed below. */ clientData?: pulumi.Input<inputs.ebs.SnapshotImportClientData>; /** * The description of the disk image being imported. */ description?: pulumi.Input<string>; /** * Information about the disk container. Detailed below. */ diskContainer: pulumi.Input<inputs.ebs.SnapshotImportDiskContainer>; /** * Specifies whether the destination snapshot of the imported image should be encrypted. The default KMS key for EBS is used unless you specify a non-default KMS key using KmsKeyId. */ encrypted?: pulumi.Input<boolean>; /** * An identifier for the symmetric KMS key to use when creating the encrypted snapshot. This parameter is only required if you want to use a non-default KMS key; if this parameter is not specified, the default KMS key for EBS is used. If a KmsKeyId is specified, the Encrypted flag must also be set. */ kmsKeyId?: pulumi.Input<string>; /** * The name of the IAM Role the VM Import/Export service will assume. This role needs certain permissions. See https://docs.aws.amazon.com/vm-import/latest/userguide/vmie_prereqs.html#vmimport-role. Default: `vmimport` */ roleName?: pulumi.Input<string>; /** * A map of tags to assign to the snapshot. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; }
the_stack
import Immutable = require('seamless-immutable'); // Test types interface User { firstName: string; lastName: string; } interface Address { line1: string; } interface ExtendedUser extends User { address: Address; } // A result type for asMutable({ deep: false } | undefined) interface NonDeepMutableExtendedUser { firstName: string; lastName: string; address: Immutable.Immutable<Address>; } // // Constructors // --------------------------------------------------------------- { interface User { firstName: string; lastName: string; } const arrayOfNumbers1: Immutable.Immutable<number[]> = Immutable.from([0, 2]); const arrayOfNumbers2: Immutable.Immutable<number[]> = Immutable([0, 2]); const user1: Immutable.Immutable<User> = Immutable.from({ firstName: 'Angry', lastName: 'Monkey' }); const user2: Immutable.Immutable<User> = Immutable({ firstName: 'Angry', lastName: 'Monkey' }); const error: Error = Immutable.ImmutableError('error'); const date: Immutable.ImmutableDate = Immutable(new Date()); // Constructing with a promise wraps the result value as an immutable const promise = new Promise<User>(resolve => resolve({ firstName: 'Angry', lastName: 'Monkey', })); const immutablePromise = Immutable(promise); immutablePromise.then((user: Immutable.Immutable<User>) => user.asMutable()); // Construction with Immutable() multiple times only creates an Immutable once const user3: Immutable.Immutable<User> = Immutable(Immutable(Immutable({ firstName: 'Angry', lastName: 'Monkey', }))); user3.asMutable(); // Can't call asMutable() multiple times since there is only one level of immutability // user3.asMutable().asMutable(); // Primitives are not made immutable const str: string = Immutable("Hello World"); const num: number = Immutable(123); const bool: boolean = Immutable(true); const sym: symbol = Immutable(Symbol("A symbol")); const undef: undefined = Immutable(undefined); const nul: null = Immutable(null); const fun: () => User = Immutable((): User => ({ firstName: 'Angry', lastName: 'Monkey', })); } // // Static utilities // --------------------------------------------------------------- { const isImmutable: boolean = Immutable.isImmutable(Immutable.from([0, 2])); const user1: Immutable.Immutable<User> = Immutable.from({ firstName: 'Angry', lastName: 'Monkey' }); const users: Immutable.Immutable<string[]> = Immutable.from(['Angry']); const replacedUser01 = Immutable.replace(user1, { firstName: 'Super', lastName: 'Monkey' }); const replacedUser02 = Immutable.replace(user1, { firstName: 'Super', lastName: 'Monkey' }, { deep: true }); // $ExpectError user1.firstName = 'Untouchable'; // asMutable on object const mutableObject = Immutable.asMutable(user1); mutableObject.firstName = 'Sedated'; // $ExpectError users.push('Super'); // asMutable on array const mutableArray = Immutable.asMutable(users); mutableArray.push('Super'); } // // Instance syntax: immutable array // --------------------------------------------------------------- { const array: Immutable.Immutable<User[]> = Immutable.from([ { firstName: 'Angry', lastName: 'Monkey' } ]); const immutableElement: Immutable.Immutable<User> = array[0]; // $ExpectError immutableElement.firstName = 'Krusty'; const asMutableDefault: Array<Immutable.Immutable<User>> = array.asMutable(); // Can't mutate beyond 1 level deep (in this case only the array itself is mutable, not the items) // $ExpectError asMutableDefault[0].firstName = 'Krusty'; const asMutableNotDeep: Array<Immutable.Immutable<User>> = array.asMutable({ deep: false }); // Can't mutate beyond 1 level deep (in this case only the array itself is mutable, not the items) // $ExpectError asMutableNotDeep[0].firstName = 'Krusty'; // Can mutate at any depth const asMutableDeep: User[] = array.asMutable({ deep: true }); asMutableDeep[0].firstName = 'Krusty'; const opaqueMutableParam = { deep: true }; const asMutableOpaque: Array<User | Immutable.Immutable<User>> = array.asMutable(opaqueMutableParam); // keys. Call the mutable array's 'keys' to ensure compatability const mutableKeys = array.asMutable().keys(); const keys: typeof mutableKeys = array.keys(); // map. Call the mutable array's 'map' with the same function to ensure compatability. Make sure the output array is immutable. interface FirstName { firstNameOnly: string; } array.asMutable().map((value: User) => ({ firstNameOnly: value.firstName })); array .asMutable() .map((value: User, index) => ({ firstNameOnly: value.firstName, index })); array.asMutable().map((value: User, index, allUsers: User[]) => ({ firstNameOnly: value.firstName, index, allUsers, })); const map: Immutable.Immutable<FirstName[]> = array.map((value: User) => ({ firstNameOnly: value.firstName })); map.asMutable(); // filter. Call the mutable array's 'filter' with the same function to ensure compatability. Make sure the output array is immutable. array.asMutable().filter((value: User) => value.firstName === 'test'); const filter: Immutable.Immutable<User[]> = array.filter((value: User, index: number) => value.firstName === 'test'); filter.asMutable(); // slice. Call the mutable array's 'slice' with the same args to ensure compatability. Make sure the output array is immutable. array.asMutable().slice(); const slice1: Immutable.Immutable<User[]> = array.slice(); slice1.asMutable(); array.asMutable().slice(1); const slice2: Immutable.Immutable<User[]> = array.slice(1); slice2.asMutable(); array.asMutable().slice(1, 2); const slice3: Immutable.Immutable<User[]> = array.slice(1, 2); slice3.asMutable(); array.asMutable().slice(undefined, 2); const slice4: Immutable.Immutable<User[]> = array.slice(undefined, 2); slice4.asMutable(); // concat. Call the mutable array's 'concat' with the same args to ensure compatability. Make sure the output array is immutable. array.asMutable().concat(Immutable({ firstName: 'Happy', lastName: 'Cat' })); const concat: Immutable.Immutable<User[]> = array .concat({ firstName: 'Happy', lastName: 'Cat' }, { firstName: 'Silly', lastName: 'Cat' }) .concat([{firstName: 'saucy', lastName: 'Cat'}], {firstName: 'Fussy', lastName: 'Cat'}) .concat([ {firstName: 'Fancy', lastName: 'Cat'}, {firstName: 'Sassy', lastName: 'Cat'}], [{firstName: 'Bossy', lastName: 'Cat'} ]); concat.asMutable(); Immutable.from([1, 2, 3]) .concat(Immutable.from([4, 5, 6]) .concat([7, 8, 9])); // reduce. Call the mutable array's 'reduce' with the same function to ensure compatability. Make sure the output array is immutable. array.asMutable().reduce((previous, current) => ({ ...previous, lastName: current.lastName })); const reduce1: Immutable.Immutable<User> = array.reduce((previous, current) => ({ ...previous, lastName: current.lastName })); reduce1.asMutable(); // NOTE: this is effectively a map function array.asMutable().reduce<FirstName[]>((previous, current) => previous.concat({ firstNameOnly: current.firstName }), []); const reduce2: Immutable.Immutable<FirstName[]> = array.reduce<FirstName[]>((previous, current) => previous.concat({ firstNameOnly: current.firstName }), []); reduce2.asMutable(); // reduceRight. Call the mutable array's 'reduceRight' with the same function to ensure compatability. Make sure the output array is immutable. array.asMutable().reduceRight((previous, current) => ({ ...previous, lastName: current.lastName })); const reduceRight1: Immutable.Immutable<User> = array.reduceRight((previous, current) => ({ ...previous, lastName: current.lastName })); reduceRight1.asMutable(); // NOTE: this is effectively a map function array.asMutable().reduceRight<FirstName[]>((previous, current) => previous.concat({ firstNameOnly: current.firstName }), []); const reduceRight2: Immutable.Immutable<FirstName[]> = array.reduceRight<FirstName[]>((previous, current) => previous.concat({ firstNameOnly: current.firstName }), []); reduceRight2.asMutable(); // asMutable const mutableArray1: User[] = array.asMutable(); const mutableArray2: User[] = array.asMutable({ deep: true }); // flatMap const flatMappedArray: Immutable.Immutable<User[]> = array.flatMap((value: User) => [value, value] ); const flatMappedArrayStrings: Immutable.Immutable<string[]> = array.flatMap((value: User) => value.firstName ); // asObject interface ArrayToObjectResult { theFirstName: string; } const arrayToObject1: Immutable.Immutable<ArrayToObjectResult> = array.asObject<ArrayToObjectResult>((value) => ['theFirstName', value.firstName]); } // // Instance syntax: immutable object // --------------------------------------------------------------- { const immutableUser: Immutable.Immutable<User> = Immutable.from({ firstName: 'Pure', lastName: 'Gold' }); const immutableUserEx: Immutable.Immutable<ExtendedUser> = Immutable.from({ firstName: 'Hairy', lastName: 'Dog', address: { line1: 'Big house' } }); const data: { propertyId: string } = { propertyId: 'user.1' }; // set: property name is strongly checked const updatedUser01: Immutable.Immutable<User> = immutableUser.set('firstName', 'Whirlwind'); const updatedUser02: Immutable.Immutable<User> = immutableUser.set(data.propertyId, 'Whirlwind'); // setIn: property path is strongly checked for up to 5 arguments (helps with refactoring and intellisense) // but will fall back to any[] if there are dynamic arguments on the way const updatedUser11: Immutable.Immutable<ExtendedUser> = immutableUserEx.setIn(['address', 'line1'], 'Small house'); const updatedUser12: Immutable.Immutable<ExtendedUser> = immutableUserEx.setIn([ data.propertyId, 'line1' ], 'Small house'); // asMutable // Can't mutate beyond 1 level deep const mutableUser21 = immutableUserEx.asMutable(); mutableUser21.firstName = 'Krusty'; // $ExpectError mutableUser21.address.line1 = 'Example'; // Can't mutate beyond 1 level deep const mutableUser22 = immutableUserEx.asMutable({ deep: false }); mutableUser22.firstName = 'Krusty'; // $ExpectError mutableUser22.address.line1 = 'Example'; // Can mutate at any depth const mutableUser23: ExtendedUser = immutableUserEx.asMutable({ deep: true }); mutableUser23.firstName = 'Krusty'; mutableUser23.address.line1 = 'Example'; const opaqueMutableParam = { deep: true }; // treats as { deep: boolean } const mutableUser24: ExtendedUser | NonDeepMutableExtendedUser = immutableUserEx.asMutable(opaqueMutableParam); // merge: merged part is strongly checked as a deeply partial object const mergedUser: Immutable.Immutable<User> = immutableUserEx.merge({ address: { line1: 'Small house' }, firstName: 'Jack' }); // accepts merge config const mergedUser2: Immutable.Immutable<User> = immutableUserEx.merge({ address: { line1: 'Small house' }, firstName: 'Jack' }, { mode: 'merge', deep: true }); // update: property name is strongly checked const updatedUser41: Immutable.Immutable<User> = immutableUser.update('firstName', x => x.toLowerCase() + ' Whirlwind'); // the type of the updated value must be explicity specified in case of fallback const updatedUser42: Immutable.Immutable<User> = immutableUser.update<string>(data.propertyId, x => x.toLowerCase() + ' Whirlwind'); // updater function is always called with Immutable object const updatedUser43: Immutable.Immutable<User> = immutableUserEx.update('address', address => address.set('line1', 'Small house')); // updateIn: property path is strongly checked for up to 5 arguments (helps with refactoring and intellisense) // but will fall back to any[] if there are dynamic arguments on the way const updatedUser51: Immutable.Immutable<User> = immutableUserEx.updateIn([ 'address', 'line1' ], x => x.toLowerCase() + ' 43'); // the type of the updated value must be explicity specified in case of fallback const updatedUser52: Immutable.Immutable<User> = immutableUserEx.updateIn<string>([ data.propertyId, 'line1' ], x => x.toLowerCase() + ' 43'); // updater function is always called with Immutable object const updatedUser53: Immutable.Immutable<User> = immutableUserEx.updateIn([ 'address' ], address => address.set('line1', 'Small house')); // without const simpleUser1: Immutable.Immutable<User> = immutableUserEx.without('address'); // getIn: propertyPath is strongly typed up to 5 parameters const firstNameWithoutDefault: string = immutableUser.getIn(['firstName']); // infers Immutable<string> const firstNameWithDefault = immutableUser.getIn(['firstName'], ''); // infers Immutable<string> const firstNameWithDynamicPathWithoutDefault = immutableUser.getIn(['first' + 'name']); const firstNameWithDynamicPathWithDefault = immutableUser.getIn(['first' + 'name'], ''); const line1WithoutDefault = immutableUserEx.getIn(['address', 'line1']); const line1WithDefault = immutableUserEx.getIn(['address', 'line1'], ''); // replace const replacedUser01 = immutableUser.replace({ firstName: 'Super', lastName: 'Monkey' }); const replacedUser02 = immutableUser.replace({ firstName: 'Super', lastName: 'Monkey' }, { deep: true }); } // // Instance syntax: immutable date // --------------------------------------------------------------- { // ImmutableDate cannot access mutable methods like setDate, etc, but CAN access getDate(). // Once we make it mutable (i.e, a regular Date), we can use those methods const immutableDate: Immutable.ImmutableDate = Immutable.from(new Date()); // immutableDate.setDate(1); immutableDate.getDate(); immutableDate.asMutable().setDate(1); const immutableDate2: Immutable.ImmutableDate = Immutable(new Date()); // immutableDate2.setDate(1) immutableDate2.getDate(); immutableDate2.asMutable().setDate(1); }
the_stack
import * as mockery from 'mockery'; describe('projects', function () { let api: any; let validators: any; let mock: any; beforeEach(function () { mockery.enable({ useCleanCache: true, warnOnUnregistered: false }); mock = { db: {}, auth: { extractRequestUser: (req) => req.user.user, }, packagedb: {}, assertProjectAccess: jasmine.createSpy('assertProjectAccess'), requireProjectAccess: jasmine .createSpy('requireProjectAccess') .and.returnValue((req, res, next) => next()), effectivePermission: jasmine.createSpy('effectivePermission'), }; // project module mocks mockery.registerMock('../../../auth', { default: mock.auth }); mockery.registerMock('../../../db/projects', mock.db); mockery.registerMock('../../../db/packages', mock.packagedb); mockery.registerMock('./auth', { assertProjectAccess: mock.assertProjectAccess, requireProjectAccess: mock.requireProjectAccess, effectivePermission: mock.effectivePermission, }); // re-silence winston (since this is a clean cache) const winston = require('winston'); winston.remove(winston.transports.Console); // load up the modules and go mockery.registerAllowable('./index'); mockery.registerAllowable('./validators'); api = require('./index'); validators = require('./validators'); }); afterEach(function () { mockery.deregisterAll(); mockery.disable(); }); describe('createProject', function () { it('should insert a valid project', async function () { mock.db.createProject = jasmine .createSpy('createProject') .and.returnValue(1234); mock.auth.getDisplayName = jasmine .createSpy('getDisplayName') .and.callFake( (u) => u === 'pretend-user' && Promise.resolve('Pretender') ); const req = makeDummyRequest(); const res = jasmine.createSpy('res'); const next = jasmine.createSpy('next'); validators.createProject(req, res, next); const p = await api.createProject(req, res); expect(p.projectId).toEqual(1234); }); it('should reject invalid form data', async function () { const req = makeDummyRequest(); req.body.description = undefined; const res = jasmine.createSpy('res'); const next = jasmine.createSpy('next'); await validators.createProject(req, res, next); expect(next.calls.first().args[0].message).toMatch( /Missing.*description/ ); }); it('should validate user existence', async function () { mock.auth.getDisplayName = jasmine .createSpy('getDisplayName') .and.returnValue(Promise.resolve(undefined)); const req = makeDummyRequest(); const res = jasmine.createSpy('res'); const next = jasmine.createSpy('next'); await validators.createProject(req, res, next); expect(next.calls.first().args[0].name).toEqual('RequestError'); expect(next.calls.first().args[0].message).toContain('Contact'); }); function makeDummyRequest() { return { user: { user: 'me', groups: ['abc'], }, body: { title: 'title', version: '9001', description: 'description', plannedRelease: '2000-01-01 01:01:01', contacts: { legal: ['pretend-user'], }, acl: { abc: 'owner' }, metadata: { open_sourcing: true }, }, } as any; } }); describe('patchProject', function () { it('should change the project', async function () { mock.db.getProject = jasmine .createSpy('getProject') .and.returnValue(makeFakeDBProject()); mock.db.patchProject = jasmine .createSpy('getProject') .and.returnValue(Promise.resolve()); const req = makeDummyRequest(); const res = makeDummyResponse({ project_id: 'abcd' }); const next = jasmine.createSpy('next'); req.body.contacts.someone = 'legal'; await validators.patchProject(req, res, next); const p = await api.patchProject(req, res); expect(mock.db.patchProject).toHaveBeenCalled(); const [projectId, changes] = mock.db.patchProject.calls.first().args; expect(p.projectId).toEqual('abcd'); expect(projectId).toEqual('abcd'); expect(changes.contacts.someone).toEqual('legal'); }); it('should validate patched fields', async function () { const req = makeDummyRequest(); const res = makeDummyResponse({ project_id: 'abcd' }); const next = jasmine.createSpy('next'); req.body.notAField = 'wat'; await validators.patchProject(req, res, next); expect(next.calls.first().args[0].message).toContain('not a valid field'); }); function makeDummyRequest() { return { params: { projectId: 'abcd', }, user: { user: 'fake person', groups: [], }, body: { contacts: {}, notAField: undefined, }, } as any; } }); describe('attachPackage', function () { it('should attach an existing package', async function () { mock.packagedb.getPackage = jasmine .createSpy('getPackage') .and.callFake((x) => x === 90 && Promise.resolve(makeFakeDBPackage())); mock.db.updatePackagesUsed = jasmine.createSpy('updatePackagesUsed'); const req = makeDummyRequest(); const res = makeDummyResponse(makeFakeDBProject()); const next = jasmine.createSpy('next'); await validators.attachPackage(req, res, next); const p = await api.attachPackage(req, res); expect(p.packageId).toEqual(90); expect(mock.db.updatePackagesUsed).toHaveBeenCalled(); const [projectId, usages] = mock.db.updatePackagesUsed.calls.first().args; expect(projectId).toEqual('abcd'); expect(usages[usages.length - 1].package_id).toEqual(90); }); it('should create a new package if it did not exist', async function () { // the only difference in this test is we're mocking a different method. // then we pretend it was a new package. ;D // anything that's not mocked will blow up in the actual code (cannot call undefined) mock.packagedb.createPackageRevision = jasmine .createSpy('createPackageRevision') .and.returnValue(Promise.resolve(90)); mock.db.updatePackagesUsed = jasmine.createSpy('updatePackagesUsed'); const req = makeDummyRequest(); req.body.packageId = undefined; const res = makeDummyResponse(makeFakeDBProject()); const next = jasmine.createSpy('next'); await validators.attachPackage(req, res, next); const p = await api.attachPackage(req, res); expect(p.packageId).toEqual(90); expect(mock.packagedb.createPackageRevision).toHaveBeenCalled(); expect(mock.db.updatePackagesUsed).toHaveBeenCalled(); const [projectId, usages] = mock.db.updatePackagesUsed.calls.first().args; expect(projectId).toEqual('abcd'); expect(usages[usages.length - 1].package_id).toEqual(90); }); it('should create a new package revision for field updates', async function () { // similar to the above tests, but return a new package because a field changed. // in this case, the version was modified. mock.packagedb.getPackage = jasmine .createSpy('getPackage') .and.callFake((x) => x === 90 && Promise.resolve(makeFakeDBPackage())); mock.packagedb.createPackageRevision = jasmine .createSpy('createPackageRevision') .and.returnValue(Promise.resolve(90)); mock.packagedb.createPackageRevision = jasmine .createSpy('createPackageRevision') .and.returnValue(Promise.resolve(91)); mock.db.updatePackagesUsed = jasmine.createSpy('updatePackagesUsed'); const req = makeDummyRequest(); req.body.version = '2.0.1'; const res = makeDummyResponse(makeFakeDBProject()); const next = jasmine.createSpy('next'); await validators.attachPackage(req, res, next); const p = await api.attachPackage(req, res); expect(p.packageId).toEqual(91); expect(mock.packagedb.createPackageRevision).toHaveBeenCalled(); expect(mock.db.updatePackagesUsed).toHaveBeenCalled(); const [projectId, usages] = mock.db.updatePackagesUsed.calls.first().args; expect(projectId).toEqual('abcd'); expect(usages[usages.length - 1].package_id).toEqual(91); }); describe('input validation', function () { let req; let res; let next; beforeEach(function () { mock.db.getProject = jasmine .createSpy('getProject') .and.callFake( (x) => x === 'abcd' && Promise.resolve(makeFakeDBProject()) ); mock.packagedb.getPackage = jasmine .createSpy('getPackage') .and.callFake( (x) => x === 90 && Promise.resolve(makeFakeDBPackage()) ); req = makeDummyRequest(); res = jasmine.createSpy('res'); next = jasmine.createSpy('next'); }); it('checks for undefined fields', async function () { req.body.version = undefined; await validators.attachPackage(req, res, next); expect(next.calls.first().args[0].message).toMatch(/Missing.*version/); }); it('checks for empty-like licenses', async function () { req.body.licenseText = ' '; await validators.attachPackage(req, res, next); expect(req.body.licenseText).toBeUndefined(); }); it('checks URL format', async function () { req.body.website = 'not-a-url'; await validators.attachPackage(req, res, next); expect(next.calls.first().args[0].message).toContain('URL'); }); it('looks for license text or name', async function () { req.body.license = undefined; req.body.licenseText = undefined; await validators.attachPackage(req, res, next); expect(next.calls.first().args[0].message).toContain( 'license name or full text' ); }); it('requires usage info', async function () { req = makeDummyRequest(); req.body.usage = undefined; await validators.attachPackage(req, res, next); expect(next.calls.first().args[0].message).toContain( 'usage information' ); }); it('checks for required questions', async function () { req.body.license = 'MyCustomLicense'; req.body.usage.link = undefined; // "linkage" tag is on MyCustomLicense await validators.attachPackage(req, res, next); expect(next.calls.first().args[0].message).toContain( 'question "Linkage"' ); }); it('validates question answers', async function () { req.body.license = 'MyCustomLicense'; req.body.usage.link = 'wat'; // "linkage" tag is on MyCustomLicense await validators.attachPackage(req, res, next); expect(next.calls.first().args[0].message).toContain( 'question "Linkage" is not valid' ); }); it('packageId must be coerced', async function () { req.body.packageId = '90'; await validators.attachPackage(req, res, next); expect(mock.packagedb.getPackage).toHaveBeenCalled(); const [packageId] = mock.packagedb.getPackage.calls.first().args; expect(packageId).toBe(90); }); }); it('should ensure the project itself exists', async function () { mock.db.getProject = jasmine .createSpy('getProject') .and.callFake((x) => x === 'abcd' && Promise.resolve(undefined)); mock.packagedb.getPackage = jasmine .createSpy('getPackage') .and.callFake((x) => x === 90 && Promise.resolve(makeFakeDBPackage())); const req = makeDummyRequest(); const res = jasmine.createSpy('res'); const next = jasmine.createSpy('next'); await validators.attachPackage(req, res, next); expect(next.calls.first().args[0].message).toMatch(/Project.*exist/); }); it('should ensure the package being attached exists', async function () { mock.db.getProject = jasmine .createSpy('getProject') .and.callFake( (x) => x === 'abcd' && Promise.resolve(makeFakeDBProject()) ); mock.packagedb.getPackage = jasmine .createSpy('getPackage') .and.callFake((x) => x === 90 && Promise.resolve(undefined)); const req = makeDummyRequest(); const res = jasmine.createSpy('res'); const next = jasmine.createSpy('next'); await validators.attachPackage(req, res, next); expect(next.calls.first().args[0].message).toMatch(/Package.*exist/); }); function makeDummyRequest() { return { params: { projectId: 'abcd', }, user: { user: 'fake person', groups: [], }, body: { packageId: 90, name: 'pkg', version: '1.2.3', website: 'http://example.com', copyright: '(c) 20xx some person', license: 'MIT', licenseText: undefined, usage: { notes: 'blah blah', link: 'dynamic', modified: false, }, }, } as any; } }); describe('replacePackage', function () { it('replaces a package ID and nothing else', async function () { mock.db.getProject = jasmine .createSpy('getProject') .and.callFake( (x) => x === 'abcd' && Promise.resolve(makeFakeDBProject()) ); mock.db.updatePackagesUsed = jasmine.createSpy('updatePackagesUsed'); const req = makeDummyRequest(); const res = makeDummyResponse(makeFakeDBProject()); const next = jasmine.createSpy('next'); await validators.replacePackage(req, res, next); await api.replacePackage(req, res); expect(mock.db.updatePackagesUsed).toHaveBeenCalled(); const [projectId, usages] = mock.db.updatePackagesUsed.calls.first().args; expect(projectId).toEqual('abcd'); expect(usages.length).toEqual(1); expect(usages[0].package_id).toEqual(91); expect(usages[0].notes).toEqual('blah blah'); }); function makeDummyRequest() { return { params: { projectId: 'abcd', }, user: { user: 'fake person', groups: [], }, body: { oldId: 90, newId: 91, }, }; } }); function makeDummyResponse(project) { return { locals: { project, }, }; } function makeFakeDBProject() { return { project_id: 'abcd', title: 'my project', version: '9001', description: 'my special description', created_on: '2000-01-01 01:01:01', planned_release: '2001-01-01 01:01:01', contacts: { 'fake person': 'legal' }, acl: { owngroup: 'owner' }, packages_used: [ { package_id: 90, modified: true, link: 'dynamic', notes: 'blah blah' }, ], metadata: {}, } as any; } function makeFakeDBPackage() { return { package_id: 90, name: 'pkg', version: '1.2.3', website: 'http://example.com', copyright: '(c) 20xx some person', license: 'MIT', license_text: undefined, } as any; } });
the_stack
import { combineReducers, PayloadAction } from '@reduxjs/toolkit'; import { ChartEditorProps } from 'app/components/ChartEditor'; import { BOARD_UNDO } from 'app/pages/DashBoardPage/constants'; import { BoardInfo, BoardLinkFilter, DeviceType, JumpPanel, WidgetData, WidgetErrorType, WidgetInfo, WidgetPanelParams, } from 'app/pages/DashBoardPage/pages/Board/slice/types'; import { EditBoardState } from 'app/pages/DashBoardPage/pages/BoardEditor/slice/types'; import { getInitBoardInfo } from 'app/pages/DashBoardPage/utils/board'; import { PageInfo } from 'app/pages/MainPage/pages/ViewPage/slice/types'; import { Layout } from 'react-grid-layout'; /** { excludeAction,includeAction } */ import undoable, { includeAction } from 'redux-undo'; import { useInjectReducer } from 'utils/@reduxjs/injectReducer'; import { createSlice } from 'utils/@reduxjs/toolkit'; import { WidgetControllerPanelParams } from './../../Board/slice/types'; import { editBoardStackSlice } from './childSlice/stackSlice'; import { fetchEditBoardDetail, getEditChartWidgetDataAsync, getEditControllerOptions, toUpdateDashboard, } from './thunk'; // BoardInfo // editDashBoardInfoActions const editDashBoardInfoSlice = createSlice({ name: 'editBoard', initialState: getInitBoardInfo({ id: 'default', }) as EditBoardState['boardInfo'], reducers: { initEditBoardInfo(state, action: PayloadAction<BoardInfo>) { const boardInfo = action.payload; Object.keys(boardInfo).forEach(key => { state[key] = boardInfo[key]; }); }, clearEditBoardInfo(state) { const boardInfo = getInitBoardInfo({ id: 'default' }); Object.keys(boardInfo).forEach(key => { state[key] = boardInfo[key]; }); }, changeDashboardEdit(state, action: PayloadAction<boolean>) { state.editing = action.payload; }, changeEditBoardLoading(state, action: PayloadAction<boolean>) { state.loading = action.payload; }, changeFullScreenItem(state, action: PayloadAction<string>) { state.fullScreenItemId = action.payload; }, changeControllerPanel( state, action: PayloadAction<WidgetControllerPanelParams>, ) { state.controllerPanel = action.payload; }, changeLinkagePanel(state, action: PayloadAction<WidgetPanelParams>) { state.linkagePanel = action.payload; }, changeJumpPanel(state, action: PayloadAction<JumpPanel>) { state.jumpPanel = action.payload; }, adjustDashLayouts(state, action: PayloadAction<Layout[]>) { state.layouts = JSON.parse(JSON.stringify(action.payload)); // state.layouts = [...action.payload]; }, changeShowBlockMask(state, action: PayloadAction<boolean>) { state.showBlockMask = action.payload; }, changeBoardDroppable(state, action: PayloadAction<boolean>) { state.isDroppable = action.payload; }, addClipboardWidgets( state, action: PayloadAction<BoardInfo['clipboardWidgets']>, ) { state.clipboardWidgets = action.payload; }, clearClipboardWidgets(state) { state.clipboardWidgets = {}; }, changeChartEditorProps( state, action: PayloadAction<ChartEditorProps | undefined>, ) { state.chartEditorProps = action.payload; }, changeBoardLinkFilter( state, action: PayloadAction<{ boardId: string; triggerId: string; linkFilters?: BoardLinkFilter[]; }>, ) { const { boardId, triggerId, linkFilters } = action.payload; state.linkFilter = state.linkFilter.filter( link => link.triggerWidgetId !== triggerId, ); if (linkFilters) { state.linkFilter = state.linkFilter.concat(linkFilters); } }, changeBoardDevice(state, action: PayloadAction<DeviceType>) { state.deviceType = action.payload; }, }, extraReducers: builder => { // updateDashboard builder.addCase(toUpdateDashboard.pending, state => { state.saving = true; }); builder.addCase(toUpdateDashboard.fulfilled, (state, action) => { state.saving = false; }); builder.addCase(toUpdateDashboard.rejected, state => { state.saving = false; }); //loadEditBoardDetail builder.addCase(fetchEditBoardDetail.pending, state => { state.loading = true; }); builder.addCase(fetchEditBoardDetail.fulfilled, (state, action) => { state.loading = false; }); builder.addCase(fetchEditBoardDetail.rejected, state => { state.loading = false; }); }, }); // widgetInfo // editWidgetInfoActions const widgetInfoRecordSlice = createSlice({ name: 'editBoard', initialState: {} as EditBoardState['widgetInfoRecord'], reducers: { selectWidget( state, action: PayloadAction<{ multipleKey: boolean; id: string; selected: boolean; }>, ) { const { multipleKey, id, selected } = action.payload; if (multipleKey) { state[id].selected = selected; } else { for (let key of Object.keys(state)) { if (key === id) { state[id].selected = selected; } else { state[key].selected = false; } } } }, selectSubWidget(state, action: PayloadAction<string>) { const id = action.payload; if (!state[id].selected) { for (let key of Object.keys(state)) { state[key].selected = false; } state[id].selected = true; } }, renderedWidgets(state, action: PayloadAction<string[]>) { const ids = action.payload; ids.forEach(id => { state[id] && (state[id].rendered = true); }); }, clearSelectedWidgets(state) { for (let key of Object.keys(state)) { state[key].selected = false; state[key].editing = false; } }, openWidgetEditing(state, action: PayloadAction<{ id: string }>) { const { id } = action.payload; for (let key of Object.keys(state)) { state[key].selected = false; } state[id].selected = true; state[id].editing = true; }, closeWidgetEditing(state, action: PayloadAction<string>) { const id = action.payload; if (id) { state[id].selected = false; state[id].editing = false; } else { for (let key of Object.keys(state)) { state[key].selected = false; state[key].editing = false; } } }, addWidgetInfos(state, action: PayloadAction<Record<string, WidgetInfo>>) { const widgetInfoMap = action.payload; const widgetIds = Object.keys(widgetInfoMap); widgetIds.forEach(id => { state[id] = widgetInfoMap[id]; }); }, clearWidgetInfo(state) { Object.keys(state).forEach(id => { delete state[id]; }); }, changeWidgetInLinking( state, action: PayloadAction<{ boardId?: string; widgetId: string; toggle: boolean; }>, ) { const { widgetId, toggle } = action.payload; state[widgetId].inLinking = toggle; }, changePageInfo( state, action: PayloadAction<{ boardId?: string; widgetId: string; pageInfo: Partial<PageInfo> | undefined; }>, ) { const { widgetId, pageInfo } = action.payload; state[widgetId].pageInfo = pageInfo || { pageNo: 1 }; }, setWidgetErrInfo( state, action: PayloadAction<{ boardId?: string; widgetId: string; errInfo?: string; errorType: WidgetErrorType; }>, ) { const { widgetId, errInfo, errorType } = action.payload; let WidgetRrrInfo = state?.[widgetId]?.errInfo; if (!WidgetRrrInfo) return; if (errInfo) { WidgetRrrInfo[errorType] = errInfo; } else { delete WidgetRrrInfo[errorType]; } }, }, extraReducers: builder => { builder.addCase(getEditChartWidgetDataAsync.pending, (state, action) => { const { widgetId } = action.meta.arg; if (!state?.[widgetId]) return; state[widgetId].loading = true; }); builder.addCase(getEditChartWidgetDataAsync.fulfilled, (state, action) => { const { widgetId } = action.meta.arg; if (!state?.[widgetId]) return; state[widgetId].loading = false; }); builder.addCase(getEditChartWidgetDataAsync.rejected, (state, action) => { const { widgetId } = action.meta.arg; if (!state?.[widgetId]) return; state[widgetId].loading = false; }); builder.addCase(getEditControllerOptions.pending, (state, action) => { const widgetId = action.meta.arg; if (!state?.[widgetId]) return; state[widgetId].loading = true; }); builder.addCase(getEditControllerOptions.fulfilled, (state, action) => { const widgetId = action.meta.arg; if (!state?.[widgetId]) return; state[widgetId].loading = false; }); builder.addCase(getEditControllerOptions.rejected, (state, action) => { const widgetId = action.meta.arg; if (!state?.[widgetId]) return; state[widgetId].loading = false; }); }, }); const editWidgetDataSlice = createSlice({ name: 'editBoard', initialState: {} as EditBoardState['widgetDataMap'], reducers: { setWidgetData(state, action: PayloadAction<WidgetData>) { const widgetData = action.payload; state[widgetData.id] = widgetData; }, }, }); export const { actions: editBoardStackActions } = editBoardStackSlice; export const { actions: editDashBoardInfoActions } = editDashBoardInfoSlice; export const { actions: editWidgetInfoActions } = widgetInfoRecordSlice; export const { actions: editWidgetDataActions } = editWidgetDataSlice; const filterActions = [ editBoardStackActions.setBoardToEditStack, editBoardStackActions.updateBoard, editBoardStackActions.toggleAllowOverlap, editBoardStackActions.updateBoardConfig, editBoardStackActions.addWidgets, editBoardStackActions.deleteWidgets, editBoardStackActions.changeAutoBoardWidgetsRect, editBoardStackActions.resizeWidgetEnd, editBoardStackActions.tabsWidgetAddTab, editBoardStackActions.tabsWidgetRemoveTab, editBoardStackActions.updateWidgetConfig, editBoardStackActions.updateWidgetsConfig, editBoardStackActions.changeWidgetsIndex, editBoardStackActions.changeBoardHasQueryControl, editBoardStackActions.changeBoardHasResetControl, editBoardStackActions.toggleLockWidget, ].map(ele => ele.toString()); const editBoardStackReducer = undoable(editBoardStackSlice.reducer, { undoType: BOARD_UNDO.undo, redoType: BOARD_UNDO.redo, ignoreInitialState: true, // filter: excludeAction([configActions.changeSlideEdit(false).type]), // 像 高频的 组件拖拽。resize、select虽然是用户的行为,但是也不能都记录在 快照中.只记录resizeEnd 和 dragEnd 有意义的结果快照 filter: includeAction(filterActions), }); const editBoardReducer = combineReducers({ stack: editBoardStackReducer, boardInfo: editDashBoardInfoSlice.reducer, widgetInfoRecord: widgetInfoRecordSlice.reducer, widgetDataMap: editWidgetDataSlice.reducer, }); export const useEditBoardSlice = () => { useInjectReducer({ key: 'editBoard', reducer: editBoardReducer }); };
the_stack
import { RequestLogicTypes } from '@requestnetwork/types'; import { CurrencyInput, CurrencyDefinition, CurrencyManager, ERC20Currency } from '../src'; const testCasesPerNetwork: Record<string, Record<string, Partial<CurrencyDefinition>>> = { mainnet: { ETH: { symbol: 'ETH', network: 'mainnet' }, SAI: { address: '0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359', decimals: 18, symbol: 'SAI', network: 'mainnet', }, DAI: { address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', decimals: 18, symbol: 'DAI', network: 'mainnet', }, }, evm: { // defaults to mainnet tokens! MATIC: { symbol: 'MATIC', network: 'mainnet', type: RequestLogicTypes.CURRENCY.ERC20 }, FTM: { symbol: 'FTM', network: 'mainnet', type: RequestLogicTypes.CURRENCY.ERC20 }, FUSE: { symbol: 'FUSE', network: 'mainnet', type: RequestLogicTypes.CURRENCY.ERC20 }, 'MATIC-matic': { symbol: 'MATIC', network: 'matic', type: RequestLogicTypes.CURRENCY.ETH }, 'FTM-fantom': { symbol: 'FTM', network: 'fantom', type: RequestLogicTypes.CURRENCY.ETH }, 'FUSE-fuse': { symbol: 'FUSE', network: 'fuse', type: RequestLogicTypes.CURRENCY.ETH }, }, celo: { CELO: { symbol: 'CELO', network: 'celo' }, cUSD: { address: '0x765DE816845861e75A25fCA122bb6898B8B1282a', decimals: 18, symbol: 'cUSD', network: 'celo', }, // different case CUSD: { address: '0x765DE816845861e75A25fCA122bb6898B8B1282a', decimals: 18, symbol: 'cUSD', network: 'celo', }, cGLD: { address: '0x471EcE3750Da237f93B8E339c536989b8978a438', decimals: 18, symbol: 'cGLD', network: 'celo', }, }, rinkeby: { 'ETH-rinkeby': { symbol: 'ETH-rinkeby', network: 'rinkeby' }, CTBK: { address: '0x995d6A8C21F24be1Dd04E105DD0d83758343E258', decimals: 18, symbol: 'CTBK', network: 'rinkeby', }, FAU: { address: '0xFab46E002BbF0b4509813474841E0716E6730136', decimals: 18, symbol: 'FAU', network: 'rinkeby', }, 'fDAIx-rinkeby': { address: '0x745861AeD1EEe363b4AaA5F1994Be40b1e05Ff90', decimals: 18, symbol: 'fDAIx', network: 'rinkeby', }, }, bitcoin: { BTC: { symbol: 'BTC' }, 'BTC-testnet': { symbol: 'BTC-testnet', network: 'testnet' }, }, other: { EUR: { decimals: 2, symbol: 'EUR' }, USD: { decimals: 2, symbol: 'USD' }, }, }; describe('CurrencyManager', () => { let currencyManager: CurrencyManager; beforeEach(() => { currencyManager = CurrencyManager.getDefault(); }); describe('Creating a CurrencyManager', () => { it('can get a default currency manager', () => { expect(currencyManager.from('DAI')).toBeDefined(); }); it('can get the default list of currencies', () => { const list = CurrencyManager.getDefaultList(); expect(list.find((x) => x.symbol === 'DAI')).toBeDefined(); }); it('can instantiate a currency manager based on a currency list', () => { const list: CurrencyInput[] = [ { type: RequestLogicTypes.CURRENCY.ETH, decimals: 18, network: 'anything', symbol: 'ANY' }, ]; currencyManager = new CurrencyManager(list); expect(currencyManager.from('ANY')).toBeDefined(); }); it('fails if there is a duplicate token in the list', () => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const dai = CurrencyManager.getDefaultList().find((x) => x.id === 'DAI-mainnet')!; const list: CurrencyInput[] = [dai, dai, dai, dai]; expect(() => new CurrencyManager(list)).toThrowError('Duplicate found: DAI-mainnet'); }); it('fixes wrong ERC20 address case', () => { const currencyManager = new CurrencyManager([ { type: RequestLogicTypes.CURRENCY.ERC20, symbol: 'FAKE', address: '0x38cf23c52bb4b13f051aec09580a2de845a7fa35', decimals: 18, network: 'private', }, ]); const fake = currencyManager.from('FAKE') as ERC20Currency; // right case expect(fake.address).toBe('0x38cF23C52Bb4B13F051Aec09580a2dE845a7FA35'); // it can match it from right case or wrong expect(currencyManager.fromAddress('0x38cf23c52bb4b13f051aec09580a2de845a7fa35')?.id).toBe( 'FAKE-private', ); expect(currencyManager.fromAddress('0x38cF23C52Bb4B13F051Aec09580a2dE845a7FA35')?.id).toBe( 'FAKE-private', ); }); }); describe('Accessing currencies', () => { it('access a common token by its symbol', () => { expect(currencyManager.from('DAI')).toMatchObject({ symbol: 'DAI', network: 'mainnet', }); expect(currencyManager.fromSymbol('DAI')).toBeDefined(); }); it('access a chain-specific token by its symbol', () => { expect(currencyManager.from('CELO')).toMatchObject({ network: 'celo', }); expect(currencyManager.fromSymbol('CELO')).toMatchObject({ network: 'celo', }); }); it('access a multichain token by its symbol and network', () => { expect(currencyManager.from('DAI-matic')).toMatchObject({ symbol: 'DAI', network: 'matic', }); expect(currencyManager.fromSymbol('DAI-matic')).toBeUndefined(); expect(currencyManager.from('DAI', 'matic')).toMatchObject({ symbol: 'DAI', network: 'matic', }); expect(currencyManager.fromSymbol('DAI', 'matic')).toMatchObject({ symbol: 'DAI', network: 'matic', }); }); it('access a currency by its id', () => { expect(currencyManager.from('ETH-rinkeby-rinkeby')).toMatchObject({ symbol: 'ETH-rinkeby', network: 'rinkeby', }); }); it('access a mainnet token by its address with or without network', () => { expect(currencyManager.from('0x6B175474E89094C44Da98b954EedeAC495271d0F')).toMatchObject({ symbol: 'DAI', network: 'mainnet', }); expect( currencyManager.from('0x6B175474E89094C44Da98b954EedeAC495271d0F', 'mainnet'), ).toMatchObject({ symbol: 'DAI', network: 'mainnet', }); expect( currencyManager.fromAddress('0x6B175474E89094C44Da98b954EedeAC495271d0F'), ).toMatchObject({ symbol: 'DAI', network: 'mainnet', }); expect( currencyManager.fromAddress('0x6B175474E89094C44Da98b954EedeAC495271d0F', 'mainnet'), ).toMatchObject({ symbol: 'DAI', network: 'mainnet', }); }); it('access a mainnet token by its address whatever the case', () => { expect(currencyManager.from('0x6b175474e89094c44da98b954eedeac495271d0f')).toMatchObject({ symbol: 'DAI', network: 'mainnet', }); expect(currencyManager.from('0x6B175474E89094C44DA98B954EEDEAC495271D0F')).toMatchObject({ symbol: 'DAI', network: 'mainnet', }); }); it('access a token by its address and network', () => { expect( currencyManager.from('0xD3b71117E6C1558c1553305b44988cd944e97300', 'matic'), ).toMatchObject({ symbol: 'YEL', network: 'matic', }); expect( currencyManager.from('0xD3b71117E6C1558c1553305b44988cd944e97300', 'fantom'), ).toMatchObject({ symbol: 'YEL', network: 'fantom', }); expect( currencyManager.fromAddress('0xD3b71117E6C1558c1553305b44988cd944e97300', 'matic'), ).toMatchObject({ symbol: 'YEL', network: 'matic', }); expect( currencyManager.fromAddress('0xD3b71117E6C1558c1553305b44988cd944e97300', 'fantom'), ).toMatchObject({ symbol: 'YEL', network: 'fantom', }); }); it('defaults to mainnet for native tokens with a mainnet equivalent', () => { expect(currencyManager.from('MATIC')).toMatchObject({ symbol: 'MATIC', network: 'mainnet', type: RequestLogicTypes.CURRENCY.ERC20, }); expect(currencyManager.from('MATIC-matic')).toMatchObject({ symbol: 'MATIC', network: 'matic', type: RequestLogicTypes.CURRENCY.ETH, }); }); it('returns undefined for empty symbol', () => { expect(currencyManager.fromSymbol('')).toBeUndefined(); }); it('returns undefined and logs a warning on conflict', () => { const warnSpy = jest.spyOn(console, 'warn'); expect(currencyManager.from('0xD3b71117E6C1558c1553305b44988cd944e97300')).toBeUndefined(); expect(warnSpy).toHaveBeenCalledWith( '0xD3b71117E6C1558c1553305b44988cd944e97300 has several matches on matic, fantom. To avoid errors, specify a network.', ); }); it('returns undefined for a known address on another network', () => { expect( currencyManager.fromAddress('0xFab46E002BbF0b4509813474841E0716E6730136'), ).toBeDefined(); expect( currencyManager.fromAddress('0xFab46E002BbF0b4509813474841E0716E6730136', 'rinkeby'), ).toBeDefined(); expect( currencyManager.fromAddress('0xFab46E002BbF0b4509813474841E0716E6730136', 'mainnet'), ).not.toBeDefined(); }); it('returns undefined for undefined or empty string', () => { expect(currencyManager.from(undefined)).toBeUndefined(); expect(currencyManager.from('')).toBeUndefined(); }); describe('fromStorageCurrency', () => { it('can access a ERC20 token from its storage format', () => { expect( currencyManager.fromStorageCurrency({ type: RequestLogicTypes.CURRENCY.ERC20, value: '0x6B175474E89094C44Da98b954EedeAC495271d0F', }), ).toMatchObject({ id: 'DAI-mainnet' }); expect( currencyManager.fromStorageCurrency({ type: RequestLogicTypes.CURRENCY.ERC20, value: '0x6B175474E89094C44Da98b954EedeAC495271d0F', network: 'mainnet', }), ).toMatchObject({ id: 'DAI-mainnet' }); }); it('can access a ERC777 token from its storage format', () => { expect( currencyManager.fromStorageCurrency({ type: RequestLogicTypes.CURRENCY.ERC777, value: '0x745861AeD1EEe363b4AaA5F1994Be40b1e05Ff90', network: 'rinkeby', }), ).toMatchObject({ id: 'fDAIx-rinkeby' }); }); it('can access native tokens from storage format', () => { expect( currencyManager.fromStorageCurrency({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }), ).toMatchObject({ id: 'ETH-mainnet' }); expect( currencyManager.fromStorageCurrency({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }), ).toMatchObject({ id: 'ETH-mainnet' }); expect( currencyManager.fromStorageCurrency({ type: RequestLogicTypes.CURRENCY.ETH, value: 'WRONG!', network: 'mainnet', }), ).toMatchObject({ id: 'ETH-mainnet' }); expect( currencyManager.fromStorageCurrency({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH-rinkeby', network: 'rinkeby', }), ).toMatchObject({ id: 'ETH-rinkeby-rinkeby' }); expect( currencyManager.fromStorageCurrency({ type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', network: 'rinkeby', }), ).toMatchObject({ id: 'ETH-rinkeby-rinkeby' }); }); it('can access fiat currencies from storage format', () => { expect( currencyManager.fromStorageCurrency({ type: RequestLogicTypes.CURRENCY.ISO4217, value: 'EUR', }), ).toMatchObject({ id: 'EUR' }); }); }); }); describe('Extending currencies', () => { it('Can specify metadata type', () => { const currencyManager = new CurrencyManager([ { type: RequestLogicTypes.CURRENCY.ETH, symbol: 'ABCD', decimals: 18, network: 'private', meta: { rate: 0.1, }, }, ]); expect(currencyManager.from('ABCD')?.meta?.rate).toBe(0.1); }); }); describe('Default currencies', () => { Object.entries(testCasesPerNetwork).forEach(([network, testCases]) => { describe(network, () => { Object.entries(testCases).forEach(([symbol, expected]) => { it(`Resolves ${symbol}`, () => { expect(currencyManager.from(symbol)).toMatchObject(expected); }); }); }); }); }); describe('Conflicting currencies', () => { it('TOP', () => { expect(currencyManager.from('TOP')).toMatchObject({ type: RequestLogicTypes.CURRENCY.ISO4217, }); expect(currencyManager.from('TOP', 'mainnet')).toMatchObject({ type: RequestLogicTypes.CURRENCY.ERC20, }); }); it('BOB', () => { expect(currencyManager.from('BOB')).toMatchObject({ type: RequestLogicTypes.CURRENCY.ISO4217, }); expect(currencyManager.from('BOB', 'mainnet')).toMatchObject({ type: RequestLogicTypes.CURRENCY.ERC20, }); }); it('MNT', () => { expect(currencyManager.from('MNT')).toMatchObject({ type: RequestLogicTypes.CURRENCY.ISO4217, }); expect(currencyManager.from('MNT', 'mainnet')).toMatchObject({ type: RequestLogicTypes.CURRENCY.ERC20, }); }); }); describe('Back & forth', () => { // exclude conflicting & native testnet const defaultList = CurrencyManager.getDefaultList().filter( (x) => !['BOB', 'MNT', 'TOP'].includes(x.symbol) && !( (x.type === RequestLogicTypes.CURRENCY.ETH || x.type === RequestLogicTypes.CURRENCY.BTC) && x.symbol.includes('-') ), ); const defaultManager = new CurrencyManager(defaultList); defaultList.forEach((currency) => { it(currency.id, () => { const def = CurrencyManager.fromInput(currency); expect(def).toBeDefined(); expect(def).toEqual(defaultManager.from(def.id)); if ('network' in def) { expect(def).toEqual(defaultManager.from(def.symbol, def.network)); expect(def).toEqual(defaultManager.fromSymbol(def.symbol, def.network)); } expect(def).toEqual( defaultManager.fromStorageCurrency(CurrencyManager.toStorageCurrency(def)), ); }); }); }); describe('Validate addresses', () => { const bitcoinAddresses: Record<string, string> = { mainnet: '1JwZzh9HLK5M4VZ98yBQLeFiGuL97vQvL3', testnet: 'n4VQ5YdHf7hLQ2gWQYYrcxoE5B7nWuDFNF', }; const nearAddresses: Record<string, string> = { aurora: 'requestnetwork.near', 'aurora-testnet': 'requestnetwork.testnet', }; const eip55Addresses: string[] = [ // All Caps '0x52908400098527886E0F7030069857D2E4169EE7', '0x8617E340B3D01FA5F11F306F4090FD50E238070D', // All Lower '0xde709f2102306220921060314715629080e2fb77', '0x27b1fdb04752bbc536007a920d24acb045561c26', // Normal '0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed', '0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359', '0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB', '0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb', ]; const extendedTestCasesPerNetwork: Record< string, Record<string, Partial<CurrencyDefinition>> > = { ...testCasesPerNetwork, aurora: { NEAR: { type: RequestLogicTypes.CURRENCY.ETH, symbol: 'NEAR', network: 'aurora', }, 'NEAR-testnet': { type: RequestLogicTypes.CURRENCY.ETH, symbol: 'NEAR-testnet', network: 'aurora-testnet', }, }, }; const testValidateAddressForCurrency = ( address: string, currency: CurrencyDefinition | undefined, expectedResult = true, ) => { if (!currency) { throw new Error('currency is undefined'); } const result = CurrencyManager.validateAddress(address, currency); expect(result).toBe(expectedResult); }; describe(`valid cases`, () => { Object.entries(extendedTestCasesPerNetwork).forEach(([network, testCases]) => { if (network === 'other') { return; } describe(`valid cases for ${network}`, () => { Object.entries(testCases).forEach(([, currencyTemplate]) => { it(`should validate ${network}.${currencyTemplate.symbol}`, () => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const currency = currencyManager.fromSymbol(currencyTemplate.symbol!)!; switch (currency.type) { case RequestLogicTypes.CURRENCY.ETH: case RequestLogicTypes.CURRENCY.ERC20: case RequestLogicTypes.CURRENCY.ERC777: switch (currency.symbol) { case 'NEAR': case 'NEAR-testnet': testValidateAddressForCurrency(nearAddresses[currency.network], currency); break; default: eip55Addresses.forEach((address) => testValidateAddressForCurrency(address, currency), ); } break; case RequestLogicTypes.CURRENCY.BTC: testValidateAddressForCurrency(bitcoinAddresses[currency.network], currency); break; default: throw new Error(`Could not generate a valid address for an unknown type`); } }); }); }); }); }); describe(`invalid cases`, () => { it('should not validate bitcoin addresses on ethereum network', () => { const currency = currencyManager.from('ETH', 'mainnet'); testValidateAddressForCurrency(bitcoinAddresses.mainnet, currency, false); }); it('should not validate bitcoin mainnet addresses on bitcoin testnet network', () => { const currency = currencyManager.from('BTC-testnet', 'testnet'); testValidateAddressForCurrency(bitcoinAddresses.mainnet, currency, false); }); it('should not validate bitcoin testnet addresses on bitcoin mainnet network', () => { const currency = currencyManager.from('BTC-testnet', 'mainnet'); testValidateAddressForCurrency(bitcoinAddresses.testnet, currency, false); }); it('should not validate ethereum addresses on bitcoin network', () => { const currency = currencyManager.from('BTC', 'mainnet'); testValidateAddressForCurrency(eip55Addresses[0], currency, false); }); describe(`ISO4217 currencies`, () => { Object.entries(testCasesPerNetwork.other).forEach(([, currencyTemplate]) => { it(`should throw for ${currencyTemplate.symbol} currency`, () => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const currency = currencyManager.from(currencyTemplate.symbol)!; expect(() => CurrencyManager.validateAddress('anyAddress', currency)).toThrow(); }); }); }); }); }); describe('Conversion paths', () => { let eur: CurrencyDefinition, usd: CurrencyDefinition, dai: CurrencyDefinition; beforeEach(() => { eur = currencyManager.from('EUR')!; usd = currencyManager.from('USD')!; dai = currencyManager.from('DAI')!; }); it('has a default conversion path', () => { const path = currencyManager.getConversionPath(eur, dai, 'mainnet'); expect(path).toMatchObject([eur.hash, usd.hash, dai.hash.toLowerCase()]); }); it('can override the default conversion path', () => { const manager = new CurrencyManager(CurrencyManager.getDefaultList(), undefined, { mainnet: { [eur.hash]: { [dai.hash.toLocaleLowerCase()]: 1 } }, }); const path = manager.getConversionPath(eur, dai, 'mainnet'); expect(path).toMatchObject([eur.hash, dai.hash.toLowerCase()]); }); }); });
the_stack
import RenderUtil from "./../../starling/utils/RenderUtil"; import SystemUtil from "./../../starling/utils/SystemUtil"; import RenderState from "./../../starling/rendering/RenderState"; import MatrixUtil from "./../../starling/utils/MatrixUtil"; import IllegalOperationError from "openfl/errors/IllegalOperationError"; import RectangleUtil from "./../../starling/utils/RectangleUtil"; import Pool from "./../../starling/utils/Pool"; import Error from "openfl/errors/Error"; import Quad from "./../../starling/display/Quad"; import MathUtil from "./../../starling/utils/MathUtil"; import BlendMode from "./../../starling/display/BlendMode"; import Matrix from "openfl/geom/Matrix"; import Vector3D from "openfl/geom/Vector3D"; import Matrix3D from "openfl/geom/Matrix3D"; import Rectangle from "openfl/geom/Rectangle"; import MeshSubset from "./../../starling/utils/MeshSubset"; import Vector from "openfl/Vector"; import BatchProcessor from "./../../starling/rendering/BatchProcessor"; import Stage3D from "openfl/display/Stage3D"; import Program from "openfl/display3D/Program"; import BatchToken from "./BatchToken"; import Context3D from "openfl/display3D/Context3D"; import DisplayObject from "./../display/DisplayObject"; import Mesh from "./../display/Mesh"; declare namespace starling.rendering { /** A class that orchestrates rendering of all Starling display objects. * * <p>A Starling instance contains exactly one 'Painter' instance that should be used for all * rendering purposes. Each frame, it is passed to the render methods of all rendered display * objects. To access it outside a render method, call <code>Starling.painter</code>.</p> * * <p>The painter is responsible for drawing all display objects to the screen. At its * core, it is a wrapper for many Context3D methods, but that's not all: it also provides * a convenient state mechanism, supports masking and acts as __iddleman between display * objects and renderers.</p> * * <strong>The State Stack</strong> * * <p>The most important concept of the Painter class is the state stack. A RenderState * stores a combination of settings that are currently used for rendering, e.g. the current * projection- and modelview-matrices and context-related settings. It can be accessed * and manipulated via the <code>state</code> property. Use the methods * <code>pushState</code> and <code>popState</code> to store a specific state and restore * it later. That makes it easy to write rendering code that doesn't have any side effects.</p> * * <listing> * painter.pushState(); // save a copy of the current state on the stack * painter.state.renderTarget = renderTexture; * painter.state.transformModelviewMatrix(object.transformationMatrix); * painter.state.alpha = 0.5; * painter.prepareToDraw(); // apply all state settings at the render context * drawSomething(); // insert Stage3D rendering code here * painter.popState(); // restores previous state</listing> * * @see RenderState */ export class Painter { /** The value with which the stencil buffer will be cleared, * and the default reference value used for stencil tests. */ public static DEFAULT_STENCIL_VALUE:number; // construction /** Creates a new Painter object. Normally, it's not necessary to create any custom * painters; instead, use the global painter found on the Starling instance. */ public constructor(stage3D:Stage3D, sharedContext?:null | boolean); /** Disposes all mesh batches, programs, and - if it is not being shared - * the render context. */ public dispose():void; // context handling /** Requests a context3D object from the stage3D object. * This is called by Starling internally during the initialization process. * You normally don't need to call this method yourself. (For a detailed description * of the parameters, look at the documentation of the method with the same name in the * "RenderUtil" class.) * * @see starling.utils.RenderUtil */ public requestContext3D(renderMode:string, profile:any):void; /** Sets the viewport dimensions and other attributes of the rendering buffer. * Starling will call this method internally, so most apps won't need to mess with this. * * <p>Beware: if <code>shareContext</code> is enabled, the method will only update the * painter's context-related information (like the size of the back buffer), but won't * make any actual changes to the context.</p> * * @param viewPort the position and size of the area that should be rendered * into, in pixels. * @param contentScaleFactor only relevant for Desktop (!) HiDPI screens. If you want * to support high resolutions, pass the 'contentScaleFactor' * of the Flash stage; otherwise, '1.0'. * @param antiAlias from 0 (none) to 16 (very high quality). * @param enableDepthAndStencil indicates whether the depth and stencil buffers should * be enabled. Note that on AIR, you also have to enable * this setting in the app-xml (application descriptor); * otherwise, this setting will be silently ignored. * @param supportBrowserZoom if enabled, zooming a website will adapt the size of * the back buffer. */ public configureBackBuffer(viewPort:Rectangle, contentScaleFactor:number, antiAlias:number, enableDepthAndStencil:boolean, supportBrowserZoom?:boolean):void; // program management /** Registers a program under a certain name. * If the name was already used, the previous program is overwritten. */ public registerProgram(name:string, program:Program):void; /** Deletes the program of a certain name. */ public deleteProgram(name:string):void; /** Returns the program registered under a certain name, or null if no program with * this name has been registered. */ public getProgram(name:string):Program; /** Indicates if a program is registered under a certain name. */ public hasProgram(name:string):boolean; // state stack /** Pushes the current render state to a stack from which it can be restored later. * * <p>If you pass a BatchToken, it will be updated to point to the current location within * the render cache. That way, you can later reference this location to render a subset of * the cache.</p> */ public pushState(token?:BatchToken):void; /** Modifies the current state with a transformation matrix, alpha factor, and blend mode. * * @param transformationMatrix Used to transform the current <code>modelviewMatrix</code>. * @param alphaFactor Multiplied with the current alpha value. * @param blendMode Replaces the current blend mode; except for "auto", which * means the current value remains unchanged. */ public setStateTo(transformationMatrix:Matrix, alphaFactor?:number, blendMode?:string):void; /** Restores the render state that was last pushed to the stack. If this changes * blend mode, clipping rectangle, render target or culling, the current batch * will be drawn right away. * * <p>If you pass a BatchToken, it will be updated to point to the current location within * the render cache. That way, you can later reference this location to render a subset of * the cache.</p> */ public popState(token?:BatchToken):void; /** Restores the render state that was last pushed to the stack, but does NOT remove * it from the stack. */ public restoreState():void; /** Updates all properties of the given token so that it describes the current position * within the render cache. */ public fillToken(token:BatchToken):void; // masks /** Draws a display object into the stencil buffer, incrementing the buffer on each * used pixel. The stencil reference value is incremented as well; thus, any subsequent * stencil tests outside of this area will fail. * * <p>If 'mask' is part of the display list, it will be drawn at its conventional stage * coordinates. Otherwise, it will be drawn with the current modelview matrix.</p> * * <p>As an optimization, this method might update the clipping rectangle of the render * state instead of utilizing the stencil buffer. This is possible when the mask object * is of type <code>starling.display.Quad</code> and is aligned parallel to the stage * axes.</p> * * <p>Note that masking breaks the render cache; the masked object must be redrawn anew * in the next frame. If you pass <code>maskee</code>, the method will automatically * call <code>excludeFromCache(maskee)</code> for you.</p> */ public drawMask(mask:DisplayObject, maskee?:DisplayObject):void; /** Draws a display object into the stencil buffer, decrementing the * buffer on each used pixel. This effectively erases the object from the stencil buffer, * restoring the previous state. The stencil reference value will be decremented. * * <p>Note: if the mask object meets the requirements of using the clipping rectangle, * it will be assumed that this erase operation undoes the clipping rectangle change * caused by the corresponding <code>drawMask()</code> call.</p> */ public eraseMask(mask:DisplayObject, maskee?:DisplayObject):void; // mesh rendering /** Adds a mesh to the current batch of unrendered meshes. If the current batch is not * compatible with the mesh, all previous meshes are rendered at once and the batch * is cleared. * * @param mesh The mesh to batch. * @param subset The range of vertices to be batched. If <code>null</code>, the complete * mesh will be used. */ public batchMesh(mesh:Mesh, subset?:MeshSubset):void; /** Finishes the current mesh batch and prepares the next one. */ public finishMeshBatch():void; /** Indicate how often the internally used batches are being trimmed to save memory. * * <p>While rendering, the internally used MeshBatches are used in a different way in each * frame. To save memory, they should be trimmed every once in a while. This method defines * how often that happens, if at all. (Default: enabled = true, interval = 250)</p> * * @param enabled If trimming happens at all. Only disable temporarily! * @param interval The number of frames between each trim operation. */ public enableBatchTrimming(enabled?:boolean, interval?:number):void; /** Completes all unfinished batches, cleanup procedures. */ public finishFrame():void; /** Makes sure that the default context settings Starling relies on will be refreshed * before the next 'draw' operation. This includes blend mode, culling, and depth test. */ public setupContextDefaults():void; /** Resets the current state, state stack, batch processor, stencil reference value, * clipping rectangle, and draw count. Furthermore, depth testing is disabled. */ public nextFrame():void; /** Draws all meshes from the render cache between <code>startToken</code> and * (but not including) <code>endToken</code>. The render cache contains all meshes * rendered in the previous frame. */ public drawFromCache(startToken:BatchToken, endToken:BatchToken):void; /** Prevents the object from being drawn from the render cache in the next frame. * Different to <code>setRequiresRedraw()</code>, this does not indicate that the object * has changed in any way, but just that it doesn't support being drawn from cache. * * <p>Note that when a container is excluded from the render cache, its children will * still be cached! This just means that batching is interrupted at this object when * the display tree is traversed.</p> */ public excludeFromCache(object:DisplayObject):void; // helper methods /** Applies all relevant state settings to at the render context. This includes * blend mode, render target and clipping rectangle. Always call this method before * <code>context.drawTriangles()</code>. */ public prepareToDraw():void; /** Clears the render context with a certain color and alpha value. Since this also * clears the stencil buffer, the stencil reference value is also reset to '0'. */ public clear(rgb?:number, alpha?:number):void; /** Resets the render target to the back buffer and displays its contents. */ public present():void; /** Refreshes the values of "backBufferWidth" and "backBufferHeight" from the current * context dimensions and stores the given "backBufferScaleFactor". This method is * called by Starling when the browser zoom factor changes (in case "supportBrowserZoom" * is enabled). */ public refreshBackBufferSize(scaleFactor:number):void; // properties /** Indicates the number of stage3D draw calls. */ public drawCount:number; protected get_drawCount():number; protected set_drawCount(value:number):number; /** The current stencil reference value of the active render target. This value * is typically incremented when drawing a mask and decrementing when erasing it. * The painter keeps track of one stencil reference value per render target. * Only change this value if you know what you're doing! */ public stencilReferenceValue:number; protected get_stencilReferenceValue():number; protected set_stencilReferenceValue(value:number):number; /** Indicates if the render cache is enabled. Normally, this should be left at the default; * however, some custom rendering logic might require to change this property temporarily. * Also note that the cache is automatically reactivated each frame, right before the * render process. * * @default true */ public cacheEnabled:boolean; protected get_cacheEnabled():boolean; protected set_cacheEnabled(value:boolean):boolean; /** The current render state, containing some of the context settings, projection- and * modelview-matrix, etc. Always returns the same instance, even after calls to "pushState" * and "popState". * * <p>When you change the current RenderState, and this change is not compatible with * the current render batch, the batch will be concluded right away. Thus, watch out * for changes of blend mode, clipping rectangle, render target or culling.</p> */ public readonly state:RenderState; protected get_state():RenderState; /** The Stage3D instance this painter renders into. */ public readonly stage3D:Stage3D; protected get_stage3D():Stage3D; /** The Context3D instance this painter renders into. */ public readonly context:Context3D; protected get_context():Context3D; /** Returns the index of the current frame <strong>if</strong> the render cache is enabled; * otherwise, returns zero. To get the frameID regardless of the render cache, call * <code>Starling.frameID</code> instead. */ public frameID:number; protected set_frameID(value:number):number; protected get_frameID():number; /** The size (in points) that represents one pixel in the back buffer. */ public pixelSize:number; protected get_pixelSize():number; protected set_pixelSize(value:number):number; /** Indicates if another Starling instance (or another Stage3D framework altogether) * uses the same render context. @default false */ public shareContext:boolean; protected get_shareContext():boolean; protected set_shareContext(value:boolean):boolean; /** Indicates if Stage3D render methods will report errors. Activate only when needed, * as this has a negative impact on performance. @default false */ public enableErrorChecking:boolean; protected get_enableErrorChecking():boolean; protected set_enableErrorChecking(value:boolean):boolean; /** Returns the current width of the back buffer. In most cases, this value is in pixels; * however, if the app is running on an HiDPI display with an activated * 'supportHighResolutions' setting, you have to multiply with 'backBufferPixelsPerPoint' * for the actual pixel count. Alternatively, use the Context3D-property with the * same name: it will return the exact pixel values. */ public readonly backBufferWidth:number; protected get_backBufferWidth():number; /** Returns the current height of the back buffer. In most cases, this value is in pixels; * however, if the app is running on an HiDPI display with an activated * 'supportHighResolutions' setting, you have to multiply with 'backBufferPixelsPerPoint' * for the actual pixel count. Alternatively, use the Context3D-property with the * same name: it will return the exact pixel values. */ public readonly backBufferHeight:number; protected get_backBufferHeight():number; /** The number of pixels per point returned by the 'backBufferWidth/Height' properties. * Except for desktop HiDPI displays with an activated 'supportHighResolutions' setting, * this will always return '1'. */ public readonly backBufferScaleFactor:number; protected get_backBufferScaleFactor():number; /** Indicates if the Context3D object is currently valid (i.e. it hasn't been lost or * disposed). */ public readonly contextValid:boolean; protected get_contextValid():boolean; /** The Context3D profile of the current render context, or <code>null</code> * if the context has not been created yet. */ public readonly profile:string; protected get_profile():string; /** A dictionary that can be used to save custom data related to the render context. * If you need to share data that is bound to the render context (e.g. textures), use * this dictionary instead of creating a static class variable. That way, the data will * be available for all Starling instances that use this stage3D / context. */ public readonly sharedData:Map<string, any>; protected get_sharedData():Map<string, any>; protected readonly programs:Map<string, Program>; protected get_programs():Map<string, Program>; } } export default starling.rendering.Painter;
the_stack
"use strict"; const address = require("address"); const fs = require("fs"); const path = require("path"); const url = require("url"); const chalk = require("chalk"); const detect = require("detect-port-alt"); const isRoot = require("is-root"); const inquirer = require("inquirer"); const clearConsole = require("react-dev-utils/clearConsole"); const formatWebpackMessages = require("react-dev-utils/formatWebpackMessages"); const getProcessForPort = require("react-dev-utils/getProcessForPort"); const typescriptFormatter = require("react-dev-utils/typescriptFormatter"); const forkTsCheckerWebpackPlugin = require("react-dev-utils/ForkTsCheckerWebpackPlugin"); const isInteractive = process.stdout.isTTY; export function prepareUrls(protocol, host, port) { const formatUrl = (hostname) => url.format({ protocol, hostname, port, pathname: "/", }); const prettyPrintUrl = (hostname) => url.format({ protocol, hostname, port: chalk.bold(port), pathname: "/", }); const isUnspecifiedHost = host === "0.0.0.0" || host === "::"; let prettyHost, lanUrlForConfig, lanUrlForTerminal; if (isUnspecifiedHost) { prettyHost = "localhost"; try { // This can only return an IPv4 address lanUrlForConfig = address.ip(); if (lanUrlForConfig) { // Check if the address is a private ip // https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces if (/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(lanUrlForConfig)) { // Address is private, format it for later use lanUrlForTerminal = prettyPrintUrl(lanUrlForConfig); } else { // Address is not private, so we will discard it lanUrlForConfig = undefined; } } } catch (_e) { // ignored } } else { prettyHost = host; } const localUrlForTerminal = prettyPrintUrl(prettyHost); const localUrlForBrowser = formatUrl(prettyHost); return { lanUrlForConfig, lanUrlForTerminal, localUrlForTerminal, localUrlForBrowser, }; } export function printInstructions(appName, urls, useYarn) { console.log(); console.log(`You can now view ${chalk.bold(appName)} in the browser.`); console.log(); if (urls.lanUrlForTerminal) { console.log(` ${chalk.bold("Local:")} ${urls.localUrlForTerminal}`); console.log(` ${chalk.bold("On Your Network:")} ${urls.lanUrlForTerminal}`); } else { console.log(` ${urls.localUrlForTerminal}`); } console.log(); console.log("Note that the development build is not optimized."); console.log(`To create a production build, use ` + `${chalk.cyan(`${useYarn ? "yarn" : "npm run"} build`)}.`); console.log(); } export function createCompiler({ appName, config, devSocket, urls, useYarn, useTypeScript, tscCompileOnError, webpack, }) { // "Compiler" is a low-level interface to Webpack. // It lets us listen to some events and provide our own custom messages. let compiler; try { compiler = webpack(config); } catch (err) { console.log(chalk.red(`(${appName}) Failed to compile.`)); console.log(); console.log(err.message || err); console.log(); process.exit(1); } // "invalid" event fires when you have changed a file, and Webpack is // recompiling a bundle. WebpackDevServer takes care to pause serving the // bundle, so if you refresh, it'll wait instead of serving the old one. // "invalid" is short for "bundle invalidated", it doesn't imply any errors. compiler.hooks.invalid.tap(`${appName}-invalid`, () => { if (isInteractive) { clearConsole(); } console.log(`(${appName}) Compiling...`); }); let isFirstCompile = true; let tsMessagesPromise; let tsMessagesResolver; if (useTypeScript) { compiler.hooks.beforeCompile.tap(`${appName}-beforeCompile`, () => { tsMessagesPromise = new Promise((resolve) => { tsMessagesResolver = (msgs) => resolve(msgs); }); }); forkTsCheckerWebpackPlugin .getCompilerHooks(compiler) .receive.tap(`${appName}-afterTypeScriptCheck`, (diagnostics, lints) => { const allMsgs = [...diagnostics, ...lints]; const format = (message) => `${message.file}\n${typescriptFormatter(message, true)}`; tsMessagesResolver({ errors: allMsgs.filter((msg) => msg.severity === "error").map(format), warnings: allMsgs.filter((msg) => msg.severity === "warning").map(format), }); }); } // "done" event fires when Webpack has finished recompiling the bundle. // Whether or not you have warnings or errors, you will get this event. compiler.hooks.done.tap(`${appName}-done`, async (stats) => { // We have switched off the default Webpack output in WebpackDevServer // options so we are going to "massage" the warnings and errors and present // them in a readable focused way. // We only construct the warnings and errors for speed: // https://github.com/facebook/create-react-app/issues/4492#issuecomment-421959548 const statsData = stats.toJson({ all: false, warnings: true, errors: true, }); if (useTypeScript && statsData.errors.length === 0) { console.log(chalk.yellow(`(${appName}) Files successfully emitted, waiting for typecheck results...`)); const messages = await tsMessagesPromise; console.log(chalk.yellow(`(${appName}) typecheck results completed.`)); if (tscCompileOnError) { statsData.warnings.push(...messages.errors); } else { statsData.errors.push(...messages.errors); } statsData.warnings.push(...messages.warnings); // Push errors and warnings into compilation result // to show them after page refresh triggered by user. if (tscCompileOnError) { stats.compilation.warnings.push(...messages.errors); } else { stats.compilation.errors.push(...messages.errors); } stats.compilation.warnings.push(...messages.warnings); if (messages.errors.length > 0) { if (tscCompileOnError) { devSocket.warnings(messages.errors); } else { devSocket.errors(messages.errors); } } else if (messages.warnings.length > 0) { devSocket.warnings(messages.warnings); } } const messages = formatWebpackMessages(statsData); const isSuccessful = !messages.errors.length && !messages.warnings.length; if (isSuccessful) { console.log(chalk.green(`(${appName}) Compiled successfully!`)); } isFirstCompile = false; // If errors exist, only show errors. if (messages.errors.length) { // Only keep the first error. Others are often indicative // of the same problem, but confuse the reader with noise. if (messages.errors.length > 1) { messages.errors.length = 1; } console.log(chalk.red(`(${appName}) Failed to compile.\n`)); console.log(messages.errors.join("\n\n")); return; } // Show warnings if no errors were found. if (messages.warnings.length) { console.log(chalk.yellow(`(${appName}) Compiled with warnings.\n`)); console.log(messages.warnings.join("\n\n")); // Teach some ESLint tricks. console.log( "\nSearch for the " + chalk.underline(chalk.yellow("keywords")) + " to learn more about each warning.", ); console.log("To ignore, add " + chalk.cyan("// eslint-disable-next-line") + " to the line before.\n"); } }); // You can safely remove this after ejecting. // We only use this block for testing of Create React App itself: const isSmokeTest = process.argv.some((arg) => arg.indexOf("--smoke-test") > -1); if (isSmokeTest) { compiler.hooks.failed.tap(`${appName}-smokeTest`, async () => { await tsMessagesPromise; process.exit(1); }); compiler.hooks.done.tap(`${appName}-smokeTest`, async (stats) => { await tsMessagesPromise; if (stats.hasErrors() || stats.hasWarnings()) { process.exit(1); } else { process.exit(0); } }); } return compiler; } function resolveLoopback(proxy) { const o = url.parse(proxy); o.host = undefined; if (o.hostname !== "localhost") { return proxy; } // Unfortunately, many languages (unlike node) do not yet support IPv6. // This means even though localhost resolves to ::1, the application // must fall back to IPv4 (on 127.0.0.1). // We can re-enable this in a few years. /*try { o.hostname = address.ipv6() ? '::1' : '127.0.0.1'; } catch (_ignored) { o.hostname = '127.0.0.1'; }*/ try { // Check if we're on a network; if we are, chances are we can resolve // localhost. Otherwise, we can just be safe and assume localhost is // IPv4 for maximum compatibility. if (!address.ip()) { o.hostname = "127.0.0.1"; } } catch (_ignored) { o.hostname = "127.0.0.1"; } return url.format(o); } // We need to provide a custom onError function for httpProxyMiddleware. // It allows us to log custom error messages on the console. function onProxyError(proxy) { return (err, req, res) => { const host = req.headers && req.headers.host; console.log( chalk.red("Proxy error:") + " Could not proxy request " + chalk.cyan(req.url) + " from " + chalk.cyan(host) + " to " + chalk.cyan(proxy) + ".", ); console.log( "See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (" + chalk.cyan(err.code) + ").", ); console.log(); // And immediately send the proper error response to the client. // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side. if (res.writeHead && !res.headersSent) { res.writeHead(500); } res.end( "Proxy error: Could not proxy request " + req.url + " from " + host + " to " + proxy + " (" + err.code + ").", ); }; } export function prepareProxy(proxy, appPublicFolder) { // `proxy` lets you specify alternate servers for specific requests. if (!proxy) { return undefined; } if (typeof proxy !== "string") { console.log(chalk.red('When specified, "proxy" in package.json must be a string.')); console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".')); console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.')); process.exit(1); } // If proxy is specified, let it handle any request except for // files in the public folder and requests to the WebpackDevServer socket endpoint. // https://github.com/facebook/create-react-app/issues/6720 function mayProxy(pathname) { const maybePublicPath = path.resolve(appPublicFolder, pathname.slice(1)); const isPublicFileRequest = fs.existsSync(maybePublicPath); const isWdsEndpointRequest = pathname.startsWith("/sockjs-node"); // used by webpackHotDevClient return !(isPublicFileRequest || isWdsEndpointRequest); } if (!/^http(s)?:\/\//.test(proxy)) { console.log(chalk.red('When "proxy" is specified in package.json it must start with either http:// or https://')); process.exit(1); } let target; if (process.platform === "win32") { target = resolveLoopback(proxy); } else { target = proxy; } return [ { target, logLevel: "silent", // For single page apps, we generally want to fallback to /index.html. // However we also want to respect `proxy` for API calls. // So if `proxy` is specified as a string, we need to decide which fallback to use. // We use a heuristic: We want to proxy all the requests that are not meant // for static assets and as all the requests for static assets will be using // `GET` method, we can proxy all non-`GET` requests. // For `GET` requests, if request `accept`s text/html, we pick /index.html. // Modern browsers include text/html into `accept` header when navigating. // However API calls like `fetch()` won’t generally accept text/html. // If this heuristic doesn’t work well for you, use `src/setupProxy.js`. context: function (pathname, req) { return ( req.method !== "GET" || (mayProxy(pathname) && req.headers.accept && req.headers.accept.indexOf("text/html") === -1) ); }, onProxyReq: (proxyReq) => { // Browsers may send Origin headers even with same-origin // requests. To prevent CORS issues, we have to change // the Origin to match the target URL. if (proxyReq.getHeader("origin")) { proxyReq.setHeader("origin", target); } }, onError: onProxyError(target), secure: false, changeOrigin: true, ws: true, xfwd: true, }, ]; } export function choosePort(host, defaultPort) { return detect(defaultPort, host).then( (port) => new Promise((resolve) => { if (port === defaultPort) { return resolve(port); } const message = process.platform !== "win32" && defaultPort < 1024 && !isRoot() ? `Admin permissions are required to run a server on a port below 1024.` : `Something is already running on port ${defaultPort}.`; if (isInteractive) { clearConsole(); const existingProcess = getProcessForPort(defaultPort); const question = { type: "confirm", name: "shouldChangePort", message: chalk.yellow(message + `${existingProcess ? ` Probably:\n ${existingProcess}` : ""}`) + "\n\nWould you like to run the app on another port instead?", default: true, }; inquirer.prompt(question).then((answer) => { if (answer.shouldChangePort) { resolve(port); } else { resolve(null); } }); } else { console.log(chalk.red(message)); resolve(null); } }), (err) => { throw new Error( chalk.red(`Could not find an open port at ${chalk.bold(host)}.`) + "\n" + ("Network error message: " + err.message || err) + "\n", ); }, ); }
the_stack
import 'mocha'; import * as vscode from 'vscode'; import { acceptFirstSuggestion, typeCommitCharacter } from '../../test/suggestTestHelpers'; import { assertEditorContents, Config, createTestEditor, enumerateConfig, joinLines, updateConfig, VsCodeConfiguration } from '../../test/testUtils'; import { disposeAll } from '../../utils/dispose'; const testDocumentUri = vscode.Uri.parse('untitled:test.ts'); const insertModes = Object.freeze(['insert', 'replace']); suite.skip('TypeScript Completions', () => { const configDefaults = Object.freeze<VsCodeConfiguration>({ [Config.autoClosingBrackets]: 'always', [Config.typescriptCompleteFunctionCalls]: false, [Config.insertMode]: 'insert', [Config.snippetSuggestions]: 'none', [Config.suggestSelection]: 'first', [Config.javascriptQuoteStyle]: 'double', [Config.typescriptQuoteStyle]: 'double', }); const _disposables: vscode.Disposable[] = []; let oldConfig: { [key: string]: any } = {}; setup(async () => { // the tests assume that typescript features are registered await vscode.extensions.getExtension('vscode.typescript-language-features')!.activate(); // Save off config and apply defaults oldConfig = await updateConfig(testDocumentUri, configDefaults); }); teardown(async () => { disposeAll(_disposables); // Restore config await updateConfig(testDocumentUri, oldConfig); return vscode.commands.executeCommand('workbench.action.closeAllEditors'); }); test('Basic var completion', async () => { await enumerateConfig(testDocumentUri, Config.insertMode, insertModes, async config => { const editor = await createTestEditor(testDocumentUri, `const abcdef = 123;`, `ab$0;` ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `const abcdef = 123;`, `abcdef;` ), `config: ${config}` ); }); }); test('Should treat period as commit character for var completions', async () => { await enumerateConfig(testDocumentUri, Config.insertMode, insertModes, async config => { const editor = await createTestEditor(testDocumentUri, `const abcdef = 123;`, `ab$0;` ); await typeCommitCharacter(testDocumentUri, '.', _disposables); assertEditorContents(editor, joinLines( `const abcdef = 123;`, `abcdef.;` ), `config: ${config}`); }); }); test('Should treat paren as commit character for function completions', async () => { await enumerateConfig(testDocumentUri, Config.insertMode, insertModes, async config => { const editor = await createTestEditor(testDocumentUri, `function abcdef() {};`, `ab$0;` ); await typeCommitCharacter(testDocumentUri, '(', _disposables); assertEditorContents(editor, joinLines( `function abcdef() {};`, `abcdef();` ), `config: ${config}`); }); }); test('Should insert brackets when completing dot properties with spaces in name', async () => { await enumerateConfig(testDocumentUri, Config.insertMode, insertModes, async config => { const editor = await createTestEditor(testDocumentUri, 'const x = { "hello world": 1 };', 'x.$0' ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( 'const x = { "hello world": 1 };', 'x["hello world"]' ), `config: ${config}`); }); }); test('Should allow commit characters for backet completions', async () => { for (const { char, insert } of [ { char: '.', insert: '.' }, { char: '(', insert: '()' }, ]) { const editor = await createTestEditor(testDocumentUri, 'const x = { "hello world2": 1 };', 'x.$0' ); await typeCommitCharacter(testDocumentUri, char, _disposables); assertEditorContents(editor, joinLines( 'const x = { "hello world2": 1 };', `x["hello world2"]${insert}` )); disposeAll(_disposables); await vscode.commands.executeCommand('workbench.action.closeAllEditors'); } }); test('Should not prioritize bracket accessor completions. #63100', async () => { await enumerateConfig(testDocumentUri, Config.insertMode, insertModes, async config => { // 'a' should be first entry in completion list const editor = await createTestEditor(testDocumentUri, 'const x = { "z-z": 1, a: 1 };', 'x.$0' ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( 'const x = { "z-z": 1, a: 1 };', 'x.a' ), `config: ${config}`); }); }); test('Accepting a string completion should replace the entire string. #53962', async () => { const editor = await createTestEditor(testDocumentUri, 'interface TFunction {', ` (_: 'abc.abc2', __ ?: {}): string;`, ` (_: 'abc.abc', __?: {}): string;`, `}`, 'const f: TFunction = (() => { }) as any;', `f('abc.abc$0')` ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( 'interface TFunction {', ` (_: 'abc.abc2', __ ?: {}): string;`, ` (_: 'abc.abc', __?: {}): string;`, `}`, 'const f: TFunction = (() => { }) as any;', `f('abc.abc')` )); }); test('completeFunctionCalls should complete function parameters when at end of word', async () => { await updateConfig(testDocumentUri, { [Config.typescriptCompleteFunctionCalls]: true }); // Complete with-in word const editor = await createTestEditor(testDocumentUri, `function abcdef(x, y, z) { }`, `abcdef$0` ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `function abcdef(x, y, z) { }`, `abcdef(x, y, z)` )); }); test.skip('completeFunctionCalls should complete function parameters when within word', async () => { await updateConfig(testDocumentUri, { [Config.typescriptCompleteFunctionCalls]: true }); const editor = await createTestEditor(testDocumentUri, `function abcdef(x, y, z) { }`, `abcd$0ef` ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `function abcdef(x, y, z) { }`, `abcdef(x, y, z)` )); }); test('completeFunctionCalls should not complete function parameters at end of word if we are already in something that looks like a function call, #18131', async () => { await updateConfig(testDocumentUri, { [Config.typescriptCompleteFunctionCalls]: true }); const editor = await createTestEditor(testDocumentUri, `function abcdef(x, y, z) { }`, `abcdef$0(1, 2, 3)` ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `function abcdef(x, y, z) { }`, `abcdef(1, 2, 3)` )); }); test.skip('completeFunctionCalls should not complete function parameters within word if we are already in something that looks like a function call, #18131', async () => { await updateConfig(testDocumentUri, { [Config.typescriptCompleteFunctionCalls]: true }); const editor = await createTestEditor(testDocumentUri, `function abcdef(x, y, z) { }`, `abcd$0ef(1, 2, 3)` ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `function abcdef(x, y, z) { }`, `abcdef(1, 2, 3)` )); }); test('should not de-prioritize `this.member` suggestion, #74164', async () => { await enumerateConfig(testDocumentUri, Config.insertMode, insertModes, async config => { const editor = await createTestEditor(testDocumentUri, `class A {`, ` private detail = '';`, ` foo() {`, ` det$0`, ` }`, `}`, ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `class A {`, ` private detail = '';`, ` foo() {`, ` this.detail`, ` }`, `}`, ), `Config: ${config}`); }); }); test('Member completions for string property name should insert `this.` and use brackets', async () => { await enumerateConfig(testDocumentUri, Config.insertMode, insertModes, async config => { const editor = await createTestEditor(testDocumentUri, `class A {`, ` ['xyz 123'] = 1`, ` foo() {`, ` xyz$0`, ` }`, `}`, ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `class A {`, ` ['xyz 123'] = 1`, ` foo() {`, ` this["xyz 123"]`, ` }`, `}`, ), `Config: ${config}`); }); }); test('Member completions for string property name already using `this.` should add brackets', async () => { await enumerateConfig(testDocumentUri, Config.insertMode, insertModes, async config => { const editor = await createTestEditor(testDocumentUri, `class A {`, ` ['xyz 123'] = 1`, ` foo() {`, ` this.xyz$0`, ` }`, `}`, ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `class A {`, ` ['xyz 123'] = 1`, ` foo() {`, ` this["xyz 123"]`, ` }`, `}`, ), `Config: ${config}`); }); }); test('Accepting a completion in word using `insert` mode should insert', async () => { await updateConfig(testDocumentUri, { [Config.insertMode]: 'insert' }); const editor = await createTestEditor(testDocumentUri, `const abc = 123;`, `ab$0c` ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `const abc = 123;`, `abcc` )); }); test('Accepting a completion in word using `replace` mode should replace', async () => { await updateConfig(testDocumentUri, { [Config.insertMode]: 'replace' }); const editor = await createTestEditor(testDocumentUri, `const abc = 123;`, `ab$0c` ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `const abc = 123;`, `abc` )); }); test('Accepting a member completion in word using `insert` mode add `this.` and insert', async () => { await updateConfig(testDocumentUri, { [Config.insertMode]: 'insert' }); const editor = await createTestEditor(testDocumentUri, `class Foo {`, ` abc = 1;`, ` foo() {`, ` ab$0c`, ` }`, `}`, ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `class Foo {`, ` abc = 1;`, ` foo() {`, ` this.abcc`, ` }`, `}`, )); }); test('Accepting a member completion in word using `replace` mode should add `this.` and replace', async () => { await updateConfig(testDocumentUri, { [Config.insertMode]: 'replace' }); const editor = await createTestEditor(testDocumentUri, `class Foo {`, ` abc = 1;`, ` foo() {`, ` ab$0c`, ` }`, `}`, ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `class Foo {`, ` abc = 1;`, ` foo() {`, ` this.abc`, ` }`, `}`, )); }); test('Accepting string completion inside string using `insert` mode should insert', async () => { await updateConfig(testDocumentUri, { [Config.insertMode]: 'insert' }); const editor = await createTestEditor(testDocumentUri, `const abc = { 'xy z': 123 }`, `abc["x$0y w"]` ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `const abc = { 'xy z': 123 }`, `abc["xy zy w"]` )); }); // Waiting on https://github.com/microsoft/TypeScript/issues/35602 test.skip('Accepting string completion inside string using insert mode should insert', async () => { await updateConfig(testDocumentUri, { [Config.insertMode]: 'replace' }); const editor = await createTestEditor(testDocumentUri, `const abc = { 'xy z': 123 }`, `abc["x$0y w"]` ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `const abc = { 'xy z': 123 }`, `abc["xy w"]` )); }); test('Private field completions on `this.#` should work', async () => { await enumerateConfig(testDocumentUri, Config.insertMode, insertModes, async config => { const editor = await createTestEditor(testDocumentUri, `class A {`, ` #xyz = 1;`, ` foo() {`, ` this.#$0`, ` }`, `}`, ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `class A {`, ` #xyz = 1;`, ` foo() {`, ` this.#xyz`, ` }`, `}`, ), `Config: ${config}`); }); }); test('Private field completions on `#` should insert `this.`', async () => { await enumerateConfig(testDocumentUri, Config.insertMode, insertModes, async config => { const editor = await createTestEditor(testDocumentUri, `class A {`, ` #xyz = 1;`, ` foo() {`, ` #$0`, ` }`, `}`, ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `class A {`, ` #xyz = 1;`, ` foo() {`, ` this.#xyz`, ` }`, `}`, ), `Config: ${config}`); }); }); test('Private field completions should not require strict prefix match (#89556)', async () => { await enumerateConfig(testDocumentUri, Config.insertMode, insertModes, async config => { const editor = await createTestEditor(testDocumentUri, `class A {`, ` #xyz = 1;`, ` foo() {`, ` this.xyz$0`, ` }`, `}`, ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `class A {`, ` #xyz = 1;`, ` foo() {`, ` this.#xyz`, ` }`, `}`, ), `Config: ${config}`); }); }); test('Private field completions without `this.` should not require strict prefix match (#89556)', async () => { await enumerateConfig(testDocumentUri, Config.insertMode, insertModes, async config => { const editor = await createTestEditor(testDocumentUri, `class A {`, ` #xyz = 1;`, ` foo() {`, ` xyz$0`, ` }`, `}`, ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `class A {`, ` #xyz = 1;`, ` foo() {`, ` this.#xyz`, ` }`, `}`, ), `Config: ${config}`); }); }); test('Accepting a completion for async property in `insert` mode should insert and add await', async () => { await updateConfig(testDocumentUri, { [Config.insertMode]: 'insert' }); const editor = await createTestEditor(testDocumentUri, `class A {`, ` xyz = Promise.resolve({ 'abc': 1 });`, ` async foo() {`, ` this.xyz.ab$0c`, ` }`, `}`, ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `class A {`, ` xyz = Promise.resolve({ 'abc': 1 });`, ` async foo() {`, ` (await this.xyz).abcc`, ` }`, `}`, )); }); test('Accepting a completion for async property in `replace` mode should replace and add await', async () => { await updateConfig(testDocumentUri, { [Config.insertMode]: 'replace' }); const editor = await createTestEditor(testDocumentUri, `class A {`, ` xyz = Promise.resolve({ 'abc': 1 });`, ` async foo() {`, ` this.xyz.ab$0c`, ` }`, `}`, ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `class A {`, ` xyz = Promise.resolve({ 'abc': 1 });`, ` async foo() {`, ` (await this.xyz).abc`, ` }`, `}`, )); }); test.skip('Accepting a completion for async string property should add await plus brackets', async () => { await enumerateConfig(testDocumentUri, Config.insertMode, insertModes, async config => { const editor = await createTestEditor(testDocumentUri, `class A {`, ` xyz = Promise.resolve({ 'ab c': 1 });`, ` async foo() {`, ` this.xyz.ab$0`, ` }`, `}`, ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `class A {`, ` xyz = Promise.resolve({ 'abc': 1 });`, ` async foo() {`, ` (await this.xyz)["ab c"]`, ` }`, `}`, ), `Config: ${config}`); }); }); test('Replace should work after this. (#91105)', async () => { await updateConfig(testDocumentUri, { [Config.insertMode]: 'replace' }); const editor = await createTestEditor(testDocumentUri, `class A {`, ` abc = 1`, ` foo() {`, ` this.$0abc`, ` }`, `}`, ); await acceptFirstSuggestion(testDocumentUri, _disposables); assertEditorContents(editor, joinLines( `class A {`, ` abc = 1`, ` foo() {`, ` this.abc`, ` }`, `}`, )); }); });
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * Location information. */ export interface Location { /** * The fully qualified ID of the location. For example, * /subscriptions/00000000-0000-0000-0000-000000000000/locations/westus. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The subscription ID. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly subscriptionId?: string; /** * The location name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The display name of the location. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly displayName?: string; /** * The latitude of the location. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly latitude?: string; /** * The longitude of the location. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly longitude?: string; } /** * Subscription policies. */ export interface SubscriptionPolicies { /** * The subscription location placement ID. The ID indicates which regions are visible for a * subscription. For example, a subscription with a location placement Id of Public_2014-09-01 * has access to Azure public regions. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly locationPlacementId?: string; /** * The subscription quota ID. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly quotaId?: string; /** * The subscription spending limit. Possible values include: 'On', 'Off', 'CurrentPeriodOff' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly spendingLimit?: SpendingLimit; } /** * Subscription information. */ export interface Subscription { /** * The fully qualified ID for the subscription. For example, * /subscriptions/00000000-0000-0000-0000-000000000000. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The subscription ID. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly subscriptionId?: string; /** * The subscription display name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly displayName?: string; /** * The subscription state. Possible values are Enabled, Warned, PastDue, Disabled, and Deleted. * Possible values include: 'Enabled', 'Warned', 'PastDue', 'Disabled', 'Deleted' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly state?: SubscriptionState; /** * The subscription policies. */ subscriptionPolicies?: SubscriptionPolicies; /** * The authorization source of the request. Valid values are one or more combinations of Legacy, * RoleBased, Bypassed, Direct and Management. For example, 'Legacy, RoleBased'. */ authorizationSource?: string; } /** * Tenant Id information. */ export interface TenantIdDescription { /** * The fully qualified ID of the tenant. For example, * /tenants/00000000-0000-0000-0000-000000000000. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The tenant ID. For example, 00000000-0000-0000-0000-000000000000. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tenantId?: string; } /** * Name and Type of the Resource */ export interface ResourceName { /** * Name of the resource */ name: string; /** * The type of the resource */ type: string; } /** * Resource Name valid if not a reserved word, does not contain a reserved word and does not start * with a reserved word */ export interface CheckResourceNameResult { /** * Name of Resource */ name?: string; /** * Type of Resource */ type?: string; /** * Is the resource name Allowed or Reserved. Possible values include: 'Allowed', 'Reserved' */ status?: ResourceNameStatus; } /** * Error description and code explaining why resource name is invalid. */ export interface ErrorDefinition { /** * Description of the error. */ message?: string; /** * Code of the error. */ code?: string; } /** * Error response. */ export interface ErrorResponse { /** * The error details. */ error?: ErrorDefinition; } /** * The object that represents the operation. */ export interface OperationDisplay { /** * Service provider: Microsoft.Resources */ provider?: string; /** * Resource on which the operation is performed: Profile, endpoint, etc. */ resource?: string; /** * Operation type: Read, write, delete, etc. */ operation?: string; /** * Description of the operation. */ description?: string; } /** * Microsoft.Resources operation */ export interface Operation { /** * Operation name: {provider}/{resource}/{operation} */ name?: string; /** * The object that represents the operation. */ display?: OperationDisplay; } /** * Optional Parameters. */ export interface SubscriptionClientCheckResourceNameOptionalParams extends msRest.RequestOptionsBase { /** * Resource object with values for resource name and resource type */ resourceNameDefinition?: ResourceName; } /** * An interface representing SubscriptionClientOptions. */ export interface SubscriptionClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * Result of the request to list Microsoft.Resources operations. It contains a list of operations * and a URL link to get the next set of results. * @extends Array<Operation> */ export interface OperationListResult extends Array<Operation> { /** * URL to get the next set of operation list results if there are any. */ nextLink?: string; } /** * @interface * Location list operation response. * @extends Array<Location> */ export interface LocationListResult extends Array<Location> { } /** * @interface * Subscription list operation response. * @extends Array<Subscription> */ export interface SubscriptionListResult extends Array<Subscription> { /** * The URL to get the next set of results. */ nextLink: string; } /** * @interface * Tenant Ids information. * @extends Array<TenantIdDescription> */ export interface TenantListResult extends Array<TenantIdDescription> { /** * The URL to use for getting the next set of results. */ nextLink: string; } /** * Defines values for SubscriptionState. * Possible values include: 'Enabled', 'Warned', 'PastDue', 'Disabled', 'Deleted' * @readonly * @enum {string} */ export type SubscriptionState = 'Enabled' | 'Warned' | 'PastDue' | 'Disabled' | 'Deleted'; /** * Defines values for SpendingLimit. * Possible values include: 'On', 'Off', 'CurrentPeriodOff' * @readonly * @enum {string} */ export type SpendingLimit = 'On' | 'Off' | 'CurrentPeriodOff'; /** * Defines values for ResourceNameStatus. * Possible values include: 'Allowed', 'Reserved' * @readonly * @enum {string} */ export type ResourceNameStatus = 'Allowed' | 'Reserved'; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the listLocations operation. */ export type SubscriptionsListLocationsResponse = LocationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: LocationListResult; }; }; /** * Contains response data for the get operation. */ export type SubscriptionsGetResponse = Subscription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Subscription; }; }; /** * Contains response data for the list operation. */ export type SubscriptionsListResponse = SubscriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SubscriptionListResult; }; }; /** * Contains response data for the listNext operation. */ export type SubscriptionsListNextResponse = SubscriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SubscriptionListResult; }; }; /** * Contains response data for the list operation. */ export type TenantsListResponse = TenantListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: TenantListResult; }; }; /** * Contains response data for the listNext operation. */ export type TenantsListNextResponse = TenantListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: TenantListResult; }; }; /** * Contains response data for the checkResourceName operation. */ export type CheckResourceNameResponse = CheckResourceNameResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CheckResourceNameResult; }; };
the_stack
import { FsLocal } from '../FsLocal'; import * as fs from 'fs'; import { sep } from 'path'; import { describeUnix, describeWin, itUnix, getPath } from '../../../utils/test/helpers'; import mock from 'mock-fs'; import TmpDir from './fixtures/tmpDir'; let localAPI: any; const HOMEDIR = getPath('home'); const TESTS_DIR = getPath('tests_dir'); // needed to avoid crashes when console.log // is called and mock() has been called // see # console.log(''); describe('FsLocal', () => { describeUnix('isDirectoryNameValid', function () { beforeAll(() => { localAPI = new FsLocal.API('/', () => {}); }); it('unix: dir name cannot start with ../', function () { const isValid = localAPI.isDirectoryNameValid('../'); expect(isValid).toBe(false); }); it('unix: dir name cannot start with ./', function () { const isValid = localAPI.isDirectoryNameValid('./'); expect(isValid).toBe(false); }); it('unix: dir name cannot start with ../.', function () { const isValid = localAPI.isDirectoryNameValid('../.'); expect(isValid).toBe(false); }); }); // @todo add Windows specific tests for isDirectoryNameValid describe('resolve', function () { beforeAll(() => { localAPI = new FsLocal.API('/', () => {}); }); it('~ resolves to homedir', function () { const dir = localAPI.resolve('~'); expect(dir).toBe(HOMEDIR); }); }); describe('cd', function () { const filePath = `${TESTS_DIR}/file`; beforeAll(() => { mock(TmpDir); localAPI = new FsLocal.API('/', () => {}); }); afterAll(() => mock.restore()); it('should throw ENOTDIR if is not a directory', async function () { expect.assertions(1); try { await localAPI.cd(filePath); } catch (err) { expect(err.code).toBe('ENOTDIR'); } }); it('should throw if does not exist', async function () { expect.assertions(1); try { await localAPI.cd(`${filePath}__`); } catch (err) { expect(err.code).toBe('ENOENT'); } }); it('should return resolved path if exists and is a dir', function () { const dir = localAPI.resolve(TESTS_DIR); expect(dir).toBe(TESTS_DIR); }); it('should return resolved homedir path for ~', function () { expect.assertions(1); const dir = localAPI.resolve('~'); expect(dir).toBe(HOMEDIR); }); }); describe('size', function () { const SIZE_PATH = `${TESTS_DIR}/sizeTest`; beforeAll(() => { mock(TmpDir); localAPI = new FsLocal.API('/', () => {}); }); afterAll(() => mock.restore()); it('should return 0 if no files', async () => { expect.assertions(1); const size = await localAPI.size(__dirname, []); expect(size).toBe(0); }); it('should return correct size for 14 bytes file', async () => { expect.assertions(1); const size = await localAPI.size(SIZE_PATH, ['14bytes']); expect(size).toBe(14); }); it('should return correct size for several 14 + 1024 files', async () => { expect.assertions(1); const size = await localAPI.size(SIZE_PATH, ['14bytes', '1024bytes']); expect(size).toBe(1038); }); it('should throw ENOENT if file does not exist', async () => { expect.assertions(1); try { await localAPI.size(SIZE_PATH, ['15bytes']); } catch (err) { expect(err.code).toBe('ENOENT'); } }); }); describe('makedir', function () { const MAKEDIR_PATH = `${TESTS_DIR}${sep}makedirTest`; beforeAll(() => { localAPI = new FsLocal.API('/', () => {}); mock(TmpDir); }); afterAll(() => mock.restore()); it('should return success if folder already exists', async () => { expect.assertions(1); const resolved = await localAPI.makedir(MAKEDIR_PATH, ''); expect(resolved).toBe(MAKEDIR_PATH); }); // won't work with mock-fs unfortunately // it.only("should throw EACCES if source does not exist", async () => { // expect.assertions(1); // try { // await localAPI.makedir("/azerty", "foo"); // } catch (err) { // // Catalina now has RO system FS // expect(err.code).toMatch(/EACCES|EROFS/); // } // }); it('should throw EACCES if source is not readable', async () => { expect.assertions(1); try { await localAPI.makedir(`${MAKEDIR_PATH}/denied`, 'foo'); } catch (err) { expect(err.code).toBe('EACCES'); } }); it('should create a single folder', async () => { expect.assertions(1); const resolved = await localAPI.makedir(MAKEDIR_PATH, 'dir1'); expect(resolved).toBe(`${MAKEDIR_PATH}${sep}dir1`); }); it('should create several folders', async () => { expect.assertions(1); const resolved = await localAPI.makedir(MAKEDIR_PATH, 'dir2/dir3/dir4'); expect(resolved).toBe(`${MAKEDIR_PATH}${sep}dir2${sep}dir3${sep}dir4`); }); }); describe('makeSymLink', () => { const filePath = `${TESTS_DIR}/file`; beforeAll(() => { localAPI = new FsLocal.API('/', () => {}); mock(TmpDir); }); afterAll(() => mock.restore()); it('should create valid softlink', async () => { expect.assertions(1); const res = await localAPI.makeSymlink(filePath, '/link1'); expect(res).toBe(true); }); it('should create non valid softlink', async () => { expect.assertions(1); const res = await localAPI.makeSymlink('/not_here', '/link2'); expect(res).toBe(true); }); it('should throw EENOENT if link could not be created because link path does not exist', async () => { expect.assertions(1); try { await localAPI.makeSymlink(filePath, '/non/valid'); } catch (err) { expect(err.code).toBe('ENOENT'); } }); it('should throw EACCES if access was denied when creating link', async () => { expect.assertions(1); try { await localAPI.makeSymlink(filePath, `${TESTS_DIR}/makedirTest/denied/link`); } catch (err) { expect(err.code).toBe('EACCES'); } }); it('should throw EEXIST if file with that name already exists', async () => { expect.assertions(1); try { const res = await localAPI.makeSymlink(filePath, `${TESTS_DIR}/file`); } catch (err) { expect(err.code).toBe('EEXIST'); } }); }); describe('rename', () => { beforeAll(() => { localAPI = new FsLocal.API('/', () => {}); mock(TmpDir); }); afterAll(() => mock.restore()); it('should throw EEXIST if destination already exists', async () => { expect.assertions(1); try { await localAPI.rename(`${TESTS_DIR}/sizeTest`, { fullname: '14bytes' }, '1024bytes'); } catch (err) { expect(err.code).toBe('EEXIST'); } }); it('should throw ENOENT if source does not exist', async () => { expect.assertions(1); try { await localAPI.rename(`${TESTS_DIR}/sizeTest`, { fullname: 'nothing_here' }, 'new_file'); } catch (err) { expect(err.code).toBe('ENOENT'); } }); it('should throw EACCES if user cannot access destination folder', async () => { expect.assertions(1); try { await localAPI.rename(`${TESTS_DIR}/deleteTest/folder_denied`, { fullname: 'file2' }, 'new_file'); } catch (err) { expect(err.code).toBe('EACCES'); } }); it('should allow renaming a protected file', async () => { expect.assertions(1); const res = await localAPI.rename(`${TESTS_DIR}/deleteTest`, { fullname: 'file_denied' }, 'new_file'); expect(res).toBe('new_file'); }); it('should rename a file', async () => { expect.assertions(1); const res = await localAPI.rename(`${TESTS_DIR}`, { fullname: 'file' }, 'new_file'); expect(res).toBe('new_file'); }); }); describe('isDir', () => { beforeAll(() => { localAPI = new FsLocal.API('/', () => {}); mock(TmpDir); }); afterAll(() => mock.restore()); it('should return true if file is a directory', async () => { expect.assertions(1); const res = await localAPI.isDir(TESTS_DIR); expect(res).toBe(true); }); it('should return true if symlink is a directory', async () => { expect.assertions(1); const res = await localAPI.isDir(`${TESTS_DIR}/linkToSizeTest`); expect(res).toBe(true); }); it('should throw ENOENT if file cannot be accessed', async () => { expect.assertions(1); try { const res = await localAPI.isDir(`${TESTS_DIR}/deleteTest/fileDenied`); expect(res).toBe(false); } catch (err) { expect(err.code).toBe('ENOENT'); } }); it('should throw ENOENT if file does not exist', async () => { expect.assertions(1); try { await localAPI.isDir(`${TESTS_DIR}/not_here`); } catch (err) { expect(err.code).toBe('ENOENT'); } }); it('should return false if file is a symlink pointing to a file', async () => { expect.assertions(1); const res = await localAPI.isDir(`${TESTS_DIR}/link`); expect(res).toBe(false); }); it('should return false if path is a file', async () => { expect.assertions(1); const res = await localAPI.isDir(`${TESTS_DIR}/file`); expect(res).toBe(false); }); }); describe('exists', () => { beforeAll(() => { localAPI = new FsLocal.API('/', () => {}); mock(TmpDir); }); afterAll(() => mock.restore()); it('should resolve to true if file exists', async () => { expect.assertions(1); const res = await localAPI.exists(`${TESTS_DIR}/file`); expect(res).toBe(true); }); it('should resolve to false if file does not exists', async () => { expect.assertions(1); const res = await localAPI.exists(`${TESTS_DIR}/nothing`); expect(res).toBe(false); }); }); describe('stat', () => { beforeAll(() => { localAPI = new FsLocal.API('/', () => {}); mock(TmpDir); }); afterAll(() => mock.restore()); it('should return stat for existing file', async () => { const path = `${TESTS_DIR}/file`; expect.assertions(1); const fsStat = fs.statSync(path); const stat = await localAPI.stat(path); expect(stat).toEqual({ dir: TESTS_DIR, fullname: 'file', name: 'file', extension: '', cDate: fsStat.ctime, bDate: fsStat.birthtime, mDate: fsStat.mtime, length: fsStat.size, isDir: false, isSym: false, id: { dev: fsStat.dev, ino: fsStat.ino, }, mode: fsStat.mode, readonly: false, target: null, type: '', }); }); it('should return link target in target prop if file is a link', async () => { const path = `${TESTS_DIR}/link`; expect.assertions(1); const stat = await localAPI.stat(path); expect(stat.target).toBe('file'); }); it('should throw error if file does not exist', async () => { const path = `${TESTS_DIR}/nothing_here`; expect.assertions(1); try { await localAPI.stat(path); } catch (err) { expect(err.code).toBe('ENOENT'); } }); }); describe('login', () => { it('should resolve to true', async () => { expect.assertions(1); expect(localAPI.login()).resolves.toBe(undefined); }); }); // TODO: cannot be tested with mock-fs for now // describe('onList',() => { // it('should return ') // }); describe('list', () => { beforeAll(() => { localAPI = new FsLocal.API('/', () => {}); jest.spyOn(localAPI, 'onList').mockImplementation(() => {}); mock(TmpDir); }); afterEach(() => jest.clearAllMocks()); afterAll(() => { mock.restore(); }); it('should throw ENOENT if path does not exist', async () => { expect.assertions(1); try { await localAPI.list('/nothing'); } catch (err) { expect(err.code).toBe('ENOENT'); } }); it('should return every files found in path if it exists', async () => { expect.assertions(1); const files = await localAPI.list(TESTS_DIR); expect(files.length).toBe(6); }); it('should throw ENOTDIR if path is not a folder', async () => { expect.assertions(1); try { await localAPI.list(`${TESTS_DIR}/deleteTest/file`); } catch (err) { expect(err.code).toBe('ENOTDIR'); } }); // mock-fs doesn't check for mode access on Windows itUnix('should throw EACCES if cannot access folder', async () => { expect.assertions(1); try { await localAPI.list(`${TESTS_DIR}/deleteTest/folder_denied`); } catch (err) { expect(err.code).toBe('EACCES'); } }); it('should call onList with path when listing a valid directory and watchDir is true', async () => { expect.assertions(2); await localAPI.list(TESTS_DIR, true); expect(localAPI.onList).toHaveBeenCalledTimes(1); expect(localAPI.onList).toHaveBeenCalledWith(TESTS_DIR); }); it('should not call onList with path when listing a valid directory and watchDir is false', async () => { expect.assertions(1); await localAPI.list(TESTS_DIR, false); expect(localAPI.onList).not.toHaveBeenCalled(); }); }); describeUnix('isRoot', () => { beforeAll(() => { localAPI = new FsLocal.API('/', () => {}); }); it('should return false for empty path', () => { expect(localAPI.isRoot('')).toBe(false); }); it('should return true is path !== "/"', () => { expect(localAPI.isRoot('/foo')).toBe(false); }); it('should return true is path === "/"', () => { expect(localAPI.isRoot('/')).toBe(true); }); }); describeWin('isRoot', () => { beforeAll(() => { localAPI = new FsLocal.API('C:\\', () => {}); }); it('should return false for empty path', () => { expect(localAPI.isRoot('')).toBe(false); }); it('should return true is path !== "X:\\"', () => { expect(localAPI.isRoot('C:\\Windows')).toBe(false); }); it('should return true is path === "X:\\"', () => { expect(localAPI.isRoot('C:\\')).toBe(true); }); it('should return true if path === "\\\\"', () => { expect(localAPI.isRoot('\\\\')).toBe(true); }); it('should return false if path === "\\\\foo"', () => { expect(localAPI.isRoot('\\\\foo')).toBe(false); }); }); // // describe("delete", function() { // const DELETE_PATH = `${TESTS_DIR}/deleteTest`; // beforeAll(() => { // localAPI = new FsLocal.API("/", () => {}); // return prepareTmpTestFiles(); // }); // it('should resolve if file/folder does not exist', async () => { // expect.assertions(1); // const deleted = await localAPI.delete(`${DELETE_PATH}`, [{ // fullname: 'not_here' // }]); // expect(deleted).toBe(1); // }); // it('should throw EACCESS if file/folder is write protected', async () => { // expect.assertions(1); // process.stdout.write('ro'); // process.stdout.write(`++${DELETE_PATH}++`) // // const deleted = await localAPI.delete(`${DELETE_PATH}`, [{ // // fullname: 'file_denied' // // }]); // // expect(deleted).toBe(2); // expect(1).toBe(2); // }); // it("should delete single file and resolve if success", () => {}); // it("should delete empty folder and resolve if success", () => {}); // it("should delete not empty folder and resolve if success", () => {}); // it("should delete not empty folder + files and resolve", () => {}); // }); });
the_stack
import assert from 'assert'; import { r } from '../src'; import config from './config'; import { uuid } from './util/common'; describe('manipulating tables', () => { let dbName: string; before(async () => { await r.connectPool(config); // delete all but the system dbs await r .dbList() .filter(db => r .expr(['rethinkdb', 'test']) .contains(db) .not() ) .forEach(db => r.dbDrop(db)) .run(); dbName = uuid(); // export to the global scope const result = await r.dbCreate(dbName).run(); assert.equal(result.dbs_created, 1); }); after(async () => { // delete all but the system dbs await r .dbList() .filter(db => r .expr(['rethinkdb', 'test']) .contains(db) .not() ) .forEach(db => r.dbDrop(db)) .run(); await r.getPoolMaster().drain(); }); it('`tableList` should return a cursor', async () => { const result = await r .db(dbName) .tableList() .run(); assert(Array.isArray(result)); }); it('`tableList` should show the table we created', async () => { const tableName = uuid(); // export to the global scope const result1 = await r .db(dbName) .tableCreate(tableName) .run(); assert.equal(result1.tables_created, 1); const result2 = await r .db(dbName) .tableList() .run(); assert(Array.isArray(result2)); assert.equal(tableName, result2.find(name => name === tableName)); }); it('`tableCreate` should create a table', async () => { const tableName = uuid(); // export to the global scope const result = await r .db(dbName) .tableCreate(tableName) .run(); assert.equal(result.tables_created, 1); }); it('`tableCreate` should create a table -- primaryKey', async () => { const tableName = uuid(); const result1 = await r .db(dbName) .tableCreate(tableName, { primaryKey: 'foo' }) .run(); assert.equal(result1.tables_created, 1); const result2 = await r .db(dbName) .table(tableName) .info() .run(); assert.equal(result2.primary_key, 'foo'); }); it('`tableCreate` should create a table -- all args', async () => { const tableName = uuid(); const result1 = await r .db(dbName) .tableCreate(tableName, { durability: 'soft', primaryKey: 'foo' }) .run(); assert.equal(result1.tables_created, 1); // We can't really check other parameters... const result2 = await r .db(dbName) .table(tableName) .info() .run(); assert.equal(result2.primary_key, 'foo'); }); it('`tableCreate` should throw -- non valid args', async () => { try { const tableName = uuid(); await r .db(dbName) // @ts-ignore .tableCreate(tableName, { nonValidArg: true }) .run(); assert.fail('should throw'); } catch (e) { assert( e.message.startsWith( 'Unrecognized optional argument `non_valid_arg` in' ) ); } }); it('`tableCreate` should throw if no argument is given', async () => { try { // @ts-ignore await r .db(dbName) .tableCreate() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`tableCreate` takes at least 1 argument, 0 provided after:\nr.db("' + dbName + '")\n' ); } }); it('`tableCreate` should throw is the name contains special char', async () => { try { await r .db(dbName) .tableCreate('-_-') .run(); } catch (e) { assert( e.message.match(/Table name `-_-` invalid \(Use A-Za-z0-9_ only\)/) ); } }); it('`tableDrop` should drop a table', async () => { const tableName = uuid(); const result1 = await r .db(dbName) .tableCreate(tableName) .run(); assert.equal(result1.tables_created, 1); const result2 = await r .db(dbName) .tableList() .run(); assert(Array.isArray(result2)); assert.equal(result2.find(name => name === tableName), tableName); const result3 = await r .db(dbName) .tableDrop(tableName) .run(); assert.equal(result3.tables_dropped, 1); const result4 = await r .db(dbName) .tableList() .run(); assert(result4.find(name => name === tableName) === undefined); }); it('`tableDrop` should throw if no argument is given', async () => { try { // @ts-ignore await r .db(dbName) .tableDrop() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`tableDrop` takes 1 argument, 0 provided after:\nr.db("' + dbName + '")\n' ); } }); describe('indices', () => { const dbName1 = uuid(); const tableName1 = uuid(); before(async () => { const result1 = await r.dbCreate(dbName1).run(); assert.equal(result1.dbs_created, 1); const result2 = await r .db(dbName1) .tableCreate(tableName1) .run(); assert.equal(result2.tables_created, 1); }); it('index operations', async () => { const result1 = await r .db(dbName1) .table(tableName1) .indexCreate('newField') .run(); assert.deepEqual(result1, { created: 1 }); const result2 = await r .db(dbName1) .table(tableName1) .indexList() .run(); assert.deepEqual(result2, ['newField']); const result3 = await r .db(dbName1) .table(tableName1) .indexWait() .pluck('index', 'ready') .run(); assert.deepEqual(result3, [{ index: 'newField', ready: true }]); const result4 = await r .db(dbName1) .table(tableName1) .indexStatus() .pluck('index', 'ready') .run(); assert.deepEqual(result4, [{ index: 'newField', ready: true }]); const result5 = await r .db(dbName1) .table(tableName1) .indexDrop('newField') .run(); assert.deepEqual(result5, { dropped: 1 }); const result6 = await r .db(dbName1) .table(tableName1) .indexCreate('field1', doc => doc('field1')) .run(); assert.deepEqual(result6, { created: 1 }); const result7 = await r .db(dbName1) .table(tableName1) .indexWait('field1') .pluck('index', 'ready') .run(); assert.deepEqual(result7, [{ index: 'field1', ready: true }]); const result8 = await r .db(dbName1) .table(tableName1) .indexStatus('field1') .pluck('index', 'ready') .run(); assert.deepEqual(result8, [{ index: 'field1', ready: true }]); const result9 = await r .db(dbName1) .table(tableName1) .indexDrop('field1') .run(); assert.deepEqual(result9, { dropped: 1 }); }); it('`indexCreate` should work with options', async () => { let result = await r .db(dbName1) .table(tableName1) .indexCreate('foo', { multi: true }) .run(); assert.deepEqual(result, { created: 1 }); result = await r .db(dbName1) .table(tableName1) .indexCreate('foo1', row => row('foo'), { multi: true }) .run(); assert.deepEqual(result, { created: 1 }); result = await r .db(dbName1) .table(tableName1) .indexCreate('foo2', doc => doc('foo'), { multi: true }) .run(); assert.deepEqual(result, { created: 1 }); await r .db(dbName1) .table(tableName1) .indexWait() .run(); const result1 = await r .db(dbName1) .table(tableName1) .insert({ foo: ['bar1', 'bar2'], buzz: 1 }) .run(); assert.equal(result1.inserted, 1); const result2 = await r .db(dbName1) .table(tableName1) .insert({ foo: ['bar1', 'bar3'], buzz: 2 }) .run(); assert.equal(result2.inserted, 1); const result3 = await r .db(dbName1) .table(tableName1) .getAll('bar1', { index: 'foo' }) .count() .run(); assert.equal(result3, 2); const result4 = await r .db(dbName1) .table(tableName1) .getAll('bar1', { index: 'foo1' }) .count() .run(); assert.equal(result4, 2); const result5 = await r .db(dbName1) .table(tableName1) .getAll('bar1', { index: 'foo2' }) .count() .run(); assert.equal(result5, 2); const result6 = await r .db(dbName1) .table(tableName1) .getAll('bar2', { index: 'foo' }) .count() .run(); assert.equal(result6, 1); const result7 = await r .db(dbName1) .table(tableName1) .getAll('bar2', { index: 'foo1' }) .count() .run(); assert.equal(result7, 1); const result8 = await r .db(dbName1) .table(tableName1) .getAll('bar2', { index: 'foo2' }) .count() .run(); assert.equal(result8, 1); const result9 = await r .db(dbName1) .table(tableName1) .getAll('bar3', { index: 'foo' }) .count() .run(); assert.equal(result9, 1); const result10 = await r .db(dbName1) .table(tableName1) .getAll('bar3', { index: 'foo1' }) .count() .run(); assert.equal(result10, 1); const result11 = await r .db(dbName1) .table(tableName1) .getAll('bar3', { index: 'foo2' }) .count() .run(); assert.equal(result11, 1); // Test when the function is wrapped in an array const result12 = await r .db(dbName1) .table(tableName1) .indexCreate('buzz', row => [row('buzz')]) .run(); assert.deepEqual(result12, { created: 1 }); await r .db(dbName1) .table(tableName1) .indexWait() .run(); const result13 = await r .db(dbName1) .table(tableName1) .getAll([1], { index: 'buzz' }) .count() .run(); assert.equal(result13, 1); }); it('`indexCreate` should throw if no argument is passed', async () => { try { // @ts-ignore await r .db(dbName1) .table(tableName1) .indexCreate() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`indexCreate` takes at least 1 argument, 0 provided after:\nr.db("' + dbName1 + '").table("' + tableName1 + '")\n' ); } }); it('`indexDrop` should throw if no argument is passed', async () => { try { // @ts-ignore await r .db(dbName1) .table(tableName1) .indexDrop() .run(); assert.fail('should throw'); } catch (e) { assert.equal( e.message, '`indexDrop` takes 1 argument, 0 provided after:\nr.db("' + dbName1 + '").table("' + tableName1 + '")\n' ); } }); it('`indexRename` should work', async () => { const toRename = uuid(); const renamed = uuid(); const existing = uuid(); let result = await r .db(dbName1) .table(tableName1) .indexCreate(toRename) .run(); assert.deepEqual(result, { created: 1 }); result = await r .db(dbName1) .table(tableName1) .indexRename(toRename, renamed) .run(); assert.deepEqual(result, { renamed: 1 }); result = await r .db(dbName1) .table(tableName1) .indexCreate(existing) .run(); assert.deepEqual(result, { created: 1 }); result = await r .db(dbName1) .table(tableName1) .indexRename(renamed, existing, { overwrite: true }) .run(); assert.deepEqual(result, { renamed: 1 }); }); it('`indexRename` should not overwrite an index if not specified', async () => { try { const name = uuid(); const otherName = uuid(); let result = await r .db(dbName1) .table(tableName1) .indexCreate(name) .run(); assert.deepEqual(result, { created: 1 }); result = await r .db(dbName1) .table(tableName1) .indexCreate(otherName) .run(); assert.deepEqual(result, { created: 1 }); await r .db(dbName1) .table(tableName1) .indexRename(otherName, name) .run(); assert.fail('should throw'); } catch (e) { assert(e.message.match(/^Index `.*` already exists on table/)); } }); it('`indexRename` should throw -- non valid args', async () => { try { await r .db(dbName1) .table(tableName1) // @ts-ignore .indexRename('foo', 'bar', { nonValidArg: true }) .run(); assert.fail('should throw'); } catch (e) { assert( e.message.startsWith( 'Unrecognized optional argument `non_valid_arg` in' ) ); } }); }); });
the_stack
import { formatDate, formatNationalId, laws, formatGender, caseTypes, capitalize, formatAccusedByGender, } from '@island.is/judicial-system/formatters' import { CaseCustodyProvisions, CaseType, isRestrictionCase, SessionArrangements, } from '@island.is/judicial-system/types' import type { CaseGender } from '@island.is/judicial-system/types' function custodyProvisionsOrder(p: CaseCustodyProvisions) { switch (p) { case CaseCustodyProvisions._95_1_A: return 0 case CaseCustodyProvisions._95_1_B: return 1 case CaseCustodyProvisions._95_1_C: return 2 case CaseCustodyProvisions._95_1_D: return 3 case CaseCustodyProvisions._95_2: return 4 case CaseCustodyProvisions._99_1_B: return 6 case CaseCustodyProvisions._100_1: return 7 default: return 999 } } function custodyProvisionsCompare( p1: CaseCustodyProvisions, p2: CaseCustodyProvisions, ) { const o1 = custodyProvisionsOrder(p1) const o2 = custodyProvisionsOrder(p2) return o1 < o2 ? -1 : o1 > o2 ? 1 : 0 } export function formatCustodyProvisions( custodyProvisions?: CaseCustodyProvisions[], legalBasis?: string, ): string { const list = custodyProvisions ?.sort((p1, p2) => custodyProvisionsCompare(p1, p2)) .reduce((s, l) => `${s}${laws[l]}\n`, '') .slice(0, -1) return list ? legalBasis ? `${list}\n${legalBasis}` : list : legalBasis ? legalBasis : 'Lagaákvæði ekki skráð' } export function formatCourtHeadsUpSmsNotification( type: CaseType, prosecutorName?: string, arrestDate?: Date, requestedCourtDate?: Date, ): string { // Prosecutor const prosecutorText = ` Ákærandi: ${prosecutorName ?? 'Ekki skráður'}.` // Arrest date const arrestDateText = arrestDate ? ` Viðkomandi handtekinn ${formatDate(arrestDate, 'Pp')?.replace( ' ', ', kl. ', )}.` : '' // Court date const requestedCourtDateText = requestedCourtDate ? ` ÓE fyrirtöku ${formatDate(requestedCourtDate, 'Pp')?.replace( ' ', ', eftir kl. ', )}.` : '' const newCaseText = `Ný ${ type === CaseType.CUSTODY ? 'gæsluvarðhaldskrafa' : type === CaseType.TRAVEL_BAN ? 'farbannskrafa' : type === CaseType.OTHER ? 'krafa um rannsóknarheimild' : `krafa um rannsóknarheimild (${caseTypes[type]})` } í vinnslu.` return `${newCaseText}${prosecutorText}${arrestDateText}${requestedCourtDateText}` } export function formatCourtReadyForCourtSmsNotification( type: CaseType, prosecutorName?: string, court?: string, ) { const submittedCaseText = type === CaseType.CUSTODY ? 'Gæsluvarðhaldskrafa' : type === CaseType.TRAVEL_BAN ? 'Farbannskrafa' : type === CaseType.OTHER ? 'Krafa um rannsóknarheimild' : `Krafa um rannsóknarheimild (${caseTypes[type]})` const prosecutorText = ` Ákærandi: ${prosecutorName ?? 'Ekki skráður'}.` const courtText = ` Dómstóll: ${court ?? 'Ekki skráður'}.` return `${submittedCaseText} tilbúin til afgreiðslu.${prosecutorText}${courtText}` } export function formatProsecutorReceivedByCourtSmsNotification( type: CaseType, court?: string, courtCaseNumber?: string, ): string { const receivedCaseText = isRestrictionCase(type) ? `${caseTypes[type]}` : type === CaseType.OTHER ? 'rannsóknarheimild' : `rannsóknarheimild (${caseTypes[type]})` return `${court} hefur móttekið kröfu um ${receivedCaseText} sem þú sendir og úthlutað málsnúmerinu ${courtCaseNumber}. Sjá nánar á rettarvorslugatt.island.is.` } export function formatProsecutorCourtDateEmailNotification( type: CaseType, court?: string, courtDate?: Date, courtRoom?: string, judgeName?: string, registrarName?: string, defenderName?: string, defenderIsSpokesperson?: boolean, sessionArrangements = SessionArrangements.ALL_PRESENT, // Defaults to ALL_PRESENT when not specified ): string { const scheduledCaseText = type === CaseType.CUSTODY ? 'gæsluvarðhaldskröfu' : type === CaseType.TRAVEL_BAN ? 'farbannskröfu' : type === CaseType.OTHER ? 'kröfu um rannsóknarheimild' : `kröfu um rannsóknarheimild (${caseTypes[type]})` const courtDateText = formatDate(courtDate, 'PPPp')?.replace(' kl.', ', kl.') const courtRoomText = sessionArrangements === SessionArrangements.REMOTE_SESSION ? 'Úrskurðað verður um kröfuna án mætingar af hálfu málsaðila' : courtRoom ? `Dómsalur: ${courtRoom}` : 'Dómsalur hefur ekki verið skráður' const judgeText = judgeName ? `Dómari: ${judgeName}` : 'Dómari hefur ekki verið skráður' const registrarText = registrarName ? `Dómritari: ${registrarName}` : 'Dómritari hefur ekki verið skráður' const defenderText = defenderName ? `${ defenderIsSpokesperson ? 'Talsmaður' : 'Verjandi' } sakbornings: ${defenderName}` : `${ defenderIsSpokesperson ? 'Talsmaður' : 'Verjandi' } sakbornings hefur ekki verið skráður` return `${court} hefur staðfest fyrirtökutíma fyrir ${scheduledCaseText}.<br /><br />Fyrirtaka mun fara fram ${courtDateText}.<br /><br />${courtRoomText}.<br /><br />${judgeText}.<br /><br />${registrarText}.<br /><br />${defenderText}.` } export function formatPrisonCourtDateEmailNotification( prosecutorOffice?: string, court?: string, courtDate?: Date, accusedName?: string, accusedGender?: CaseGender, requestedValidToDate?: Date, isolation?: boolean, defenderName?: string, defenderIsSpokesperson?: boolean, isExtension?: boolean, ): string { const courtText = court?.replace('dómur', 'dóms') const courtDateText = formatDate(courtDate, 'PPPPp') ?.replace('dagur,', 'daginn') ?.replace(' kl.', ', kl.') const requestedValidToDateText = formatDate(requestedValidToDate, 'PPPPp') ?.replace('dagur,', 'dagsins') ?.replace(' kl.', ', kl.') const requestText = `Nafn sakbornings: ${accusedName}.<br /><br />Kyn sakbornings: ${formatGender( accusedGender, )}.<br /><br />Krafist er gæsluvarðhalds til ${requestedValidToDateText}.` const isolationText = isolation ? 'Farið er fram á einangrun.' : 'Ekki er farið fram á einangrun.' const defenderText = defenderName ? `${ defenderIsSpokesperson ? 'Talsmaður' : 'Verjandi' } sakbornings: ${defenderName}` : `${ defenderIsSpokesperson ? 'Talsmaður' : 'Verjandi' } sakbornings hefur ekki verið skráður` return `${prosecutorOffice} hefur sent kröfu um ${ isExtension ? 'áframhaldandi ' : '' }gæsluvarðhald til ${courtText} og verður málið tekið fyrir ${courtDateText}.<br /><br />${requestText}<br /><br />${isolationText}<br /><br />${defenderText}.` } export function formatDefenderCourtDateEmailNotification( court?: string, courtCaseNumber?: string, courtDate?: Date, courtRoom?: string, defenderIsSpokesperson = false, ): string { return `${court} hefur boðað þig í fyrirtöku sem ${ defenderIsSpokesperson ? 'talsmann' : 'verjanda' } sakbornings.<br /><br />Fyrirtaka mun fara fram ${formatDate( courtDate, 'PPPPp', ) ?.replace('dagur,', 'daginn') ?.replace( ' kl.', ', kl.', )}.<br /><br />Málsnúmer: ${courtCaseNumber}.<br /><br />${ courtRoom ? `Dómsalur: ${courtRoom}` : 'Dómsalur hefur ekki verið skráður' }.` } // This function is only intended for case type CUSTODY export function formatPrisonRulingEmailNotification( courtEndTime?: Date, ): string { return `Meðfylgjandi er vistunarseðill gæsluvarðhaldsfanga sem var úrskurðaður í gæsluvarðhald í héraðsdómi ${formatDate( courtEndTime, 'PPP', )}.` } export function formatCourtRevokedSmsNotification( type: CaseType, prosecutorName?: string, requestedCourtDate?: Date, courtDate?: Date, ) { // Prosecutor const prosecutorText = ` Ákærandi: ${prosecutorName ?? 'Ekki skráður'}.` // Court date const courtDateText = courtDate ? ` Fyrirtökutími: ${formatDate(courtDate, 'Pp')?.replace(' ', ', kl. ')}.` : requestedCourtDate ? ` ÓVE fyrirtöku ${formatDate(requestedCourtDate, 'Pp')?.replace( ' ', ', eftir kl. ', )}.` : '' return `${ type === CaseType.CUSTODY ? 'Gæsluvarðhaldskrafa' : 'Farbannskrafa' } afturkölluð.${prosecutorText}${courtDateText}` } export function formatPrisonRevokedEmailNotification( prosecutorOffice?: string, court?: string, courtDate?: Date, accusedName?: string, defenderName?: string, isExtension?: boolean, ): string { const courtText = court?.replace('dómur', 'dóms') const courtDateText = formatDate(courtDate, 'PPPPp') ?.replace('dagur,', 'daginn') ?.replace(' kl.', ', kl.') const accusedNameText = `Nafn sakbornings: ${accusedName}.` const defenderText = defenderName ? `Verjandi sakbornings: ${defenderName}` : 'Verjandi sakbornings hefur ekki verið skráður' return `${prosecutorOffice} hefur afturkallað kröfu um ${ isExtension ? 'áframhaldandi ' : '' }gæsluvarðhald sem send var til ${courtText} og taka átti fyrir ${courtDateText}.<br /><br />${accusedNameText}<br /><br />${defenderText}.` } export function formatDefenderRevokedEmailNotification( type: CaseType, accusedNationalId: string, accusedName?: string, court?: string, courtDate?: Date, ): string { const courtText = court?.replace('dómur', 'dómi') const courtDateText = formatDate(courtDate, 'PPPPp') ?.replace('dagur,', 'daginn') ?.replace(' kl.', ', kl.') return `${ type === CaseType.CUSTODY ? 'Gæsluvarðhaldskrafa' : 'Farbannskrafa' } sem taka átti fyrir hjá ${courtText} ${courtDateText}, hefur verið afturkölluð.<br /><br />Sakborningur: ${accusedName}, kt. ${formatNationalId( accusedNationalId, )}.<br /><br />Dómstóllinn hafði skráð þig sem verjanda sakbornings.` } export function stripHtmlTags(html: string): string { return html.replace(/(?:<br \/>)/g, '\n').replace(/(?:<\/?strong>)/g, '') } export function formatCustodyIsolation( gender?: CaseGender, isolationToDate?: Date, ) { return `${capitalize( formatAccusedByGender(gender), )} skal sæta einangrun til ${formatDate(isolationToDate, 'PPPPp') ?.replace('dagur,', 'dagsins') ?.replace(' kl.', ', kl.')}.` }
the_stack
/* * Copyright (c) 2016 - now David Sehnal, licensed under Apache 2.0, See LICENSE file for more info. */ namespace LiteMol.Core.Formats.Molecule.PDB { "use strict"; class Tokenizer { private length: number; trimmedToken = { start: 0, end: 0 }; line: number = 0; position: number = 0; moveToNextLine() { while (this.position < this.length && this.data.charCodeAt(this.position) !== 10) { this.position++; } this.position++; this.line++; return this.position; } moveToEndOfLine() { while (this.position < this.length) { let c = this.data.charCodeAt(this.position); if (c === 10 || c === 13) { // /n | /r return this.position; } this.position++; } return this.position; } startsWith(start: number, value: string) { for (let i = value.length - 1; i >= 0; i--) { if (this.data.charCodeAt(i + start) !== value.charCodeAt(i)) { return false; } } return true; } trim(start: number, end: number) { while (start < end && this.data.charCodeAt(start) === 32) start++; while (end > start && this.data.charCodeAt(end - 1) === 32) end--; this.trimmedToken.start = start; this.trimmedToken.end = end; } tokenizeAtomRecord(tokens: TokenIndexBuilder): boolean { let startPos = this.position; let start = this.position; let end = this.moveToEndOfLine(); let length = end - start; // invalid atom record if (length < 60) return false; //COLUMNS DATA TYPE CONTENTS //-------------------------------------------------------------------------------- // 1 - 6 Record name "ATOM " this.trim(start, start + 6); TokenIndexBuilder.addToken(tokens, this.trimmedToken.start, this.trimmedToken.end); // 7 - 11 Integer Atom serial number. start = startPos + 6; this.trim(start, start + 5); TokenIndexBuilder.addToken(tokens, this.trimmedToken.start, this.trimmedToken.end); //13 - 16 Atom Atom name. start = startPos + 12; this.trim(start, start + 4); TokenIndexBuilder.addToken(tokens, this.trimmedToken.start, this.trimmedToken.end); //17 Character Alternate location indicator. if (this.data.charCodeAt(startPos + 16) === 32) { // ' ' TokenIndexBuilder.addToken(tokens, 0, 0); } else { TokenIndexBuilder.addToken(tokens, startPos + 16, startPos + 17); } //18 - 20 Residue name Residue name. start = startPos + 17; this.trim(start, start + 3); TokenIndexBuilder.addToken(tokens, this.trimmedToken.start, this.trimmedToken.end); //22 Character Chain identifier. TokenIndexBuilder.addToken(tokens, startPos + 21, startPos + 22); //23 - 26 Integer Residue sequence number. start = startPos + 22; this.trim(start, start + 4); TokenIndexBuilder.addToken(tokens, this.trimmedToken.start, this.trimmedToken.end); //27 AChar Code for insertion of residues. if (this.data.charCodeAt(startPos + 26) === 32) { // ' ' TokenIndexBuilder.addToken(tokens, 0, 0); } else { TokenIndexBuilder.addToken(tokens, startPos + 26, startPos + 27); } //31 - 38 Real(8.3) Orthogonal coordinates for X in Angstroms. start = startPos + 30; this.trim(start, start + 8); TokenIndexBuilder.addToken(tokens, this.trimmedToken.start, this.trimmedToken.end); //39 - 46 Real(8.3) Orthogonal coordinates for Y in Angstroms. start = startPos + 38; this.trim(start, start + 8); TokenIndexBuilder.addToken(tokens, this.trimmedToken.start, this.trimmedToken.end); //47 - 54 Real(8.3) Orthogonal coordinates for Z in Angstroms. start = startPos + 46; this.trim(start, start + 8); TokenIndexBuilder.addToken(tokens, this.trimmedToken.start, this.trimmedToken.end); //55 - 60 Real(6.2) Occupancy. start = startPos + 54; this.trim(start, start + 6); TokenIndexBuilder.addToken(tokens, this.trimmedToken.start, this.trimmedToken.end); //61 - 66 Real(6.2) Temperature factor (Default = 0.0). if (length >= 66) { start = startPos + 60; this.trim(start, start + 6); TokenIndexBuilder.addToken(tokens, this.trimmedToken.start, this.trimmedToken.end); } else { TokenIndexBuilder.addToken(tokens, 0, 0); } //73 - 76 LString(4) Segment identifier, left-justified. // ignored //77 - 78 LString(2) Element symbol, right-justified. if (length >= 78) { start = startPos + 76; this.trim(start, start + 2); if (this.trimmedToken.start < this.trimmedToken.end) { TokenIndexBuilder.addToken(tokens, this.trimmedToken.start, this.trimmedToken.end); } else { TokenIndexBuilder.addToken(tokens, startPos + 12, startPos + 13); } } else { TokenIndexBuilder.addToken(tokens, startPos + 12, startPos + 13); } //79 - 80 LString(2) Charge on the atom. // ignored return true; } constructor(private data: string) { this.length = data.length; } } export class Parser { private static tokenizeAtom(tokens: TokenIndexBuilder, tokenizer: Tokenizer): ParserError | undefined { if (tokenizer.tokenizeAtomRecord(tokens)) { return void 0; } return new ParserError("Invalid ATOM/HETATM record.", tokenizer.line); } private static tokenize(id: string, data: string): PDB.MoleculeData | ParserError { const tokenizer = new Tokenizer(data); const length = data.length; let modelAtomTokens: TokenIndexBuilder | null = TokenIndexBuilder.create(4096); //2 * 14 * this.data.length / 78); let atomCount = 0; let models: PDB.ModelData[] = []; let cryst: PDB.CrystStructureInfo | undefined = void 0; let modelIdToken = { start: 0, end: 0 }; while (tokenizer.position < length) { let cont = true; switch (data.charCodeAt(tokenizer.position)) { case 65: // A if (tokenizer.startsWith(tokenizer.position, "ATOM")) { if (!modelAtomTokens) { modelAtomTokens = TokenIndexBuilder.create(4096); } let err = Parser.tokenizeAtom(modelAtomTokens, tokenizer); atomCount++; if (err) return err; } break; case 67: // C if (tokenizer.startsWith(tokenizer.position, "CRYST1")) { let start = tokenizer.position; let end = tokenizer.moveToEndOfLine(); cryst = new CrystStructureInfo(data.substring(start, end)); } break; case 69: // E if (tokenizer.startsWith(tokenizer.position, "ENDMDL") && atomCount > 0) { if (models.length === 0) { modelIdToken = { start: data.length + 3, end: data.length + 4 }; } if (modelAtomTokens) { models.push(new ModelData(modelIdToken, <any>modelAtomTokens.tokens, atomCount)); } atomCount = 0; modelAtomTokens = null; } else if (tokenizer.startsWith(tokenizer.position, "END")) { let start = tokenizer.position; let end = tokenizer.moveToEndOfLine(); tokenizer.trim(start, end); if (tokenizer.trimmedToken.end - tokenizer.trimmedToken.start === 3) { cont = false; } } break; case 72: // H if (tokenizer.startsWith(tokenizer.position, "HETATM")) { if (!modelAtomTokens) { modelAtomTokens = TokenIndexBuilder.create(4096); } let err = Parser.tokenizeAtom(modelAtomTokens, tokenizer); atomCount++; if (err) return err; } break; case 77: //M if (tokenizer.startsWith(tokenizer.position, "MODEL")) { if (atomCount > 0) { if (models.length === 0) { modelIdToken = { start: data.length + 3, end: data.length + 4 }; } if (modelAtomTokens) { models.push(new ModelData(modelIdToken, <any>modelAtomTokens.tokens, atomCount)); } } let start = tokenizer.position + 6; let end = tokenizer.moveToEndOfLine(); tokenizer.trim(start, end); modelIdToken = { start: tokenizer.trimmedToken.start, end: tokenizer.trimmedToken.end }; if (atomCount > 0 || !modelAtomTokens) { modelAtomTokens = TokenIndexBuilder.create(4096); } atomCount = 0; } break; } tokenizer.moveToNextLine(); if (!cont) break; } let fakeCifData = data + ".?0123"; if (atomCount > 0) { if (models.length === 0) { modelIdToken = { start: data.length + 3, end: data.length + 4 }; } if (modelAtomTokens) { models.push(new ModelData(modelIdToken, <any>modelAtomTokens.tokens, atomCount)); } } return new MoleculeData( new Header(id), cryst, new ModelsData(models), fakeCifData ); } static getDotRange(length: number): TokenRange { return { start: length - 6, end: length - 5 }; } static getNumberRanges(length: number): Utils.FastMap<number, TokenRange> { let ret = Utils.FastMap.create<number, TokenRange>(); for (let i = 0; i < 4; i++) { ret.set(i, { start: length - 4 + i, end: length - 3 + i }); } return ret; } static getQuestionmarkRange(length: number): TokenRange { return { start: length - 5, end: length - 4 }; } static parse(id: string, data: string): ParserResult<CIF.File> { let ret = Parser.tokenize(id, data); if (ret instanceof ParserError) { return ParserResult.error<CIF.File>(ret.message, ret.line); } else { return ParserResult.success(ret.toCifFile()); } } } export function toCifFile(id:string, data: string) { return Parser.parse(id, data); } }
the_stack
import type { ActionDefaults } from '@interactjs/core/options' import type { Element, EdgeOptions, PointerEventType, PointerType, FullRect, CoordsSet, } from '@interactjs/types/index' import * as arr from '@interactjs/utils/arr' import extend from '@interactjs/utils/extend' import hypot from '@interactjs/utils/hypot' import { warnOnce, copyAction } from '@interactjs/utils/misc' import * as pointerUtils from '@interactjs/utils/pointerUtils' import * as rectUtils from '@interactjs/utils/rect' import type { EventPhase } from './InteractEvent' import { InteractEvent } from './InteractEvent' import type { Interactable } from './Interactable' import { PointerInfo } from './PointerInfo' import type { ActionName, Scope } from './scope' export interface ActionProps<T extends ActionName | null = never> { name: T axis?: 'x' | 'y' | 'xy' | null edges?: EdgeOptions | null } export enum _ProxyValues { interactable = '', element = '', prepared = '', pointerIsDown = '', pointerWasMoved = '', _proxy = '', } export enum _ProxyMethods { start = '', move = '', end = '', stop = '', interacting = '', } export type PointerArgProps<T extends {} = {}> = { pointer: PointerType event: PointerEventType eventTarget: Node pointerIndex: number pointerInfo: PointerInfo interaction: Interaction<never> } & T export interface DoPhaseArg<T extends ActionName, P extends EventPhase> { event: PointerEventType phase: EventPhase interaction: Interaction<T> iEvent: InteractEvent<T, P> preEnd?: boolean type?: string } export type DoAnyPhaseArg = DoPhaseArg<ActionName, EventPhase> declare module '@interactjs/core/scope' { interface SignalArgs { 'interactions:new': { interaction: Interaction<ActionName> } 'interactions:down': PointerArgProps<{ type: 'down' }> 'interactions:move': PointerArgProps<{ type: 'move' dx: number dy: number duplicate: boolean }> 'interactions:up': PointerArgProps<{ type: 'up' curEventTarget: EventTarget }> 'interactions:cancel': SignalArgs['interactions:up'] & { type: 'cancel' curEventTarget: EventTarget } 'interactions:update-pointer': PointerArgProps<{ down: boolean }> 'interactions:remove-pointer': PointerArgProps 'interactions:blur': { interaction: Interaction<never>, event: Event, type: 'blur' } 'interactions:before-action-start': Omit<DoAnyPhaseArg, 'iEvent'> 'interactions:action-start': DoAnyPhaseArg 'interactions:after-action-start': DoAnyPhaseArg 'interactions:before-action-move': Omit<DoAnyPhaseArg, 'iEvent'> 'interactions:action-move': DoAnyPhaseArg 'interactions:after-action-move': DoAnyPhaseArg 'interactions:before-action-end': Omit<DoAnyPhaseArg, 'iEvent'> 'interactions:action-end': DoAnyPhaseArg 'interactions:after-action-end': DoAnyPhaseArg 'interactions:stop': { interaction: Interaction } } } export type InteractionProxy<T extends ActionName | null = never> = Pick< Interaction<T>, keyof typeof _ProxyValues | keyof typeof _ProxyMethods > let idCounter = 0 export class Interaction<T extends ActionName | null = ActionName> { // current interactable being interacted with interactable: Interactable = null // the target element of the interactable element: Element = null rect: FullRect _rects?: { start: FullRect corrected: FullRect previous: FullRect delta: FullRect } edges: EdgeOptions _scopeFire: Scope['fire'] // action that's ready to be fired on next move event prepared: ActionProps<T> = { name: null, axis: null, edges: null, } pointerType: string // keep track of added pointers pointers: PointerInfo[] = [] // pointerdown/mousedown/touchstart event downEvent: PointerEventType = null downPointer: PointerType = {} as PointerType _latestPointer: { pointer: PointerType event: PointerEventType eventTarget: Node } = { pointer: null, event: null, eventTarget: null, } // previous action event prevEvent: InteractEvent<T, EventPhase> = null pointerIsDown = false pointerWasMoved = false _interacting = false _ending = false _stopped = true _proxy: InteractionProxy<T> = null simulation = null /** @internal */ get pointerMoveTolerance () { return 1 } /** * @alias Interaction.prototype.move */ doMove = warnOnce(function (this: Interaction, signalArg: any) { this.move(signalArg) }, 'The interaction.doMove() method has been renamed to interaction.move()') coords: CoordsSet = { // Starting InteractEvent pointer coordinates start: pointerUtils.newCoords(), // Previous native pointer move event coordinates prev: pointerUtils.newCoords(), // current native pointer move event coordinates cur: pointerUtils.newCoords(), // Change in coordinates and time of the pointer delta: pointerUtils.newCoords(), // pointer velocity velocity: pointerUtils.newCoords(), } readonly _id: number = idCounter++ /** */ constructor ({ pointerType, scopeFire }: { pointerType?: string, scopeFire: Scope['fire'] }) { this._scopeFire = scopeFire this.pointerType = pointerType const that = this this._proxy = {} as InteractionProxy<T> for (const key in _ProxyValues) { Object.defineProperty(this._proxy, key, { get () { return that[key] }, }) } for (const key in _ProxyMethods) { Object.defineProperty(this._proxy, key, { value: (...args: any[]) => that[key](...args), }) } this._scopeFire('interactions:new', { interaction: this }) } pointerDown (pointer: PointerType, event: PointerEventType, eventTarget: Node) { const pointerIndex = this.updatePointer(pointer, event, eventTarget, true) const pointerInfo = this.pointers[pointerIndex] this._scopeFire('interactions:down', { pointer, event, eventTarget, pointerIndex, pointerInfo, type: 'down', interaction: (this as unknown) as Interaction<never>, }) } /** * ```js * interact(target) * .draggable({ * // disable the default drag start by down->move * manualStart: true * }) * // start dragging after the user holds the pointer down * .on('hold', function (event) { * var interaction = event.interaction * * if (!interaction.interacting()) { * interaction.start({ name: 'drag' }, * event.interactable, * event.currentTarget) * } * }) * ``` * * Start an action with the given Interactable and Element as tartgets. The * action must be enabled for the target Interactable and an appropriate * number of pointers must be held down - 1 for drag/resize, 2 for gesture. * * Use it with `interactable.<action>able({ manualStart: false })` to always * [start actions manually](https://github.com/taye/interact.js/issues/114) * * @param {object} action The action to be performed - drag, resize, etc. * @param {Interactable} target The Interactable to target * @param {Element} element The DOM Element to target * @return {Boolean} Whether the interaction was successfully started */ start<A extends ActionName> (action: ActionProps<A>, interactable: Interactable, element: Element): boolean { if ( this.interacting() || !this.pointerIsDown || this.pointers.length < (action.name === 'gesture' ? 2 : 1) || !interactable.options[action.name as keyof ActionDefaults].enabled ) { return false } copyAction(this.prepared, action) this.interactable = interactable this.element = element this.rect = interactable.getRect(element) this.edges = this.prepared.edges ? extend({}, this.prepared.edges) : { left: true, right: true, top: true, bottom: true } this._stopped = false this._interacting = this._doPhase({ interaction: this, event: this.downEvent, phase: 'start', }) && !this._stopped return this._interacting } pointerMove (pointer: PointerType, event: PointerEventType, eventTarget: Node) { if (!this.simulation && !(this.modification && this.modification.endResult)) { this.updatePointer(pointer, event, eventTarget, false) } const duplicateMove = this.coords.cur.page.x === this.coords.prev.page.x && this.coords.cur.page.y === this.coords.prev.page.y && this.coords.cur.client.x === this.coords.prev.client.x && this.coords.cur.client.y === this.coords.prev.client.y let dx: number let dy: number // register movement greater than pointerMoveTolerance if (this.pointerIsDown && !this.pointerWasMoved) { dx = this.coords.cur.client.x - this.coords.start.client.x dy = this.coords.cur.client.y - this.coords.start.client.y this.pointerWasMoved = hypot(dx, dy) > this.pointerMoveTolerance } const pointerIndex = this.getPointerIndex(pointer) const signalArg = { pointer, pointerIndex, pointerInfo: this.pointers[pointerIndex], event, type: 'move' as const, eventTarget, dx, dy, duplicate: duplicateMove, interaction: (this as unknown) as Interaction<never>, } if (!duplicateMove) { // set pointer coordinate, time changes and velocity pointerUtils.setCoordVelocity(this.coords.velocity, this.coords.delta) } this._scopeFire('interactions:move', signalArg) if (!duplicateMove && !this.simulation) { // if interacting, fire an 'action-move' signal etc if (this.interacting()) { signalArg.type = null this.move(signalArg) } if (this.pointerWasMoved) { pointerUtils.copyCoords(this.coords.prev, this.coords.cur) } } } /** * ```js * interact(target) * .draggable(true) * .on('dragmove', function (event) { * if (someCondition) { * // change the snap settings * event.interactable.draggable({ snap: { targets: [] }}) * // fire another move event with re-calculated snap * event.interaction.move() * } * }) * ``` * * Force a move of the current action at the same coordinates. Useful if * snap/restrict has been changed and you want a movement with the new * settings. */ move (signalArg?: any) { if (!signalArg || !signalArg.event) { pointerUtils.setZeroCoords(this.coords.delta) } signalArg = extend( { pointer: this._latestPointer.pointer, event: this._latestPointer.event, eventTarget: this._latestPointer.eventTarget, interaction: this, }, signalArg || {}, ) signalArg.phase = 'move' this._doPhase(signalArg) } // End interact move events and stop auto-scroll unless simulation is running pointerUp (pointer: PointerType, event: PointerEventType, eventTarget: Node, curEventTarget: EventTarget) { let pointerIndex = this.getPointerIndex(pointer) if (pointerIndex === -1) { pointerIndex = this.updatePointer(pointer, event, eventTarget, false) } const type = /cancel$/i.test(event.type) ? 'cancel' : 'up' this._scopeFire(`interactions:${type}` as 'interactions:up' | 'interactions:cancel', { pointer, pointerIndex, pointerInfo: this.pointers[pointerIndex], event, eventTarget, type: type as any, curEventTarget, interaction: (this as unknown) as Interaction<never>, }) if (!this.simulation) { this.end(event) } this.removePointer(pointer, event) } documentBlur (event: Event) { this.end(event as any) this._scopeFire('interactions:blur', { event, type: 'blur', interaction: (this as unknown) as Interaction<never>, }) } /** * ```js * interact(target) * .draggable(true) * .on('move', function (event) { * if (event.pageX > 1000) { * // end the current action * event.interaction.end() * // stop all further listeners from being called * event.stopImmediatePropagation() * } * }) * ``` * * @param {PointerEvent} [event] */ end (event?: PointerEventType) { this._ending = true event = event || this._latestPointer.event let endPhaseResult: boolean if (this.interacting()) { endPhaseResult = this._doPhase({ event, interaction: this, phase: 'end', }) } this._ending = false if (endPhaseResult === true) { this.stop() } } currentAction () { return this._interacting ? this.prepared.name : null } interacting () { return this._interacting } /** */ stop () { this._scopeFire('interactions:stop', { interaction: this }) this.interactable = this.element = null this._interacting = false this._stopped = true this.prepared.name = this.prevEvent = null } getPointerIndex (pointer: PointerType) { const pointerId = pointerUtils.getPointerId(pointer) // mouse and pen interactions may have only one pointer return this.pointerType === 'mouse' || this.pointerType === 'pen' ? this.pointers.length - 1 : arr.findIndex(this.pointers, (curPointer) => curPointer.id === pointerId) } getPointerInfo (pointer: any) { return this.pointers[this.getPointerIndex(pointer)] } updatePointer (pointer: PointerType, event: PointerEventType, eventTarget: Node, down?: boolean) { const id = pointerUtils.getPointerId(pointer) let pointerIndex = this.getPointerIndex(pointer) let pointerInfo = this.pointers[pointerIndex] down = down === false ? false : down || /(down|start)$/i.test(event.type) if (!pointerInfo) { pointerInfo = new PointerInfo(id, pointer, event, null, null) pointerIndex = this.pointers.length this.pointers.push(pointerInfo) } else { pointerInfo.pointer = pointer } pointerUtils.setCoords( this.coords.cur, this.pointers.map((p) => p.pointer), this._now(), ) pointerUtils.setCoordDeltas(this.coords.delta, this.coords.prev, this.coords.cur) if (down) { this.pointerIsDown = true pointerInfo.downTime = this.coords.cur.timeStamp pointerInfo.downTarget = eventTarget pointerUtils.pointerExtend(this.downPointer, pointer) if (!this.interacting()) { pointerUtils.copyCoords(this.coords.start, this.coords.cur) pointerUtils.copyCoords(this.coords.prev, this.coords.cur) this.downEvent = event this.pointerWasMoved = false } } this._updateLatestPointer(pointer, event, eventTarget) this._scopeFire('interactions:update-pointer', { pointer, event, eventTarget, down, pointerInfo, pointerIndex, interaction: (this as unknown) as Interaction<never>, }) return pointerIndex } removePointer (pointer: PointerType, event: PointerEventType) { const pointerIndex = this.getPointerIndex(pointer) if (pointerIndex === -1) return const pointerInfo = this.pointers[pointerIndex] this._scopeFire('interactions:remove-pointer', { pointer, event, eventTarget: null, pointerIndex, pointerInfo, interaction: (this as unknown) as Interaction<never>, }) this.pointers.splice(pointerIndex, 1) this.pointerIsDown = false } _updateLatestPointer (pointer: PointerType, event: PointerEventType, eventTarget: Node) { this._latestPointer.pointer = pointer this._latestPointer.event = event this._latestPointer.eventTarget = eventTarget } destroy () { this._latestPointer.pointer = null this._latestPointer.event = null this._latestPointer.eventTarget = null } _createPreparedEvent<P extends EventPhase> ( event: PointerEventType, phase: P, preEnd?: boolean, type?: string, ) { return new InteractEvent<T, P>(this, event, this.prepared.name, phase, this.element, preEnd, type) } _fireEvent<P extends EventPhase> (iEvent: InteractEvent<T, P>) { this.interactable.fire(iEvent) if (!this.prevEvent || iEvent.timeStamp >= this.prevEvent.timeStamp) { this.prevEvent = iEvent } } _doPhase<P extends EventPhase> ( signalArg: Omit<DoPhaseArg<T, P>, 'iEvent'> & { iEvent?: InteractEvent<T, P> }, ) { const { event, phase, preEnd, type } = signalArg const { rect } = this if (rect && phase === 'move') { // update the rect changes due to pointer move rectUtils.addEdges(this.edges, rect, this.coords.delta[this.interactable.options.deltaSource]) rect.width = rect.right - rect.left rect.height = rect.bottom - rect.top } const beforeResult = this._scopeFire(`interactions:before-action-${phase}` as any, signalArg) if (beforeResult === false) { return false } const iEvent = (signalArg.iEvent = this._createPreparedEvent(event, phase, preEnd, type)) this._scopeFire(`interactions:action-${phase}` as any, signalArg) if (phase === 'start') { this.prevEvent = iEvent } this._fireEvent(iEvent) this._scopeFire(`interactions:after-action-${phase}` as any, signalArg) return true } _now () { return Date.now() } } export default Interaction export { PointerInfo }
the_stack
import * as React from 'react'; import { Animated, TextStyle, StyleProp } from 'react-native'; declare type Props = React.ComponentPropsWithRef<typeof Animated.Text> & { style?: StyleProp<TextStyle>; /** * @optional */ theme: ReactNativePaper.Theme; }; /** * Text component which follows styles from the theme. * * @extends Text props https://facebook.github.io/react-native/docs/text.html#props */ declare function AnimatedText({ style, theme, ...rest }: Props): JSX.Element; declare const _default: (React.ComponentClass<Pick<{ allowFontScaling?: Animated.WithAnimatedValue<boolean | undefined> | undefined; ellipsizeMode?: Animated.WithAnimatedValue<"head" | "middle" | "tail" | "clip" | undefined> | undefined; lineBreakMode?: Animated.WithAnimatedValue<"head" | "middle" | "tail" | "clip" | undefined> | undefined; numberOfLines?: Animated.WithAnimatedValue<number | undefined> | undefined; onLayout?: Animated.WithAnimatedValue<((event: import("react-native").LayoutChangeEvent) => void) | undefined> | undefined; onPress?: Animated.WithAnimatedValue<((event: import("react-native").GestureResponderEvent) => void) | undefined> | undefined; onLongPress?: Animated.WithAnimatedValue<((event: import("react-native").GestureResponderEvent) => void) | undefined> | undefined; style?: Animated.WithAnimatedValue<StyleProp<TextStyle>> | undefined; testID?: Animated.WithAnimatedValue<string | undefined> | undefined; nativeID?: Animated.WithAnimatedValue<string | undefined> | undefined; maxFontSizeMultiplier?: Animated.WithAnimatedValue<number | null | undefined> | undefined; adjustsFontSizeToFit?: Animated.WithAnimatedValue<boolean | undefined> | undefined; minimumFontScale?: Animated.WithAnimatedValue<number | undefined> | undefined; suppressHighlighting?: Animated.WithAnimatedValue<boolean | undefined> | undefined; selectable?: Animated.WithAnimatedValue<boolean | undefined> | undefined; selectionColor?: Animated.WithAnimatedValue<string | undefined> | undefined; textBreakStrategy?: Animated.WithAnimatedValue<"simple" | "highQuality" | "balanced" | undefined> | undefined; accessible?: Animated.WithAnimatedValue<boolean | undefined> | undefined; accessibilityActions?: Animated.WithAnimatedValue<readonly Readonly<{ name: import("react-native").AccessibilityActionName; label?: string | undefined; }>[] | undefined> | undefined; accessibilityLabel?: Animated.WithAnimatedValue<string | undefined> | undefined; accessibilityRole?: Animated.WithAnimatedValue<"button" | "header" | "link" | "menu" | "menuitem" | "summary" | "image" | "switch" | "text" | "search" | "none" | "keyboardkey" | "adjustable" | "imagebutton" | "alert" | "checkbox" | "combobox" | "menubar" | "progressbar" | "radio" | "radiogroup" | "scrollbar" | "spinbutton" | "tab" | "tablist" | "timer" | "toolbar" | undefined> | undefined; accessibilityState?: Animated.WithAnimatedValue<import("react-native").AccessibilityState | undefined> | undefined; accessibilityHint?: Animated.WithAnimatedValue<string | undefined> | undefined; accessibilityValue?: Animated.WithAnimatedValue<import("react-native").AccessibilityValue | undefined> | undefined; onAccessibilityAction?: Animated.WithAnimatedValue<((event: import("react-native").AccessibilityActionEvent) => void) | undefined> | undefined; accessibilityComponentType?: Animated.WithAnimatedValue<"button" | "none" | "radiobutton_checked" | "radiobutton_unchecked" | undefined> | undefined; accessibilityLiveRegion?: Animated.WithAnimatedValue<"none" | "polite" | "assertive" | undefined> | undefined; importantForAccessibility?: Animated.WithAnimatedValue<"no-hide-descendants" | "auto" | "yes" | "no" | undefined> | undefined; accessibilityElementsHidden?: Animated.WithAnimatedValue<boolean | undefined> | undefined; accessibilityTraits?: Animated.WithAnimatedValue<"button" | "header" | "link" | "summary" | "image" | "text" | "search" | "none" | "adjustable" | "selected" | "plays" | "key" | "disabled" | "frequentUpdates" | "startsMedia" | "allowsDirectInteraction" | "pageTurn" | import("react-native").AccessibilityTrait[] | undefined> | undefined; accessibilityViewIsModal?: Animated.WithAnimatedValue<boolean | undefined> | undefined; onAccessibilityEscape?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; onAccessibilityTap?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; onMagicTap?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; accessibilityIgnoresInvertColors?: Animated.WithAnimatedValue<boolean | undefined> | undefined; ref?: Animated.WithAnimatedValue<((instance: import("react-native").Text | null) => void) | React.RefObject<import("react-native").Text> | null | undefined> | undefined; key?: Animated.WithAnimatedValue<string | number | undefined> | undefined; } & { ref?: ((instance: import("react-native").Text | { getNode(): import("react-native").Text; } | null) => void) | React.RefObject<import("react-native").Text | { getNode(): import("react-native").Text; }> | null | undefined; } & { style?: StyleProp<TextStyle>; /** * @optional */ theme: ReactNativePaper.Theme; }, "ref" | "style" | "allowFontScaling" | "ellipsizeMode" | "lineBreakMode" | "numberOfLines" | "onLayout" | "onPress" | "onLongPress" | "testID" | "nativeID" | "maxFontSizeMultiplier" | "adjustsFontSizeToFit" | "minimumFontScale" | "suppressHighlighting" | "selectable" | "selectionColor" | "textBreakStrategy" | "accessible" | "accessibilityActions" | "accessibilityLabel" | "accessibilityRole" | "accessibilityState" | "accessibilityHint" | "accessibilityValue" | "onAccessibilityAction" | "accessibilityComponentType" | "accessibilityLiveRegion" | "importantForAccessibility" | "accessibilityElementsHidden" | "accessibilityTraits" | "accessibilityViewIsModal" | "onAccessibilityEscape" | "onAccessibilityTap" | "onMagicTap" | "accessibilityIgnoresInvertColors" | "key"> & { theme?: import("@callstack/react-theme-provider").$DeepPartial<ReactNativePaper.Theme> | undefined; }, any> & import("@callstack/react-theme-provider/typings/hoist-non-react-statics").NonReactStatics<(React.ComponentClass<{ allowFontScaling?: Animated.WithAnimatedValue<boolean | undefined> | undefined; ellipsizeMode?: Animated.WithAnimatedValue<"head" | "middle" | "tail" | "clip" | undefined> | undefined; lineBreakMode?: Animated.WithAnimatedValue<"head" | "middle" | "tail" | "clip" | undefined> | undefined; numberOfLines?: Animated.WithAnimatedValue<number | undefined> | undefined; onLayout?: Animated.WithAnimatedValue<((event: import("react-native").LayoutChangeEvent) => void) | undefined> | undefined; onPress?: Animated.WithAnimatedValue<((event: import("react-native").GestureResponderEvent) => void) | undefined> | undefined; onLongPress?: Animated.WithAnimatedValue<((event: import("react-native").GestureResponderEvent) => void) | undefined> | undefined; style?: Animated.WithAnimatedValue<StyleProp<TextStyle>> | undefined; testID?: Animated.WithAnimatedValue<string | undefined> | undefined; nativeID?: Animated.WithAnimatedValue<string | undefined> | undefined; maxFontSizeMultiplier?: Animated.WithAnimatedValue<number | null | undefined> | undefined; adjustsFontSizeToFit?: Animated.WithAnimatedValue<boolean | undefined> | undefined; minimumFontScale?: Animated.WithAnimatedValue<number | undefined> | undefined; suppressHighlighting?: Animated.WithAnimatedValue<boolean | undefined> | undefined; selectable?: Animated.WithAnimatedValue<boolean | undefined> | undefined; selectionColor?: Animated.WithAnimatedValue<string | undefined> | undefined; textBreakStrategy?: Animated.WithAnimatedValue<"simple" | "highQuality" | "balanced" | undefined> | undefined; accessible?: Animated.WithAnimatedValue<boolean | undefined> | undefined; accessibilityActions?: Animated.WithAnimatedValue<readonly Readonly<{ name: import("react-native").AccessibilityActionName; label?: string | undefined; }>[] | undefined> | undefined; accessibilityLabel?: Animated.WithAnimatedValue<string | undefined> | undefined; accessibilityRole?: Animated.WithAnimatedValue<"button" | "header" | "link" | "menu" | "menuitem" | "summary" | "image" | "switch" | "text" | "search" | "none" | "keyboardkey" | "adjustable" | "imagebutton" | "alert" | "checkbox" | "combobox" | "menubar" | "progressbar" | "radio" | "radiogroup" | "scrollbar" | "spinbutton" | "tab" | "tablist" | "timer" | "toolbar" | undefined> | undefined; accessibilityState?: Animated.WithAnimatedValue<import("react-native").AccessibilityState | undefined> | undefined; accessibilityHint?: Animated.WithAnimatedValue<string | undefined> | undefined; accessibilityValue?: Animated.WithAnimatedValue<import("react-native").AccessibilityValue | undefined> | undefined; onAccessibilityAction?: Animated.WithAnimatedValue<((event: import("react-native").AccessibilityActionEvent) => void) | undefined> | undefined; accessibilityComponentType?: Animated.WithAnimatedValue<"button" | "none" | "radiobutton_checked" | "radiobutton_unchecked" | undefined> | undefined; accessibilityLiveRegion?: Animated.WithAnimatedValue<"none" | "polite" | "assertive" | undefined> | undefined; importantForAccessibility?: Animated.WithAnimatedValue<"no-hide-descendants" | "auto" | "yes" | "no" | undefined> | undefined; accessibilityElementsHidden?: Animated.WithAnimatedValue<boolean | undefined> | undefined; accessibilityTraits?: Animated.WithAnimatedValue<"button" | "header" | "link" | "summary" | "image" | "text" | "search" | "none" | "adjustable" | "selected" | "plays" | "key" | "disabled" | "frequentUpdates" | "startsMedia" | "allowsDirectInteraction" | "pageTurn" | import("react-native").AccessibilityTrait[] | undefined> | undefined; accessibilityViewIsModal?: Animated.WithAnimatedValue<boolean | undefined> | undefined; onAccessibilityEscape?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; onAccessibilityTap?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; onMagicTap?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; accessibilityIgnoresInvertColors?: Animated.WithAnimatedValue<boolean | undefined> | undefined; ref?: Animated.WithAnimatedValue<((instance: import("react-native").Text | null) => void) | React.RefObject<import("react-native").Text> | null | undefined> | undefined; key?: Animated.WithAnimatedValue<string | number | undefined> | undefined; } & { ref?: ((instance: import("react-native").Text | { getNode(): import("react-native").Text; } | null) => void) | React.RefObject<import("react-native").Text | { getNode(): import("react-native").Text; }> | null | undefined; } & { style?: StyleProp<TextStyle>; /** * @optional */ theme: ReactNativePaper.Theme; }, any> & typeof AnimatedText) | (React.FunctionComponent<{ allowFontScaling?: Animated.WithAnimatedValue<boolean | undefined> | undefined; ellipsizeMode?: Animated.WithAnimatedValue<"head" | "middle" | "tail" | "clip" | undefined> | undefined; lineBreakMode?: Animated.WithAnimatedValue<"head" | "middle" | "tail" | "clip" | undefined> | undefined; numberOfLines?: Animated.WithAnimatedValue<number | undefined> | undefined; onLayout?: Animated.WithAnimatedValue<((event: import("react-native").LayoutChangeEvent) => void) | undefined> | undefined; onPress?: Animated.WithAnimatedValue<((event: import("react-native").GestureResponderEvent) => void) | undefined> | undefined; onLongPress?: Animated.WithAnimatedValue<((event: import("react-native").GestureResponderEvent) => void) | undefined> | undefined; style?: Animated.WithAnimatedValue<StyleProp<TextStyle>> | undefined; testID?: Animated.WithAnimatedValue<string | undefined> | undefined; nativeID?: Animated.WithAnimatedValue<string | undefined> | undefined; maxFontSizeMultiplier?: Animated.WithAnimatedValue<number | null | undefined> | undefined; adjustsFontSizeToFit?: Animated.WithAnimatedValue<boolean | undefined> | undefined; minimumFontScale?: Animated.WithAnimatedValue<number | undefined> | undefined; suppressHighlighting?: Animated.WithAnimatedValue<boolean | undefined> | undefined; selectable?: Animated.WithAnimatedValue<boolean | undefined> | undefined; selectionColor?: Animated.WithAnimatedValue<string | undefined> | undefined; textBreakStrategy?: Animated.WithAnimatedValue<"simple" | "highQuality" | "balanced" | undefined> | undefined; accessible?: Animated.WithAnimatedValue<boolean | undefined> | undefined; accessibilityActions?: Animated.WithAnimatedValue<readonly Readonly<{ name: import("react-native").AccessibilityActionName; label?: string | undefined; }>[] | undefined> | undefined; accessibilityLabel?: Animated.WithAnimatedValue<string | undefined> | undefined; accessibilityRole?: Animated.WithAnimatedValue<"button" | "header" | "link" | "menu" | "menuitem" | "summary" | "image" | "switch" | "text" | "search" | "none" | "keyboardkey" | "adjustable" | "imagebutton" | "alert" | "checkbox" | "combobox" | "menubar" | "progressbar" | "radio" | "radiogroup" | "scrollbar" | "spinbutton" | "tab" | "tablist" | "timer" | "toolbar" | undefined> | undefined; accessibilityState?: Animated.WithAnimatedValue<import("react-native").AccessibilityState | undefined> | undefined; accessibilityHint?: Animated.WithAnimatedValue<string | undefined> | undefined; accessibilityValue?: Animated.WithAnimatedValue<import("react-native").AccessibilityValue | undefined> | undefined; onAccessibilityAction?: Animated.WithAnimatedValue<((event: import("react-native").AccessibilityActionEvent) => void) | undefined> | undefined; accessibilityComponentType?: Animated.WithAnimatedValue<"button" | "none" | "radiobutton_checked" | "radiobutton_unchecked" | undefined> | undefined; accessibilityLiveRegion?: Animated.WithAnimatedValue<"none" | "polite" | "assertive" | undefined> | undefined; importantForAccessibility?: Animated.WithAnimatedValue<"no-hide-descendants" | "auto" | "yes" | "no" | undefined> | undefined; accessibilityElementsHidden?: Animated.WithAnimatedValue<boolean | undefined> | undefined; accessibilityTraits?: Animated.WithAnimatedValue<"button" | "header" | "link" | "summary" | "image" | "text" | "search" | "none" | "adjustable" | "selected" | "plays" | "key" | "disabled" | "frequentUpdates" | "startsMedia" | "allowsDirectInteraction" | "pageTurn" | import("react-native").AccessibilityTrait[] | undefined> | undefined; accessibilityViewIsModal?: Animated.WithAnimatedValue<boolean | undefined> | undefined; onAccessibilityEscape?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; onAccessibilityTap?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; onMagicTap?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; accessibilityIgnoresInvertColors?: Animated.WithAnimatedValue<boolean | undefined> | undefined; ref?: Animated.WithAnimatedValue<((instance: import("react-native").Text | null) => void) | React.RefObject<import("react-native").Text> | null | undefined> | undefined; key?: Animated.WithAnimatedValue<string | number | undefined> | undefined; } & { ref?: ((instance: import("react-native").Text | { getNode(): import("react-native").Text; } | null) => void) | React.RefObject<import("react-native").Text | { getNode(): import("react-native").Text; }> | null | undefined; } & { style?: StyleProp<TextStyle>; /** * @optional */ theme: ReactNativePaper.Theme; }> & typeof AnimatedText), {}>) | (React.FunctionComponent<Pick<{ allowFontScaling?: Animated.WithAnimatedValue<boolean | undefined> | undefined; ellipsizeMode?: Animated.WithAnimatedValue<"head" | "middle" | "tail" | "clip" | undefined> | undefined; lineBreakMode?: Animated.WithAnimatedValue<"head" | "middle" | "tail" | "clip" | undefined> | undefined; numberOfLines?: Animated.WithAnimatedValue<number | undefined> | undefined; onLayout?: Animated.WithAnimatedValue<((event: import("react-native").LayoutChangeEvent) => void) | undefined> | undefined; onPress?: Animated.WithAnimatedValue<((event: import("react-native").GestureResponderEvent) => void) | undefined> | undefined; onLongPress?: Animated.WithAnimatedValue<((event: import("react-native").GestureResponderEvent) => void) | undefined> | undefined; style?: Animated.WithAnimatedValue<StyleProp<TextStyle>> | undefined; testID?: Animated.WithAnimatedValue<string | undefined> | undefined; nativeID?: Animated.WithAnimatedValue<string | undefined> | undefined; maxFontSizeMultiplier?: Animated.WithAnimatedValue<number | null | undefined> | undefined; adjustsFontSizeToFit?: Animated.WithAnimatedValue<boolean | undefined> | undefined; minimumFontScale?: Animated.WithAnimatedValue<number | undefined> | undefined; suppressHighlighting?: Animated.WithAnimatedValue<boolean | undefined> | undefined; selectable?: Animated.WithAnimatedValue<boolean | undefined> | undefined; selectionColor?: Animated.WithAnimatedValue<string | undefined> | undefined; textBreakStrategy?: Animated.WithAnimatedValue<"simple" | "highQuality" | "balanced" | undefined> | undefined; accessible?: Animated.WithAnimatedValue<boolean | undefined> | undefined; accessibilityActions?: Animated.WithAnimatedValue<readonly Readonly<{ name: import("react-native").AccessibilityActionName; label?: string | undefined; }>[] | undefined> | undefined; accessibilityLabel?: Animated.WithAnimatedValue<string | undefined> | undefined; accessibilityRole?: Animated.WithAnimatedValue<"button" | "header" | "link" | "menu" | "menuitem" | "summary" | "image" | "switch" | "text" | "search" | "none" | "keyboardkey" | "adjustable" | "imagebutton" | "alert" | "checkbox" | "combobox" | "menubar" | "progressbar" | "radio" | "radiogroup" | "scrollbar" | "spinbutton" | "tab" | "tablist" | "timer" | "toolbar" | undefined> | undefined; accessibilityState?: Animated.WithAnimatedValue<import("react-native").AccessibilityState | undefined> | undefined; accessibilityHint?: Animated.WithAnimatedValue<string | undefined> | undefined; accessibilityValue?: Animated.WithAnimatedValue<import("react-native").AccessibilityValue | undefined> | undefined; onAccessibilityAction?: Animated.WithAnimatedValue<((event: import("react-native").AccessibilityActionEvent) => void) | undefined> | undefined; accessibilityComponentType?: Animated.WithAnimatedValue<"button" | "none" | "radiobutton_checked" | "radiobutton_unchecked" | undefined> | undefined; accessibilityLiveRegion?: Animated.WithAnimatedValue<"none" | "polite" | "assertive" | undefined> | undefined; importantForAccessibility?: Animated.WithAnimatedValue<"no-hide-descendants" | "auto" | "yes" | "no" | undefined> | undefined; accessibilityElementsHidden?: Animated.WithAnimatedValue<boolean | undefined> | undefined; accessibilityTraits?: Animated.WithAnimatedValue<"button" | "header" | "link" | "summary" | "image" | "text" | "search" | "none" | "adjustable" | "selected" | "plays" | "key" | "disabled" | "frequentUpdates" | "startsMedia" | "allowsDirectInteraction" | "pageTurn" | import("react-native").AccessibilityTrait[] | undefined> | undefined; accessibilityViewIsModal?: Animated.WithAnimatedValue<boolean | undefined> | undefined; onAccessibilityEscape?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; onAccessibilityTap?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; onMagicTap?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; accessibilityIgnoresInvertColors?: Animated.WithAnimatedValue<boolean | undefined> | undefined; ref?: Animated.WithAnimatedValue<((instance: import("react-native").Text | null) => void) | React.RefObject<import("react-native").Text> | null | undefined> | undefined; key?: Animated.WithAnimatedValue<string | number | undefined> | undefined; } & { ref?: ((instance: import("react-native").Text | { getNode(): import("react-native").Text; } | null) => void) | React.RefObject<import("react-native").Text | { getNode(): import("react-native").Text; }> | null | undefined; } & { style?: StyleProp<TextStyle>; /** * @optional */ theme: ReactNativePaper.Theme; }, "ref" | "style" | "allowFontScaling" | "ellipsizeMode" | "lineBreakMode" | "numberOfLines" | "onLayout" | "onPress" | "onLongPress" | "testID" | "nativeID" | "maxFontSizeMultiplier" | "adjustsFontSizeToFit" | "minimumFontScale" | "suppressHighlighting" | "selectable" | "selectionColor" | "textBreakStrategy" | "accessible" | "accessibilityActions" | "accessibilityLabel" | "accessibilityRole" | "accessibilityState" | "accessibilityHint" | "accessibilityValue" | "onAccessibilityAction" | "accessibilityComponentType" | "accessibilityLiveRegion" | "importantForAccessibility" | "accessibilityElementsHidden" | "accessibilityTraits" | "accessibilityViewIsModal" | "onAccessibilityEscape" | "onAccessibilityTap" | "onMagicTap" | "accessibilityIgnoresInvertColors" | "key"> & { theme?: import("@callstack/react-theme-provider").$DeepPartial<ReactNativePaper.Theme> | undefined; }> & import("@callstack/react-theme-provider/typings/hoist-non-react-statics").NonReactStatics<(React.ComponentClass<{ allowFontScaling?: Animated.WithAnimatedValue<boolean | undefined> | undefined; ellipsizeMode?: Animated.WithAnimatedValue<"head" | "middle" | "tail" | "clip" | undefined> | undefined; lineBreakMode?: Animated.WithAnimatedValue<"head" | "middle" | "tail" | "clip" | undefined> | undefined; numberOfLines?: Animated.WithAnimatedValue<number | undefined> | undefined; onLayout?: Animated.WithAnimatedValue<((event: import("react-native").LayoutChangeEvent) => void) | undefined> | undefined; onPress?: Animated.WithAnimatedValue<((event: import("react-native").GestureResponderEvent) => void) | undefined> | undefined; onLongPress?: Animated.WithAnimatedValue<((event: import("react-native").GestureResponderEvent) => void) | undefined> | undefined; style?: Animated.WithAnimatedValue<StyleProp<TextStyle>> | undefined; testID?: Animated.WithAnimatedValue<string | undefined> | undefined; nativeID?: Animated.WithAnimatedValue<string | undefined> | undefined; maxFontSizeMultiplier?: Animated.WithAnimatedValue<number | null | undefined> | undefined; adjustsFontSizeToFit?: Animated.WithAnimatedValue<boolean | undefined> | undefined; minimumFontScale?: Animated.WithAnimatedValue<number | undefined> | undefined; suppressHighlighting?: Animated.WithAnimatedValue<boolean | undefined> | undefined; selectable?: Animated.WithAnimatedValue<boolean | undefined> | undefined; selectionColor?: Animated.WithAnimatedValue<string | undefined> | undefined; textBreakStrategy?: Animated.WithAnimatedValue<"simple" | "highQuality" | "balanced" | undefined> | undefined; accessible?: Animated.WithAnimatedValue<boolean | undefined> | undefined; accessibilityActions?: Animated.WithAnimatedValue<readonly Readonly<{ name: import("react-native").AccessibilityActionName; label?: string | undefined; }>[] | undefined> | undefined; accessibilityLabel?: Animated.WithAnimatedValue<string | undefined> | undefined; accessibilityRole?: Animated.WithAnimatedValue<"button" | "header" | "link" | "menu" | "menuitem" | "summary" | "image" | "switch" | "text" | "search" | "none" | "keyboardkey" | "adjustable" | "imagebutton" | "alert" | "checkbox" | "combobox" | "menubar" | "progressbar" | "radio" | "radiogroup" | "scrollbar" | "spinbutton" | "tab" | "tablist" | "timer" | "toolbar" | undefined> | undefined; accessibilityState?: Animated.WithAnimatedValue<import("react-native").AccessibilityState | undefined> | undefined; accessibilityHint?: Animated.WithAnimatedValue<string | undefined> | undefined; accessibilityValue?: Animated.WithAnimatedValue<import("react-native").AccessibilityValue | undefined> | undefined; onAccessibilityAction?: Animated.WithAnimatedValue<((event: import("react-native").AccessibilityActionEvent) => void) | undefined> | undefined; accessibilityComponentType?: Animated.WithAnimatedValue<"button" | "none" | "radiobutton_checked" | "radiobutton_unchecked" | undefined> | undefined; accessibilityLiveRegion?: Animated.WithAnimatedValue<"none" | "polite" | "assertive" | undefined> | undefined; importantForAccessibility?: Animated.WithAnimatedValue<"no-hide-descendants" | "auto" | "yes" | "no" | undefined> | undefined; accessibilityElementsHidden?: Animated.WithAnimatedValue<boolean | undefined> | undefined; accessibilityTraits?: Animated.WithAnimatedValue<"button" | "header" | "link" | "summary" | "image" | "text" | "search" | "none" | "adjustable" | "selected" | "plays" | "key" | "disabled" | "frequentUpdates" | "startsMedia" | "allowsDirectInteraction" | "pageTurn" | import("react-native").AccessibilityTrait[] | undefined> | undefined; accessibilityViewIsModal?: Animated.WithAnimatedValue<boolean | undefined> | undefined; onAccessibilityEscape?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; onAccessibilityTap?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; onMagicTap?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; accessibilityIgnoresInvertColors?: Animated.WithAnimatedValue<boolean | undefined> | undefined; ref?: Animated.WithAnimatedValue<((instance: import("react-native").Text | null) => void) | React.RefObject<import("react-native").Text> | null | undefined> | undefined; key?: Animated.WithAnimatedValue<string | number | undefined> | undefined; } & { ref?: ((instance: import("react-native").Text | { getNode(): import("react-native").Text; } | null) => void) | React.RefObject<import("react-native").Text | { getNode(): import("react-native").Text; }> | null | undefined; } & { style?: StyleProp<TextStyle>; /** * @optional */ theme: ReactNativePaper.Theme; }, any> & typeof AnimatedText) | (React.FunctionComponent<{ allowFontScaling?: Animated.WithAnimatedValue<boolean | undefined> | undefined; ellipsizeMode?: Animated.WithAnimatedValue<"head" | "middle" | "tail" | "clip" | undefined> | undefined; lineBreakMode?: Animated.WithAnimatedValue<"head" | "middle" | "tail" | "clip" | undefined> | undefined; numberOfLines?: Animated.WithAnimatedValue<number | undefined> | undefined; onLayout?: Animated.WithAnimatedValue<((event: import("react-native").LayoutChangeEvent) => void) | undefined> | undefined; onPress?: Animated.WithAnimatedValue<((event: import("react-native").GestureResponderEvent) => void) | undefined> | undefined; onLongPress?: Animated.WithAnimatedValue<((event: import("react-native").GestureResponderEvent) => void) | undefined> | undefined; style?: Animated.WithAnimatedValue<StyleProp<TextStyle>> | undefined; testID?: Animated.WithAnimatedValue<string | undefined> | undefined; nativeID?: Animated.WithAnimatedValue<string | undefined> | undefined; maxFontSizeMultiplier?: Animated.WithAnimatedValue<number | null | undefined> | undefined; adjustsFontSizeToFit?: Animated.WithAnimatedValue<boolean | undefined> | undefined; minimumFontScale?: Animated.WithAnimatedValue<number | undefined> | undefined; suppressHighlighting?: Animated.WithAnimatedValue<boolean | undefined> | undefined; selectable?: Animated.WithAnimatedValue<boolean | undefined> | undefined; selectionColor?: Animated.WithAnimatedValue<string | undefined> | undefined; textBreakStrategy?: Animated.WithAnimatedValue<"simple" | "highQuality" | "balanced" | undefined> | undefined; accessible?: Animated.WithAnimatedValue<boolean | undefined> | undefined; accessibilityActions?: Animated.WithAnimatedValue<readonly Readonly<{ name: import("react-native").AccessibilityActionName; label?: string | undefined; }>[] | undefined> | undefined; accessibilityLabel?: Animated.WithAnimatedValue<string | undefined> | undefined; accessibilityRole?: Animated.WithAnimatedValue<"button" | "header" | "link" | "menu" | "menuitem" | "summary" | "image" | "switch" | "text" | "search" | "none" | "keyboardkey" | "adjustable" | "imagebutton" | "alert" | "checkbox" | "combobox" | "menubar" | "progressbar" | "radio" | "radiogroup" | "scrollbar" | "spinbutton" | "tab" | "tablist" | "timer" | "toolbar" | undefined> | undefined; accessibilityState?: Animated.WithAnimatedValue<import("react-native").AccessibilityState | undefined> | undefined; accessibilityHint?: Animated.WithAnimatedValue<string | undefined> | undefined; accessibilityValue?: Animated.WithAnimatedValue<import("react-native").AccessibilityValue | undefined> | undefined; onAccessibilityAction?: Animated.WithAnimatedValue<((event: import("react-native").AccessibilityActionEvent) => void) | undefined> | undefined; accessibilityComponentType?: Animated.WithAnimatedValue<"button" | "none" | "radiobutton_checked" | "radiobutton_unchecked" | undefined> | undefined; accessibilityLiveRegion?: Animated.WithAnimatedValue<"none" | "polite" | "assertive" | undefined> | undefined; importantForAccessibility?: Animated.WithAnimatedValue<"no-hide-descendants" | "auto" | "yes" | "no" | undefined> | undefined; accessibilityElementsHidden?: Animated.WithAnimatedValue<boolean | undefined> | undefined; accessibilityTraits?: Animated.WithAnimatedValue<"button" | "header" | "link" | "summary" | "image" | "text" | "search" | "none" | "adjustable" | "selected" | "plays" | "key" | "disabled" | "frequentUpdates" | "startsMedia" | "allowsDirectInteraction" | "pageTurn" | import("react-native").AccessibilityTrait[] | undefined> | undefined; accessibilityViewIsModal?: Animated.WithAnimatedValue<boolean | undefined> | undefined; onAccessibilityEscape?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; onAccessibilityTap?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; onMagicTap?: Animated.WithAnimatedValue<(() => void) | undefined> | undefined; accessibilityIgnoresInvertColors?: Animated.WithAnimatedValue<boolean | undefined> | undefined; ref?: Animated.WithAnimatedValue<((instance: import("react-native").Text | null) => void) | React.RefObject<import("react-native").Text> | null | undefined> | undefined; key?: Animated.WithAnimatedValue<string | number | undefined> | undefined; } & { ref?: ((instance: import("react-native").Text | { getNode(): import("react-native").Text; } | null) => void) | React.RefObject<import("react-native").Text | { getNode(): import("react-native").Text; }> | null | undefined; } & { style?: StyleProp<TextStyle>; /** * @optional */ theme: ReactNativePaper.Theme; }> & typeof AnimatedText), {}>); export default _default;
the_stack
import { catchError, defer as observableDefer, map, Observable, of as observableOf, throwError as observableThrow, } from "rxjs"; import { ICustomMediaKeySystemAccess, requestMediaKeySystemAccess, shouldRenewMediaKeys, } from "../../compat"; import config from "../../config"; import { EncryptedMediaError } from "../../errors"; import log from "../../log"; import arrayIncludes from "../../utils/array_includes"; import flatMap from "../../utils/flat_map"; import MediaKeysInfosStore from "./media_keys_infos_store"; import { IKeySystemOption } from "./types"; type MediaKeysRequirement = "optional" | "required" | "not-allowed"; export interface IMediaKeySystemAccessInfos { mediaKeySystemAccess: MediaKeySystemAccess | ICustomMediaKeySystemAccess; options: IKeySystemOption; } export interface IReuseMediaKeySystemAccessEvent { type: "reuse-media-key-system-access"; value: IMediaKeySystemAccessInfos; } export interface ICreateMediaKeySystemAccessEvent { type: "create-media-key-system-access"; value: IMediaKeySystemAccessInfos; } export type IFoundMediaKeySystemAccessEvent = IReuseMediaKeySystemAccessEvent | ICreateMediaKeySystemAccessEvent; interface IMediaCapability { contentType?: string; robustness?: string; } interface IKeySystemType { keyName : string | undefined; keyType : string; keySystemOptions : IKeySystemOption; } const { EME_DEFAULT_WIDEVINE_ROBUSTNESSES, EME_KEY_SYSTEMS } = config; /** * @param {Array.<Object>} keySystems * @param {MediaKeySystemAccess} currentKeySystemAccess * @param {Object} currentKeySystemOptions * @returns {null|Object} */ function checkCachedMediaKeySystemAccess( keySystems: IKeySystemOption[], currentKeySystemAccess: MediaKeySystemAccess|ICustomMediaKeySystemAccess, currentKeySystemOptions: IKeySystemOption ) : null | { keySystemOptions: IKeySystemOption; keySystemAccess: MediaKeySystemAccess|ICustomMediaKeySystemAccess; } { const mksConfiguration = currentKeySystemAccess.getConfiguration(); if (shouldRenewMediaKeys() || mksConfiguration == null) { return null; } const firstCompatibleOption = keySystems.filter((ks) => { // TODO Do it with MediaKeySystemAccess.prototype.keySystem instead if (ks.type !== currentKeySystemOptions.type) { return false; } if ((ks.persistentLicense === true || ks.persistentStateRequired === true) && mksConfiguration.persistentState !== "required") { return false; } if (ks.distinctiveIdentifierRequired === true && mksConfiguration.distinctiveIdentifier !== "required") { return false; } return true; })[0]; if (firstCompatibleOption != null) { return { keySystemOptions: firstCompatibleOption, keySystemAccess: currentKeySystemAccess }; } return null; } /** * Find key system canonical name from key system type. * @param {string} ksType - Obtained via inversion * @returns {string|undefined} - Either the canonical name, or undefined. */ function findKeySystemCanonicalName(ksType: string) : string | undefined { for (const ksName of Object.keys(EME_KEY_SYSTEMS)) { if (arrayIncludes(EME_KEY_SYSTEMS[ksName] as string[], ksType)) { return ksName; } } return undefined; } /** * Build configuration for the requestMediaKeySystemAccess EME API, based * on the current keySystem object. * @param {string} [ksName] - Generic name for the key system. e.g. "clearkey", * "widevine", "playready". Can be used to make exceptions depending on it. * @param {Object} keySystem * @returns {Array.<Object>} - Configuration to give to the * requestMediaKeySystemAccess API. */ function buildKeySystemConfigurations( ksName : string | undefined, keySystem : IKeySystemOption ) : MediaKeySystemConfiguration[] { const sessionTypes = ["temporary"]; let persistentState: MediaKeysRequirement = "optional"; let distinctiveIdentifier: MediaKeysRequirement = "optional"; if (keySystem.persistentLicense === true) { persistentState = "required"; sessionTypes.push("persistent-license"); } if (keySystem.persistentStateRequired === true) { persistentState = "required"; } if (keySystem.distinctiveIdentifierRequired === true) { distinctiveIdentifier = "required"; } // Set robustness, in order of consideration: // 1. the user specified its own robustnesses // 2. a "widevine" key system is used, in that case set the default widevine // robustnesses as defined in the config // 3. set an undefined robustness const videoRobustnesses = keySystem.videoRobustnesses != null ? keySystem.videoRobustnesses : (ksName === "widevine" ? EME_DEFAULT_WIDEVINE_ROBUSTNESSES : []); const audioRobustnesses = keySystem.audioRobustnesses != null ? keySystem.audioRobustnesses : (ksName === "widevine" ? EME_DEFAULT_WIDEVINE_ROBUSTNESSES : []); if (videoRobustnesses.length === 0) { videoRobustnesses.push(undefined); } if (audioRobustnesses.length === 0) { audioRobustnesses.push(undefined); } // From the W3 EME spec, we have to provide videoCapabilities and // audioCapabilities. // These capabilities must specify a codec (even though you can use a // completely different codec afterward). // It is also strongly recommended to specify the required security // robustness. As we do not want to forbide any security level, we specify // every existing security level from highest to lowest so that the best // security level is selected. // More details here: // https://storage.googleapis.com/wvdocs/Chrome_EME_Changes_and_Best_Practices.pdf // https://www.w3.org/TR/encrypted-media/#get-supported-configuration-and-consent const videoCapabilities: IMediaCapability[] = flatMap(videoRobustnesses, robustness => [{ contentType: "video/mp4;codecs=\"avc1.4d401e\"", robustness }, { contentType: "video/mp4;codecs=\"avc1.42e01e\"", robustness }, { contentType: "video/webm;codecs=\"vp8\"", robustness } ]); const audioCapabilities: IMediaCapability[] = flatMap(audioRobustnesses, robustness => [{ contentType: "audio/mp4;codecs=\"mp4a.40.2\"", robustness }, { contentType: "audio/webm;codecs=opus", robustness } ]); // TODO Re-test with a set contentType but an undefined robustness on the // STBs on which this problem was found. // // add another with no {audio,video}Capabilities for some legacy browsers. // As of today's spec, this should return NotSupported but the first // candidate configuration should be good, so we should have no downside // doing that. // initDataTypes: ["cenc"], // videoCapabilities: undefined, // audioCapabilities: undefined, // distinctiveIdentifier, // persistentState, // sessionTypes, return [{ initDataTypes: ["cenc"], videoCapabilities, audioCapabilities, distinctiveIdentifier, persistentState, sessionTypes }]; } /** * Try to find a compatible key system from the keySystems array given. * * Returns an Observable which, when subscribed to, will request a * MediaKeySystemAccess based on the various keySystems provided. This * Observable will: * - emit the MediaKeySystemAccess and the keySystems as an object, when * found. The object is under this form: * { * keySystemAccess {MediaKeySystemAccess} * keySystem {Object} * } * - complete immediately after emitting. * - throw if no compatible key system has been found. * * @param {HTMLMediaElement} mediaElement * @param {Array.<Object>} keySystems - The keySystems you want to test. * @returns {Observable} */ export default function getMediaKeySystemAccess( mediaElement : HTMLMediaElement, keySystemsConfigs: IKeySystemOption[] ) : Observable<IFoundMediaKeySystemAccessEvent> { return observableDefer<Observable<IFoundMediaKeySystemAccessEvent>>(() => { log.info("EME: Searching for compatible MediaKeySystemAccess"); const currentState = MediaKeysInfosStore.getState(mediaElement); if (currentState != null) { // Fast way to find a compatible keySystem if the currently loaded // one as exactly the same compatibility options. const cachedKeySystemAccess = checkCachedMediaKeySystemAccess(keySystemsConfigs, currentState.mediaKeySystemAccess, currentState.keySystemOptions); if (cachedKeySystemAccess !== null) { log.info("EME: Found cached compatible keySystem", cachedKeySystemAccess); return observableOf({ type: "reuse-media-key-system-access" as const, value: { mediaKeySystemAccess: cachedKeySystemAccess.keySystemAccess, options: cachedKeySystemAccess.keySystemOptions }, }); } } /** * Array of set keySystems for this content. * Each item of this array is an object containing the following keys: * - keyName {string}: keySystem canonical name (e.g. "widevine") * - keyType {string}: keySystem type (e.g. "com.widevine.alpha") * - keySystem {Object}: the original keySystem object * @type {Array.<Object>} */ const keySystemsType: IKeySystemType[] = keySystemsConfigs.reduce( (arr: IKeySystemType[], keySystemOptions) => { const managedRDNs = EME_KEY_SYSTEMS[keySystemOptions.type]; let ksType; if (managedRDNs != null) { ksType = managedRDNs.map((keyType) => { const keyName = keySystemOptions.type; return { keyName, keyType, keySystemOptions }; }); } else { const keyName = findKeySystemCanonicalName(keySystemOptions.type); const keyType = keySystemOptions.type; ksType = [{ keyName, keyType, keySystemOptions }]; } return arr.concat(ksType); } , []); return recursivelyTestKeySystems(0); /** * Test all key system configuration stored in `keySystemsType` one by one * recursively. * Returns an Observable which emit the MediaKeySystemAccess if one was * found compatible with one of the configurations or just throws if none * were found to be compatible. * @param {Number} index - The index in `keySystemsType` to start from. * Should be set to `0` when calling directly. * @returns {Observable} */ function recursivelyTestKeySystems( index : number ) : Observable<IFoundMediaKeySystemAccessEvent> { // if we iterated over the whole keySystemsType Array, quit on error if (index >= keySystemsType.length) { const error = new EncryptedMediaError("INCOMPATIBLE_KEYSYSTEMS", "No key system compatible with your " + "wanted configuration has been found " + "in the current browser."); return observableThrow(() => error); } if (requestMediaKeySystemAccess == null) { const error = Error("requestMediaKeySystemAccess is not " + "implemented in your browser."); return observableThrow(() => error); } const { keyName, keyType, keySystemOptions } = keySystemsType[index]; const keySystemConfigurations = buildKeySystemConfigurations(keyName, keySystemOptions); log.debug(`EME: Request keysystem access ${keyType},` + `${index + 1} of ${keySystemsType.length}`, keySystemConfigurations); return requestMediaKeySystemAccess(keyType, keySystemConfigurations).pipe( map((keySystemAccess) => { log.info("EME: Found compatible keysystem", keyType, keySystemConfigurations); return { type: "create-media-key-system-access" as const, value: { options: keySystemOptions, mediaKeySystemAccess: keySystemAccess } }; }), catchError(() => { log.debug("EME: Rejected access to keysystem", keyType, keySystemConfigurations); return recursivelyTestKeySystems(index + 1); })); } }); }
the_stack
import { getPoint, ChartLocation, appendClipElement, pathAnimation } from '../../common/utils/helper'; import { PathOption, SvgRenderer } from '@syncfusion/ej2-svg-base'; import { Chart } from '../chart'; import { Series, Points } from './chart-series'; import { Axis } from '../../chart/axis/axis'; import { LineBase } from './line-base'; import { RectOption, getElement } from '../../common/utils/helper'; import { ChartSegment } from './chart-series'; import { ChartSegmentModel } from './chart-series-model'; import { DataUtil } from '@syncfusion/ej2-data'; import { DateFormatOptions } from '@syncfusion/ej2-base'; import {PathAttributes } from '@syncfusion/ej2-svg-base'; /** * Base class for multi colored series */ export class MultiColoredSeries extends LineBase { /** * To Generate the area path direction * * @param {number} xValue xValue * @param {number} yValue yValue * @param {Series} series series * @param {boolean} isInverted isInverted * @param {Function} getPointLocation getPointLocation * @param {ChartLocation} startPoint startPoint * @param {string} startPath startPath */ public getAreaPathDirection( xValue: number, yValue: number, series: Series, isInverted: boolean, getPointLocation: Function, startPoint: ChartLocation, startPath: string ): string { let direction: string = ''; let firstPoint: ChartLocation; if (startPoint === null) { firstPoint = getPointLocation(xValue, yValue, series.xAxis, series.yAxis, isInverted, series); direction += (startPath + ' ' + (firstPoint.x) + ' ' + (firstPoint.y) + ' '); } return direction; } /** * To Generate the empty point direction * * @param {ChartLocation} firstPoint firstPoint * @param {ChartLocation} secondPoint secondPoint * @param {Series} series series * @param {boolean} isInverted isInverted * @param {Function} getPointLocation getPointLocation */ public getAreaEmptyDirection( firstPoint: ChartLocation, secondPoint: ChartLocation, series: Series, isInverted: boolean, getPointLocation: Function ): string { let direction: string = ''; direction += this.getAreaPathDirection( firstPoint.x, firstPoint.y, series, isInverted, getPointLocation, null, 'L' ); direction += this.getAreaPathDirection( secondPoint.x, secondPoint.y, series, isInverted, getPointLocation, null, 'L' ); return direction; } /** * To set point color */ public setPointColor(currentPoint: Points, previous: Points, series: Series, isXSegment : boolean, segments: ChartSegmentModel[]): boolean { if (series.pointColorMapping === '') { let segment : ChartSegmentModel; let value : number; for (let i : number = 0; i < segments.length ; i++) { segment = segments[i]; value = isXSegment ? currentPoint.xValue : currentPoint.yValue; if (value <= this.getAxisValue(segment.value, isXSegment ? series.xAxis : series.yAxis, series.chart) || !segment.value) { currentPoint.interior = segment.color; break; } } if (currentPoint.interior == null) { currentPoint.interior = series.interior; } return false; } else { if (previous) { return series.setPointColor(currentPoint, series.interior) !== series.setPointColor(previous, series.interior); } else { return false; } } } public sortSegments(series: Series, chartSegments: ChartSegmentModel[]) : ChartSegmentModel[] { const axis: Axis = series.segmentAxis === 'X' ? series.xAxis : series.yAxis; const segments: ChartSegmentModel[] = [].concat(chartSegments); return segments.sort((a : ChartSegmentModel, b : ChartSegmentModel) => { return this.getAxisValue(a.value, axis, series.chart) - this.getAxisValue(b.value, axis, series.chart); }); } /** * Segment calculation performed here * * @param {Series} series series * @param {PathOption[]} options options * @param {ChartSegmentModel[]} segments chartSegments */ public applySegmentAxis(series: Series, options: PathOption[], segments: ChartSegmentModel[]): void { if (series.pointColorMapping !== '') { options.map((option: PathOption) => { this.appendLinePath(option, series, ''); }); return null; } const isXSegment: boolean = series.segmentAxis === 'X'; const axis: Axis = isXSegment ? series.xAxis : series.yAxis; const chart: Chart = series.chart; let segment: ChartSegment; this.includeSegment(segments, axis, series, segments.length); const length: number = segments.length; let value : number; let clipPath : string; let attributeOptions: PathAttributes; for (let index: number = 0; index < length; index++) { segment = segments[index] as ChartSegment; value = this.getAxisValue(segment.value, axis, series.chart); clipPath = this.createClipRect(index ? this.getAxisValue(segments[index - 1].value, axis, series.chart) : axis.visibleRange.min, value, series, index, isXSegment); if (clipPath) { options.map((option: PathOption) => { attributeOptions = { 'clip-path': clipPath, 'stroke-dasharray': segment.dashArray, 'opacity': option.opacity, 'stroke': series.type.indexOf('Line') > -1 ? segment.color || series.interior : series.border.color, 'stroke-width': option['stroke-width'], 'fill': series.type.indexOf('Line') > -1 ? 'none' : segment.color || series.interior, 'id': option.id + '_Segment_' + index, 'd': option.d }; pathAnimation(getElement(attributeOptions.id), attributeOptions.d, chart.redraw); series.seriesElement.appendChild( chart.renderer.drawPath(attributeOptions) ); }); } } } private includeSegment(segments : ChartSegmentModel[], axis : Axis, series : Series, length : number) : void { if (length <= 0) { segments.push({ value: axis.visibleRange.max, color: series.interior }); return null; } if (this.getAxisValue(segments[length - 1].value, axis, series.chart) < axis.visibleRange.max) { segments.push({value : axis.visibleRange.max, color : series.interior}); } } /** * To create clip rect for segment axis * * @param {number} startValue startValue * @param {number} endValue endValue * @param {Series} series series * @param {number} index index * @param {boolean} isX isX */ public createClipRect( startValue: number, endValue: number, series: Series, index: number, isX: boolean ): string { const isRequired: boolean = series.chart.requireInvertedAxis; let startPointLocation: ChartLocation = getPoint( isX ? startValue : series.xAxis.visibleRange.min, isX ? series.yAxis.visibleRange.max : endValue, series.xAxis, series.yAxis, isRequired ); let endPointLocation: ChartLocation = getPoint( isX ? endValue : series.xAxis.visibleRange.max, isX ? series.yAxis.visibleRange.min : startValue, series.xAxis, series.yAxis, isRequired ); endPointLocation = isRequired ? [startPointLocation, startPointLocation = endPointLocation][0] : endPointLocation; let options: RectOption; if ((endPointLocation.x - startPointLocation.x > 0) && (endPointLocation.y - startPointLocation.y > 0)) { options = new RectOption( series.chart.element.id + '_ChartSegment' + series.index + 'ClipRect_' + index, 'transparent', { width: 1, color: 'Gray' }, 1, { x: startPointLocation.x, y: startPointLocation.y, width: endPointLocation.x - startPointLocation.x, height: endPointLocation.y - startPointLocation.y } ); series.seriesElement.appendChild( appendClipElement(series.chart.redraw, options, series.chart.renderer as SvgRenderer) ); return 'url(#' + series.chart.element.id + '_ChartSegment' + series.index + 'ClipRect_' + index + ')'; } return null; } /** * To get exact value from segment value * * @param {Object} segmentValue segmentValue * @param {Axis} axis axis * @param {Chart} chart chart */ public getAxisValue(segmentValue: Object, axis: Axis, chart: Chart): number { if (segmentValue === null) { segmentValue = axis.visibleRange.max; } if (axis.valueType === 'DateTime') { const option: DateFormatOptions = { skeleton: 'full', type: 'dateTime' }; return Date.parse(chart.intl.getDateParser(option)( chart.intl.getDateFormat(option)(new Date( DataUtil.parse.parseJson({ val: segmentValue }).val )) )); } else if (axis.valueType.indexOf('Category') > -1) { const xValue: string = axis.valueType === 'DateTimeCategory' ? ((segmentValue as Date).getTime()).toString() : <string>segmentValue; return (axis.labels.indexOf(xValue) < 0) ? +segmentValue : axis.labels.indexOf(xValue); } else { return +segmentValue; } } }
the_stack
import './passwords_list_handler.js'; import 'chrome://resources/cr_elements/shared_style_css.m.js'; import '../settings_shared_css.js'; import './avatar_icon.js'; import './passwords_shared_css.js'; import './password_list_item.js'; import './password_move_multiple_passwords_to_account_dialog.js'; import 'chrome://resources/cr_elements/cr_toast/cr_toast.js'; import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js'; import 'chrome://resources/polymer/v3_0/iron-list/iron-list.js'; import {CrToastElement} from 'chrome://resources/cr_elements/cr_toast/cr_toast.js'; import {PluralStringProxyImpl} from 'chrome://resources/js/plural_string_proxy.js'; import {getDeepActiveElement} from 'chrome://resources/js/util.m.js'; import {WebUIListenerMixin, WebUIListenerMixinInterface} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {GlobalScrollTargetMixin} from '../global_scroll_target_mixin.js'; import {loadTimeData} from '../i18n_setup.js'; import {OpenWindowProxyImpl} from '../open_window_proxy.js'; import {StoredAccount, SyncBrowserProxyImpl, SyncStatus} from '../people_page/sync_browser_proxy.js'; import {routes} from '../route.js'; import {Route, RouteObserverMixin, RouteObserverMixinInterface, Router} from '../router.js'; import {MergePasswordsStoreCopiesMixin, MergePasswordsStoreCopiesMixinInterface} from './merge_passwords_store_copies_mixin.js'; import {MultiStorePasswordUiEntry} from './multi_store_password_ui_entry.js'; import {AccountStorageOptInStateChangedListener, PasswordManagerImpl} from './password_manager_proxy.js'; import {PasswordsListHandlerElement} from './passwords_list_handler.js'; /** * Checks if an HTML element is an editable. An editable element is either a * text input or a text area. */ function isEditable(element: Element): boolean { const nodeName = element.nodeName.toLowerCase(); return element.nodeType === Node.ELEMENT_NODE && (nodeName === 'textarea' || (nodeName === 'input' && /^(?:text|search|email|number|tel|url|password)$/i.test( (element as HTMLInputElement).type))); } interface PasswordsDeviceSectionElement { $: { toast: CrToastElement, passwordsListHandler: PasswordsListHandlerElement, }; } // TODO(crbug.com/1234307): Remove when RouteObserverMixin is converted to // TypeScript. type Constructor<T> = new (...args: any[]) => T; const PasswordsDeviceSectionElementBase = MergePasswordsStoreCopiesMixin(GlobalScrollTargetMixin(WebUIListenerMixin( RouteObserverMixin(PolymerElement) as unknown as Constructor<PolymerElement>))) as { new (): PolymerElement & WebUIListenerMixinInterface & MergePasswordsStoreCopiesMixinInterface & RouteObserverMixinInterface }; class PasswordsDeviceSectionElement extends PasswordsDeviceSectionElementBase { static get is() { return 'passwords-device-section'; } static get template() { return html`{__html_template__}`; } static get properties() { return { subpageRoute: { type: Object, value: routes.DEVICE_PASSWORDS, }, /** Search filter on the saved passwords. */ filter: { type: String, value: '', }, /** * Passwords displayed in the device-only subsection. */ deviceOnlyPasswords_: { type: Array, value: () => [], computed: 'computeDeviceOnlyPasswords_(savedPasswords, savedPasswords.splices)', }, /** * Passwords displayed in the 'device and account' subsection. */ deviceAndAccountPasswords_: { type: Array, value: () => [], computed: 'computeDeviceAndAccountPasswords_(savedPasswords, ' + 'savedPasswords.splices)', }, /** * Passwords displayed in both the device-only and 'device and account' * subsections. */ allDevicePasswords_: { type: Array, value: () => [], computed: 'computeAllDevicePasswords_(savedPasswords.splices)', observer: 'onAllDevicePasswordsChanged_', }, /** * Whether the entry point leading to the dialog to move multiple * passwords to the Google Account should be shown. It's shown only where * there is at least one password store on device. */ shouldShowMoveMultiplePasswordsBanner_: { type: Boolean, value: false, computed: 'computeShouldShowMoveMultiplePasswordsBanner_(' + 'savedPasswords, savedPasswords.splices)', }, lastFocused_: Object, listBlurred_: Boolean, accountEmail_: String, isUserAllowedToAccessPage_: { type: Boolean, computed: 'computeIsUserAllowedToAccessPage_(signedIn_, syncDisabled_,' + 'optedInForAccountStorage_)', }, /** * Whether the user is signed in, one of the requirements to view this * page. */ signedIn_: { type: Boolean, value: null, }, /** * Whether Sync is disabled, one of the requirements to view this page. */ syncDisabled_: { type: Boolean, value: null, }, /** * Whether the user has opted in to the account-scoped password storage, * one of the requirements to view this page. */ optedInForAccountStorage_: { type: Boolean, value: null, }, showMoveMultiplePasswordsDialog_: Boolean, currentRoute_: { type: Object, value: null, }, devicePasswordsLabel_: { type: String, value: '', }, }; } static get observers() { return [ 'maybeRedirectToPasswordsPage_(isUserAllowedToAccessPage_, currentRoute_)' ]; } subpageRoute: Route; filter: string; private deviceOnlyPasswords_: Array<MultiStorePasswordUiEntry>; private deviceAndAccountPasswords_: Array<MultiStorePasswordUiEntry>; private allDevicePasswords_: Array<MultiStorePasswordUiEntry>; private shouldShowMoveMultiplePasswordsBanner_: boolean; private lastFocused_: MultiStorePasswordUiEntry; private listBlurred_: boolean; private accountEmail_: string; private isUserAllowedToAccessPage_: boolean; private signedIn_: boolean|null; private syncDisabled_: boolean|null; private optedInForAccountStorage_: boolean|null; private showMoveMultiplePasswordsDialog_: boolean; private currentRoute_: Route|null; private devicePasswordsLabel_: string; private accountStorageOptInStateListener_: AccountStorageOptInStateChangedListener|null = null; connectedCallback() { super.connectedCallback(); this.addListenersForAccountStorageRequirements_(); this.currentRoute_ = Router.getInstance().currentRoute; const extractFirstStoredAccountEmail = (accounts: Array<StoredAccount>) => { this.accountEmail_ = accounts.length > 0 ? accounts[0].email : ''; }; SyncBrowserProxyImpl.getInstance().getStoredAccounts().then( extractFirstStoredAccountEmail); this.addWebUIListener( 'stored-accounts-updated', extractFirstStoredAccountEmail); } ready() { super.ready(); document.addEventListener('keydown', keyboardEvent => { // <if expr="is_macosx"> if (keyboardEvent.metaKey && keyboardEvent.key === 'z') { this.onUndoKeyBinding_(keyboardEvent); } // </if> // <if expr="not is_macosx"> if (keyboardEvent.ctrlKey && keyboardEvent.key === 'z') { this.onUndoKeyBinding_(keyboardEvent); } // </if> }); } disconnectedCallback() { super.disconnectedCallback(); PasswordManagerImpl.getInstance().removeAccountStorageOptInStateListener( this.accountStorageOptInStateListener_!); this.accountStorageOptInStateListener_ = null; } private computeAllDevicePasswords_(): Array<MultiStorePasswordUiEntry> { return this.savedPasswords.filter(p => p.isPresentOnDevice()); } private computeDeviceOnlyPasswords_(): Array<MultiStorePasswordUiEntry> { return this.savedPasswords.filter( p => p.isPresentOnDevice() && !p.isPresentInAccount()); } private computeDeviceAndAccountPasswords_(): Array<MultiStorePasswordUiEntry> { return this.savedPasswords.filter( p => p.isPresentOnDevice() && p.isPresentInAccount()); } private computeIsUserAllowedToAccessPage_(): boolean { // Only deny access when one of the requirements has already been computed // and is not satisfied. return (this.signedIn_ === null || !!this.signedIn_) && (this.syncDisabled_ === null || !!this.syncDisabled_) && (this.optedInForAccountStorage_ === null || !!this.optedInForAccountStorage_); } private computeShouldShowMoveMultiplePasswordsBanner_(): boolean { if (!loadTimeData.getBoolean('enableMovingMultiplePasswordsToAccount')) { return false; } if (this.allDevicePasswords_.length === 0) { return false; } // Check if all username, and urls are unique. The existence of two entries // with the same url and username indicate that they must have conflicting // passwords, otherwise, they would have been deduped in // MergePasswordsStoreCopiesBehavior. This however may mistakenly exclude // users who have conflicting duplicates within the same store, which is an // acceptable compromise. return this.savedPasswords.every( p1 => (this.savedPasswords .filter( p2 => p1.username === p2.username && p1.urls.origin === p2.urls.origin) .length === 1)); } private async onAllDevicePasswordsChanged_() { this.devicePasswordsLabel_ = await PluralStringProxyImpl.getInstance().getPluralString( 'movePasswordsToAccount', this.allDevicePasswords_.length); } /** * From RouteObserverMixin. */ currentRouteChanged(route: Route) { super.currentRouteChanged(route); this.currentRoute_ = route || null; } private addListenersForAccountStorageRequirements_() { const setSyncDisabled = (syncStatus: SyncStatus) => { this.syncDisabled_ = !syncStatus.signedIn; }; SyncBrowserProxyImpl.getInstance().getSyncStatus().then(setSyncDisabled); this.addWebUIListener('sync-status-changed', setSyncDisabled); const setSignedIn = (storedAccounts: Array<StoredAccount>) => { this.signedIn_ = storedAccounts.length > 0; }; SyncBrowserProxyImpl.getInstance().getStoredAccounts().then(setSignedIn); this.addWebUIListener('stored-accounts-updated', setSignedIn); const setOptedIn = (optedInForAccountStorage: boolean) => { this.optedInForAccountStorage_ = optedInForAccountStorage; }; PasswordManagerImpl.getInstance().isOptedInForAccountStorage().then( setOptedIn); PasswordManagerImpl.getInstance().addAccountStorageOptInStateListener( setOptedIn); this.accountStorageOptInStateListener_ = setOptedIn; } private isNonEmpty_(passwords: Array<MultiStorePasswordUiEntry>): boolean { return passwords.length > 0; } private getFilteredPasswords_( passwords: Array<MultiStorePasswordUiEntry>, filter: string): Array<MultiStorePasswordUiEntry> { if (!filter) { return passwords.slice(); } return passwords.filter( p => [p.urls.shown, p.username].some( term => term.toLowerCase().includes(filter.toLowerCase()))); } /** * Handle the undo shortcut. */ // TODO(crbug.com/1102294): Consider grouping the ctrl-z related code into // a dedicated behavior. private onUndoKeyBinding_(event: Event) { const activeElement = getDeepActiveElement(); if (!activeElement || !isEditable(activeElement)) { PasswordManagerImpl.getInstance().undoRemoveSavedPasswordOrException(); this.$.passwordsListHandler.onSavedPasswordOrExceptionRemoved(); // Preventing the default is necessary to not conflict with a possible // search action. event.preventDefault(); } } private onManageAccountPasswordsClicked_() { OpenWindowProxyImpl.getInstance().openURL( loadTimeData.getString('googlePasswordManagerUrl')); } private onMoveMultiplePasswordsTap_() { this.showMoveMultiplePasswordsDialog_ = true; } private onMoveMultiplePasswordsDialogClose_() { if (this.shadowRoot! .querySelector( 'password-move-multiple-passwords-to-account-dialog')! .wasConfirmed()) { this.$.toast.show(); } this.showMoveMultiplePasswordsDialog_ = false; } private maybeRedirectToPasswordsPage_() { // The component can be attached even if the route is no longer // DEVICE_PASSWORDS, so check to avoid navigating when the user is viewing // other non-related pages. if (!this.isUserAllowedToAccessPage_ && this.currentRoute_ === routes.DEVICE_PASSWORDS) { Router.getInstance().navigateTo(routes.PASSWORDS); } } } customElements.define( PasswordsDeviceSectionElement.is, PasswordsDeviceSectionElement);
the_stack
import { DOWN_ARROW, END, ENTER, ESCAPE, HOME, SPACE, UP_ARROW } from "@angular/cdk/keycodes"; import { ConnectionPositionPair, Overlay, OverlayConfig, OverlayRef } from "@angular/cdk/overlay"; import { ComponentPortal } from "@angular/cdk/portal"; import { AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ComponentRef, ContentChild, ContentChildren, ElementRef, EventEmitter, HostBinding, HostListener, Injector, Input, OnDestroy, Optional, Output, QueryList, Self, SimpleChange, TemplateRef, ViewChild, } from "@angular/core"; import { ControlValueAccessor, NgControl } from "@angular/forms"; import { FlagInput, ListKeyNavigator, coerceBooleanProperty } from "@batch-flask/core"; import { FormFieldControl } from "@batch-flask/ui/form/form-field"; import { SelectDropdownComponent } from "@batch-flask/ui/select/select-dropdown/select-dropdown.component"; import { Subject, Subscription } from "rxjs"; import { OptionTemplateDirective } from "./option-template.directive"; import { BL_OPTION_PARENT, OptionParent, SelectOptionComponent } from "./option/option.component"; import "./select.scss"; /** Custom injector type specifically for instantiating components with a dialog. */ export class SelectInjector implements Injector { constructor(private select: SelectComponent, private parentInjector: Injector) { } public get(token: any, notFoundValue?: any): any { if (token === SelectComponent) { return this.select; } return this.parentInjector.get(token, notFoundValue); } } let nextUniqueId = 0; @Component({ selector: "bl-select", templateUrl: "select.html", changeDetection: ChangeDetectionStrategy.OnPush, providers: [ { provide: FormFieldControl, useExisting: SelectComponent }, { provide: BL_OPTION_PARENT, useExisting: SelectComponent }, ], }) export class SelectComponent<TValue = any> implements FormFieldControl<any>, OptionParent, ControlValueAccessor, AfterContentInit, OnDestroy { @Input() public placeholder = ""; /** * If the select accepts multiple values */ @Input() @FlagInput() public multiple = false; /** * If there select include a search box */ @Input() @FlagInput() public filterable = false; @Input() @HostBinding("attr.id") get id(): string { return this._id; } set id(value: string) { this._id = value; } @Input() @FlagInput() public required = false; @Input() @HostBinding("class.bl-disabled") public get disabled(): boolean { if (this.ngControl && this.ngControl.disabled !== null) { return this.ngControl.disabled; } return this._disabled; } public set disabled(value: boolean) { this._disabled = coerceBooleanProperty(value); } @Input() public get value(): any | any[] { if (this.multiple) { return [...this.selected]; } else { return [...this.selected].first(); } } public set value(value: any | any[]) { if (value !== this.value) { this.writeValue(value); this.stateChanges.next(); } } @Output() public change = new EventEmitter<any | any[]>(); /** * ARIA */ @HostBinding("attr.aria-describedby") public ariaDescribedby: string; @HostBinding("attr.role") public readonly role = "combobox"; @HostBinding("attr.aria-haspopup") public readonly ariaHasPopup = "listbox"; @Input("attr.aria-label") @HostBinding("attr.aria-label") public set ariaLabel(label: string) { this._ariaLabel = label; } public get ariaLabel() { return this._ariaLabel || this.placeholder; } @HostBinding("attr.aria-expanded") public get ariaExpanded() { return this.dropdownOpen; } @HostBinding("attr.aria-owns") public get ariaOwns() { return this.dropdownId; } @HostBinding("attr.tabindex") public readonly tabindex = -1; // Options @ContentChildren(SelectOptionComponent, { descendants: true }) public options: QueryList<SelectOptionComponent<TValue>>; @ContentChild(OptionTemplateDirective, { read: TemplateRef, static: false }) public optionTemplate: TemplateRef<any>; public filter: string = ""; public set displayedOptions(displayedOptions: SelectOptionComponent[]) { this._displayedOptions = displayedOptions; if (this._dropdownRef) { this._dropdownRef.instance.displayedOptions = displayedOptions; } this._keyNavigator.items = displayedOptions; } public get displayedOptions() { return this._displayedOptions; } public set focusedOption(option: SelectOptionComponent) { this._focusedOption = option; if (this._dropdownRef) { this._dropdownRef.instance.focusedOption = option; } } public get focusedOption() { return this._focusedOption; } public set selected(selection: Set<any>) { this._selected = selection; if (this._dropdownRef) { this._dropdownRef.instance.selected = selection; } } public get selected() { return this._selected; } public readonly stateChanges = new Subject<void>(); public readonly controlType: string = "bl-select"; private _dropdownRef: ComponentRef<SelectDropdownComponent>; private _displayedOptions: SelectOptionComponent[]; private _focusedOption: SelectOptionComponent = null; private _overlayRef: OverlayRef; private _backDropClickSub: Subscription; private _id = `bl-select-${nextUniqueId++}`; private _disabled = false; private _ariaLabel: string | null = null; private _keyNavigator: ListKeyNavigator<SelectOptionComponent>; private _selected: Set<any> = new Set<any>(); @ViewChild("selectButton", { read: ElementRef, static: false }) private _selectButtonEl: ElementRef; @ViewChild("filterInput", { static: false }) private _filterInputEl: ElementRef; public get dropdownOpen() { return Boolean(this._dropdownRef); } private _propagateChange: (value: any) => void; private _touchedFn: () => void; private _optionsMap: Map<any, SelectOptionComponent> = new Map(); public get dropdownId() { return this.id + "-dropdown"; } constructor( @Self() @Optional() public ngControl: NgControl, private changeDetector: ChangeDetectorRef, private elementRef: ElementRef, private overlay: Overlay, private injector: Injector) { if (this.ngControl) { // Note: we provide the value accessor through here, instead of // the `providers` to avoid running into a circular import. this.ngControl.valueAccessor = this; } this._initKeyNavigator(); } public ngAfterContentInit() { this._computeOptions(); this.options.changes.subscribe((value) => { this._computeOptions(); }); setTimeout(() => { this.changeDetector.markForCheck(); }); } public ngOnDestroy() { if (this._overlayRef) { this._overlayRef.dispose(); } if (this._backDropClickSub) { this._backDropClickSub.unsubscribe(); } if (this._keyNavigator) { this._keyNavigator.dispose(); } } public writeValue(value: any): void { if (Array.isArray(value)) { this.selected = new Set(value); } else { this.selected = new Set(value !== undefined ? [value] : []); } if (!this._keyNavigator.focusedItem) { const option = this._getOptionByValue(value); if (option) { this._keyNavigator.focusItem(option); } } this.changeDetector.markForCheck(); } public registerOnChange(fn: any): void { this._propagateChange = fn; } public registerOnTouched(fn: any): void { this._touchedFn = fn; } public clickSelectButton(event: Event) { if (this.disabled) { return; } this.toggleDropdown(); event.stopPropagation(); } @HostListener("keydown", ["$event"]) public handleKeyDown(event: KeyboardEvent) { if (this.disabled) { return; } this.dropdownOpen ? this._handleKeydownOpen(event) : this._handleKeyDownClosed(event); } public get hasValueSelected() { return this.selected.size > 0; } public get hasMultipleSelected() { return this.selected.size > 1; } public get firstSelection() { return this._optionsMap.get([...this.selected].first()); } public get title() { if (this.hasValueSelected) { const values = [...this.selected].map(x => this._optionsMap.get(x)).map(x => x && x.label).join(", "); return `${this.placeholder}: ${values}`; } else { return this.placeholder; } } public toggleDropdown() { if (this.dropdownOpen) { this.closeDropdown(); } else { this.openDropdown(); } } public openDropdown() { if (this.filterable) { // Disable type ahead as there is a search bar when filterable is enabled this._keyNavigator.disableTypeAhead(); } this._overlayRef = this._createOverlay(); this._backDropClickSub = this._overlayRef.backdropClick().subscribe(() => { this.closeDropdown(); }); const injector = new SelectInjector(this, this.injector); const portal = new ComponentPortal(SelectDropdownComponent, null, injector); const ref = this._dropdownRef = this._overlayRef.attach(portal); ref.instance.id = this.dropdownId; ref.instance.displayedOptions = this.displayedOptions; ref.instance.focusedOption = this.focusedOption; ref.instance.selected = this.selected; ref.instance.multiple = this.multiple; ref.onDestroy(() => { this._dropdownRef = null; this._overlayRef = null; if (this._backDropClickSub) { this._backDropClickSub.unsubscribe(); this._backDropClickSub = null; } }); if (!this.focusedOption) { this.focusFirstOption(); } if (this.filterable) { setTimeout(() => { this._filterInputEl.nativeElement.focus(); }); } this.changeDetector.markForCheck(); } public closeDropdown(focus = true) { if (!this.dropdownOpen) { return; } if (this.filterable) { this._keyNavigator.withTypeAhead(); // Reenable typeAhead as it was disabled when dropdown is open } if (this._overlayRef) { this._overlayRef.dispose(); this._overlayRef = null; this._dropdownRef = null; } if (focus) { setTimeout(() => { this._selectButtonEl.nativeElement.focus(); }); } this.changeDetector.markForCheck(); } public selectOption(option: SelectOptionComponent | null) { this._keyNavigator.focusItem(option); let changed = false; if (this.multiple) { if (option) { if (this.selected.has(option.value)) { this.selected.delete(option.value); } else { this.selected.add(option.value); } } changed = true; } else { if (option) { if (!this.selected.has(option.value)) { changed = true; this.selected = new Set([option.value]); } } else { if (this.selected.size !== 0) { changed = true; this.selected = new Set([]); } } this.closeDropdown(); } if (changed) { this.notifyChanges(); } this.changeDetector.markForCheck(); } public unselectAll() { this.selected.clear(); this.notifyChanges(); this.changeDetector.markForCheck(); } public notifyChanges() { if (this._touchedFn) { this._touchedFn(); } if (this._propagateChange) { this._propagateChange(this.value); } this.change.emit(this.value); } public filterChanged(filter: string) { this.filter = filter; this._computeDisplayedOptions(); } public focusFirstOption() { this._keyNavigator.focusFirstItem(); } public setDescribedByIds(ids: string[]) { this.ariaDescribedby = ids.join(" "); } public onContainerClick(event: Event) { this._selectButtonEl.nativeElement.focus(); this.clickSelectButton(event); } public optionValueChanged(value: SimpleChange) { if (this._optionsMap.has(value.previousValue)) { const previous = this._optionsMap.get(value.previousValue); this._optionsMap.set(value.currentValue, previous); } this.changeDetector.markForCheck(); } public onButtonBlur() { if (this.dropdownOpen && !this.filterable) { this.closeDropdown(false); } } public onInputBlur() { if (this.dropdownOpen) { this.closeDropdown(false); } } private _computeOptions() { const optionsMap = new Map(); this.options.forEach((option) => { optionsMap.set(option.value, option); }); this._optionsMap = optionsMap; this._computeDisplayedOptions(); } private _computeDisplayedOptions() { const options = []; let focusedOptionIncluded = false; this.options.forEach((option) => { const label = option.label && option.label.toLowerCase(); if (!this.filter || label.contains(this.filter.toLowerCase())) { options.push(option); if (option === this.focusedOption) { focusedOptionIncluded = true; } } }); this.displayedOptions = options; // If the filter makes it that we don't see the currently focusesd option fallback to focussing the first item if (!focusedOptionIncluded && this.dropdownOpen && this.filterable && this.filter) { this.focusFirstOption(); } this.changeDetector.markForCheck(); } private _createOverlay(): OverlayRef { const dimensions = this.elementRef.nativeElement.getBoundingClientRect(); const positions: ConnectionPositionPair[] = [ { originX: "start", originY: "bottom", overlayX: "start", overlayY: "top", offsetX: 0, offsetY: 0, }, { originX: "start", originY: "top", overlayX: "start", overlayY: "bottom", offsetX: 0, offsetY: 0, }, ]; const positionStrategy = this.overlay.position().connectedTo(this.elementRef, { originX: "start", originY: "top" }, { overlayX: "start", overlayY: "bottom" }); positionStrategy.withPositions(positions); positionStrategy.onPositionChange.subscribe((x) => { if (this._dropdownRef) { this._dropdownRef.instance.above = x.connectionPair.overlayY === "bottom"; } }); return this.overlay.create(new OverlayConfig({ positionStrategy, scrollStrategy: this.overlay.scrollStrategies.block(), minWidth: dimensions.width, hasBackdrop: true, backdropClass: "cdk-overlay-transparent-backdrop", })); } private _handleKeyDownClosed(event: KeyboardEvent) { const keyCode = event.code; const isArrowKey = keyCode === "ArrowDown" || keyCode === "ArrowUp" || keyCode === "ArrowLeft" || keyCode === "ArrowRight"; const isOpenKey = keyCode === "Enter" || keyCode === "Space"; // Open the select on ALT + arrow key to match the native <select> if (isOpenKey || ((this.multiple || event.altKey) && isArrowKey)) { event.preventDefault(); // prevents the page from scrolling down when pressing space this.openDropdown(); } else { this._keyNavigator.onKeydown(event); } } private _handleKeydownOpen(event: KeyboardEvent) { if (this.displayedOptions.length === 0) { return; } const keyCode = event.keyCode; const isArrowKey = keyCode === DOWN_ARROW || keyCode === UP_ARROW; const navigator = this._keyNavigator; if (keyCode === HOME || keyCode === END) { event.preventDefault(); keyCode === HOME ? navigator.focusFirstItem() : navigator.focusLastItem(); } else if (isArrowKey && event.altKey || keyCode === ESCAPE) { // Close the select on ALT + arrow key to match the native <select> event.preventDefault(); this.closeDropdown(); } else if ((keyCode === ENTER || keyCode === SPACE) && navigator.focusedItem) { event.preventDefault(); this.selectOption(navigator.focusedItem); } else { const previouslyFocusedIndex = navigator.focusedItemIndex; navigator.onKeydown(event); if (this.multiple && isArrowKey && event.shiftKey && navigator.focusedItem && navigator.focusedItemIndex !== previouslyFocusedIndex) { this.selectOption(navigator.focusedItem); } } } /** Sets up a key manager to listen to keyboard events on the overlay panel. */ private _initKeyNavigator() { this._keyNavigator = new ListKeyNavigator<SelectOptionComponent>() .withWrap() .withTypeAhead(); this._keyNavigator.change.subscribe((index) => { const option = this.focusedOption = this._keyNavigator.focusedItem; this.changeDetector.markForCheck(); if (this.dropdownOpen) { this._scrollToFocusedItem(); } else if (!this.dropdownOpen && !this.multiple) { this.selectOption(option); } }); } private _getOptionByValue(value: any) { return this.displayedOptions && this.displayedOptions.find(x => x.value === value); } private _scrollToFocusedItem() { this._dropdownRef.instance.scrollToIndex(this._keyNavigator.focusedItemIndex); } }
the_stack
import { debugAssert, debugCast } from '../util/assert'; import { wrapInUserErrorIfRecoverable } from '../util/async_queue'; import { FirestoreError } from '../util/error'; import { EventHandler } from '../util/misc'; import { ObjectMap } from '../util/obj_map'; import { canonifyQuery, Query, queryEquals, stringifyQuery } from './query'; import { OnlineState } from './types'; import { ChangeType, DocumentViewChange, ViewSnapshot } from './view_snapshot'; /** * Holds the listeners and the last received ViewSnapshot for a query being * tracked by EventManager. */ class QueryListenersInfo { viewSnap: ViewSnapshot | undefined = undefined; listeners: QueryListener[] = []; } /** * Interface for handling events from the EventManager. */ export interface Observer<T> { next: EventHandler<T>; error: EventHandler<FirestoreError>; } /** * EventManager is responsible for mapping queries to query event emitters. * It handles "fan-out". -- Identical queries will re-use the same watch on the * backend. * * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This * allows users to tree-shake the Watch logic. */ export interface EventManager { onListen?: (query: Query) => Promise<ViewSnapshot>; onUnlisten?: (query: Query) => Promise<void>; } export function newEventManager(): EventManager { return new EventManagerImpl(); } export class EventManagerImpl implements EventManager { queries = new ObjectMap<Query, QueryListenersInfo>( q => canonifyQuery(q), queryEquals ); onlineState = OnlineState.Unknown; snapshotsInSyncListeners: Set<Observer<void>> = new Set(); /** Callback invoked when a Query is first listen to. */ onListen?: (query: Query) => Promise<ViewSnapshot>; /** Callback invoked once all listeners to a Query are removed. */ onUnlisten?: (query: Query) => Promise<void>; } export async function eventManagerListen( eventManager: EventManager, listener: QueryListener ): Promise<void> { const eventManagerImpl = debugCast(eventManager, EventManagerImpl); debugAssert(!!eventManagerImpl.onListen, 'onListen not set'); const query = listener.query; let firstListen = false; let queryInfo = eventManagerImpl.queries.get(query); if (!queryInfo) { firstListen = true; queryInfo = new QueryListenersInfo(); } if (firstListen) { try { queryInfo.viewSnap = await eventManagerImpl.onListen(query); } catch (e) { const firestoreError = wrapInUserErrorIfRecoverable( e, `Initialization of query '${stringifyQuery(listener.query)}' failed` ); listener.onError(firestoreError); return; } } eventManagerImpl.queries.set(query, queryInfo); queryInfo.listeners.push(listener); // Run global snapshot listeners if a consistent snapshot has been emitted. const raisedEvent = listener.applyOnlineStateChange( eventManagerImpl.onlineState ); debugAssert( !raisedEvent, "applyOnlineStateChange() shouldn't raise an event for brand-new listeners." ); if (queryInfo.viewSnap) { const raisedEvent = listener.onViewSnapshot(queryInfo.viewSnap); if (raisedEvent) { raiseSnapshotsInSyncEvent(eventManagerImpl); } } } export async function eventManagerUnlisten( eventManager: EventManager, listener: QueryListener ): Promise<void> { const eventManagerImpl = debugCast(eventManager, EventManagerImpl); debugAssert(!!eventManagerImpl.onUnlisten, 'onUnlisten not set'); const query = listener.query; let lastListen = false; const queryInfo = eventManagerImpl.queries.get(query); if (queryInfo) { const i = queryInfo.listeners.indexOf(listener); if (i >= 0) { queryInfo.listeners.splice(i, 1); lastListen = queryInfo.listeners.length === 0; } } if (lastListen) { eventManagerImpl.queries.delete(query); return eventManagerImpl.onUnlisten(query); } } export function eventManagerOnWatchChange( eventManager: EventManager, viewSnaps: ViewSnapshot[] ): void { const eventManagerImpl = debugCast(eventManager, EventManagerImpl); let raisedEvent = false; for (const viewSnap of viewSnaps) { const query = viewSnap.query; const queryInfo = eventManagerImpl.queries.get(query); if (queryInfo) { for (const listener of queryInfo.listeners) { if (listener.onViewSnapshot(viewSnap)) { raisedEvent = true; } } queryInfo.viewSnap = viewSnap; } } if (raisedEvent) { raiseSnapshotsInSyncEvent(eventManagerImpl); } } export function eventManagerOnWatchError( eventManager: EventManager, query: Query, error: FirestoreError ): void { const eventManagerImpl = debugCast(eventManager, EventManagerImpl); const queryInfo = eventManagerImpl.queries.get(query); if (queryInfo) { for (const listener of queryInfo.listeners) { listener.onError(error); } } // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten() // after an error. eventManagerImpl.queries.delete(query); } export function eventManagerOnOnlineStateChange( eventManager: EventManager, onlineState: OnlineState ): void { const eventManagerImpl = debugCast(eventManager, EventManagerImpl); eventManagerImpl.onlineState = onlineState; let raisedEvent = false; eventManagerImpl.queries.forEach((_, queryInfo) => { for (const listener of queryInfo.listeners) { // Run global snapshot listeners if a consistent snapshot has been emitted. if (listener.applyOnlineStateChange(onlineState)) { raisedEvent = true; } } }); if (raisedEvent) { raiseSnapshotsInSyncEvent(eventManagerImpl); } } export function addSnapshotsInSyncListener( eventManager: EventManager, observer: Observer<void> ): void { const eventManagerImpl = debugCast(eventManager, EventManagerImpl); eventManagerImpl.snapshotsInSyncListeners.add(observer); // Immediately fire an initial event, indicating all existing listeners // are in-sync. observer.next(); } export function removeSnapshotsInSyncListener( eventManager: EventManager, observer: Observer<void> ): void { const eventManagerImpl = debugCast(eventManager, EventManagerImpl); eventManagerImpl.snapshotsInSyncListeners.delete(observer); } // Call all global snapshot listeners that have been set. function raiseSnapshotsInSyncEvent(eventManagerImpl: EventManagerImpl): void { eventManagerImpl.snapshotsInSyncListeners.forEach(observer => { observer.next(); }); } export interface ListenOptions { /** Raise events even when only the metadata changes */ readonly includeMetadataChanges?: boolean; /** * Wait for a sync with the server when online, but still raise events while * offline. */ readonly waitForSyncWhenOnline?: boolean; } /** * QueryListener takes a series of internal view snapshots and determines * when to raise the event. * * It uses an Observer to dispatch events. */ export class QueryListener { /** * Initial snapshots (e.g. from cache) may not be propagated to the wrapped * observer. This flag is set to true once we've actually raised an event. */ private raisedInitialEvent = false; private options: ListenOptions; private snap: ViewSnapshot | null = null; private onlineState = OnlineState.Unknown; constructor( readonly query: Query, private queryObserver: Observer<ViewSnapshot>, options?: ListenOptions ) { this.options = options || {}; } /** * Applies the new ViewSnapshot to this listener, raising a user-facing event * if applicable (depending on what changed, whether the user has opted into * metadata-only changes, etc.). Returns true if a user-facing event was * indeed raised. */ onViewSnapshot(snap: ViewSnapshot): boolean { debugAssert( snap.docChanges.length > 0 || snap.syncStateChanged, 'We got a new snapshot with no changes?' ); if (!this.options.includeMetadataChanges) { // Remove the metadata only changes. const docChanges: DocumentViewChange[] = []; for (const docChange of snap.docChanges) { if (docChange.type !== ChangeType.Metadata) { docChanges.push(docChange); } } snap = new ViewSnapshot( snap.query, snap.docs, snap.oldDocs, docChanges, snap.mutatedKeys, snap.fromCache, snap.syncStateChanged, /* excludesMetadataChanges= */ true ); } let raisedEvent = false; if (!this.raisedInitialEvent) { if (this.shouldRaiseInitialEvent(snap, this.onlineState)) { this.raiseInitialEvent(snap); raisedEvent = true; } } else if (this.shouldRaiseEvent(snap)) { this.queryObserver.next(snap); raisedEvent = true; } this.snap = snap; return raisedEvent; } onError(error: FirestoreError): void { this.queryObserver.error(error); } /** Returns whether a snapshot was raised. */ applyOnlineStateChange(onlineState: OnlineState): boolean { this.onlineState = onlineState; let raisedEvent = false; if ( this.snap && !this.raisedInitialEvent && this.shouldRaiseInitialEvent(this.snap, onlineState) ) { this.raiseInitialEvent(this.snap); raisedEvent = true; } return raisedEvent; } private shouldRaiseInitialEvent( snap: ViewSnapshot, onlineState: OnlineState ): boolean { debugAssert( !this.raisedInitialEvent, 'Determining whether to raise first event but already had first event' ); // Always raise the first event when we're synced if (!snap.fromCache) { return true; } // NOTE: We consider OnlineState.Unknown as online (it should become Offline // or Online if we wait long enough). const maybeOnline = onlineState !== OnlineState.Offline; // Don't raise the event if we're online, aren't synced yet (checked // above) and are waiting for a sync. if (this.options.waitForSyncWhenOnline && maybeOnline) { debugAssert( snap.fromCache, 'Waiting for sync, but snapshot is not from cache' ); return false; } // Raise data from cache if we have any documents or we are offline return !snap.docs.isEmpty() || onlineState === OnlineState.Offline; } private shouldRaiseEvent(snap: ViewSnapshot): boolean { // We don't need to handle includeDocumentMetadataChanges here because // the Metadata only changes have already been stripped out if needed. // At this point the only changes we will see are the ones we should // propagate. if (snap.docChanges.length > 0) { return true; } const hasPendingWritesChanged = this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites; if (snap.syncStateChanged || hasPendingWritesChanged) { return this.options.includeMetadataChanges === true; } // Generally we should have hit one of the cases above, but it's possible // to get here if there were only metadata docChanges and they got // stripped out. return false; } private raiseInitialEvent(snap: ViewSnapshot): void { debugAssert( !this.raisedInitialEvent, 'Trying to raise initial events for second time' ); snap = ViewSnapshot.fromInitialDocuments( snap.query, snap.docs, snap.mutatedKeys, snap.fromCache ); this.raisedInitialEvent = true; this.queryObserver.next(snap); } }
the_stack
import * as sinon from 'sinon'; import { expect } from 'chai'; import { noop, isFunction } from '../../../src/facade/lang'; import { AfterContentInit, OnDestroy, OnInit, AfterViewInit } from '../../../src/core/linker/directive_lifecycle_interfaces'; import { Component, Directive, Input, Attr, Output, HostListener, HostBinding } from '../../../src/core/directives/decorators'; import { Inject, Host } from '../../../src/core/di/decorators'; import { $Scope, $Attrs, ElementFactory } from '../../utils'; import { directiveProvider } from '../../../src/core/directives/directive_provider'; import { NgModel } from '../../../src/common/directives/ng_model'; import { NgmDirective } from '../../../src/core/directives/constants'; describe( `directives/directive_provider`, ()=> { it( `should create angular 1 directive factory and create directive name`, ()=> { @Directive( { selector: '[myClicker]', host: { tabindex: '1', role: 'button' } } ) class MyClicker implements OnDestroy,AfterContentInit,OnInit { static test = { destroy: false, init: false, contentInit: false }; @Input() enableColor: boolean; @Attr() defaultColor: string; @Output() execMe: Function; @HostBinding( 'class.is-disabled' ) isDisabled: boolean; @HostListener( 'click', [ '$event' ] ) onClick() { this.$attrs.$addClass( 'clicked' ); this.execMe(); } constructor( @Inject( '$attrs' ) private $attrs: ng.IAttributes ) {} ngOnInit() { MyClicker.test.init = true } ngAfterContentInit() { MyClicker.test.init = true } ngOnDestroy() { MyClicker.test.destroy = true } } const [directiveName,directiveFactory] = directiveProvider.createFromType( MyClicker ); const ddo: NgmDirective = directiveFactory(); expect( directiveName ).to.equal( 'myClicker' ); expect( isFunction( directiveFactory ) ).to.equal( true ); expect( directiveFactory() ).to.deep.equal( { restrict: 'A', require: [ 'myClicker' ], controller: ddo.controller, link: (ddo.link as ng.IDirectivePrePost), _ngOnInitBound: ddo._ngOnInitBound } ); const howShouldLinkFnLookLike = function postLink( scope, element, attrs: ng.IAttributes, controller ) { const _watchers = []; const _observers = []; const [ctrl] = controller; // setup Inputs _watchers.push( scope.$watch( (attrs as any).enableColor, ( newValue )=> { ctrl.isDisabled = newValue; } ) ); // setup Attrs _observers.push( attrs.$observe( 'defaultColor', ( value )=> { ctrl.defaultColor = value; } ) ); // setup Outputs ctrl.execMe = ()=> { scope.$eval( (attrs as any).execMe ) }; // setup host attributes attrs.$set( 'tabindex', '1' ); attrs.$set( 'role', 'button' ); // setup @HostBindings _watchers.push( scope.$watch( ()=>ctrl.isDisabled, ( newValue )=> { if ( newValue ) { attrs.$addClass( 'isDisabled' ) } else { attrs.$removeClass( 'isDisabled' ) } } ) ); // setup @HostListeners element .on( 'click', function ( $event ) { const noPreventDefault = Boolean( ctrl.onClick() ); if ( noPreventDefault ) { $event.preventDefault(); } } ); // AfterContent Hooks ctrl.ngAfterContentInit(); // destroy scope.$on( '$destroy', ()=> { ctrl.ngOnDestroy(); _watchers.forEach( _watcherDispose=>_watcherDispose() ); _observers.forEach( _observerDispose=>_observerDispose() ); element.off(); } ); }; } ); it( `should correctly create angular 1 directive component and it's name`, ()=> { @Component( { selector: 'jedi-master', host: { tabindex: '1' }, template: `<div>Click me to attack!</div>` } ) class JediMasterCmp implements OnDestroy,AfterViewInit,OnInit { static test = { destroy: false, init: false, contentInit: false }; @Input() enableColor: boolean; @Attr() defaultColor: string; @Output() onLightsaberAttack: Function; @HostBinding( 'class.is-disabled' ) isDisabled: boolean; @HostListener( 'click', [ '$event' ] ) onClick() { this.$attrs.$addClass( 'clicked' ); this.onLightsaberAttack(); } constructor( @Inject( '$attrs' ) private $attrs: ng.IAttributes ) {} ngOnInit() { JediMasterCmp.test.init = true } ngAfterViewInit() { JediMasterCmp.test.init = true } ngOnDestroy() { JediMasterCmp.test.destroy = true } } const [directiveName,directiveFactory] = directiveProvider.createFromType( JediMasterCmp ); const ddo: NgmDirective = directiveFactory(); expect( directiveName ).to.equal( 'jediMaster' ); expect( isFunction( directiveFactory ) ).to.equal( true ); expect( ddo ).to.deep.equal( { restrict: 'E', scope: {}, bindToController: { // enableColor: '=', // defaultColor: '@', // onLightsaberAttack: '&' }, require: [ 'jediMaster' ], controller: ddo.controller, controllerAs: '$ctrl', link: (ddo.link as ng.IDirectivePrePost), template: `<div>Click me to attack!</div>`, transclude: false, _ngOnInitBound: ddo._ngOnInitBound } ); const howShoulsLinkLookLike = { pre: function ( scope, element, attrs, controller ) { const [ctrl] = controller; ctrl.ngOnInit(); }, post: function ( scope, element, attrs: ng.IAttributes, controller ) { const _watchers = []; const [ctrl] = controller; // setup host attributes attrs.$set( 'tabindex', '1' ); // setup @HostBindings _watchers.push( scope.$watch( ()=>ctrl.isDisabled, ( newValue )=> { if ( newValue ) { attrs.$addClass( 'isDisabled' ) } else { attrs.$removeClass( 'isDisabled' ) } } ) ); // setup @HostListeners element .on( 'click', function ( $event ) { const noPreventDefault = Boolean( ctrl.onClick() ); if ( noPreventDefault ) { $event.preventDefault(); } } ); // AfterContent Hooks ctrl.ngAfterViewInit(); // destroy scope.$on( '$destroy', ()=> { ctrl.ngOnDestroy(); _watchers.forEach( _watcherDispose=>_watcherDispose() ); element.off(); } ); } }; } ); describe( `local directive injections`, ()=> { it( `should correctly inject and bind directive to instance by string`, ()=> { @Directive({selector:'[validator]'}) class MyValidator{ constructor( @Inject('$log') $log: ng.ILogService, @Host() private ngModel: NgModel ){} } const [directiveName,directiveFactory] = directiveProvider.createFromType( MyValidator ); const ddo: NgmDirective = directiveFactory(); expect( directiveName ).to.equal( 'validator' ); expect( isFunction( directiveFactory ) ).to.equal( true ); expect( directiveFactory() ).to.deep.equal( { restrict: 'A', require: [ 'validator','^ngModel' ], controller: ddo.controller, link: ddo.link as ng.IDirectiveLinkFn, _ngOnInitBound: ddo._ngOnInitBound } ); } ); it( `should correctly inject and bind directive to instance by Injectable `, ()=> { @Directive({selector:'[my-css-mutator]'}) class CssHandler{} @Directive({selector:'[my-css-extractor]'}) class CssExtractorHandler{} @Directive({selector:'[validator]'}) class MyValidator{ constructor( @Inject('$log') $log: ng.ILogService, @Inject('ngModel') @Host() private ngModel, @Inject(CssHandler) @Host() private myCssMutator, @Host() private myCssExtractor: CssExtractorHandler ){} } const [directiveName,directiveFactory] = directiveProvider.createFromType( MyValidator ); const ddo: NgmDirective = directiveFactory(); expect( directiveName ).to.equal( 'validator' ); expect( isFunction( directiveFactory ) ).to.equal( true ); expect( directiveFactory() ).to.deep.equal( { restrict: 'A', require: [ 'validator','^ngModel','^myCssMutator','^myCssExtractor' ], controller: ddo.controller, link: ddo.link as ng.IDirectiveLinkFn, _ngOnInitBound: ddo._ngOnInitBound } ); } ); } ); describe( `static DDO methods on class`, ()=> { describe( `compile function`, ()=> { it( `should allow to define compile ddo function as static method`, ()=> { const spyFromCompile = sinon.spy(); @Directive({selector:'[with-compile]'}) class WithCompileDirective{ static compile(tElement:ng.IAugmentedJQuery,tAttrs:ng.IAttributes){ spyFromCompile(); } } const [,directiveFactory] = directiveProvider.createFromType( WithCompileDirective ); const ddo: NgmDirective = directiveFactory(); expect( isFunction(ddo.compile) ).to.equal(true); expect( ddo ).to.deep.equal( { restrict: 'A', require: [ 'withCompile' ], controller: ddo.controller, compile: ddo.compile, link: ddo.link as ng.IDirectiveLinkFn, _ngOnInitBound: ddo._ngOnInitBound } ); expect( spyFromCompile.called ).to.equal( false ); const linkFromCompileFn = ddo.compile({} as ng.IAugmentedJQuery,{} as ng.IAttributes, noop as ng.ITranscludeFunction) expect( linkFromCompileFn ).to.equal( ddo.link ); expect( spyFromCompile.called ).to.equal( true ); } ); it( `should return the link fn from compile if it returns function`, ()=> { const spyFromCompile = sinon.spy(); const spyFromLink = sinon.spy(); @Directive( { selector: '[with-compile]' } ) class WithCompileDirective { static compile( tElement: ng.IAugmentedJQuery, tAttrs: ng.IAttributes ) { spyFromCompile(); return function postLink( scope, element, attrs, controller, transclude ) { spyFromLink(); } } } const [,directiveFactory] = directiveProvider.createFromType( WithCompileDirective ); const ddo: ng.IDirective = directiveFactory(); const ddoLinkSpy = sinon.spy( ddo.link, 'post' ); expect( spyFromCompile.called ).to.equal( false ); expect( ddoLinkSpy.called ).to.equal( false ); const linkFromCompileFn = ddo.compile( {} as ng.IAugmentedJQuery, {} as ng.IAttributes, noop as ng.ITranscludeFunction ) as Function; expect( spyFromCompile.called ).to.equal( true ); expect( linkFromCompileFn ).to.not.equal( ddo.link ); linkFromCompileFn( {}, {}, {}, noop, noop ); expect( spyFromLink.called ).to.equal( true ); } ); } ); describe( `link function`, ()=> { it( `should allow to define link ddo function as static method`, ()=> { const spyFromLink = sinon.spy(); @Directive({selector:'[with-compile]'}) class WithLink{ static link(scope,el,attrs,ctrl,translcude){ spyFromLink(); } } const [,directiveFactory] = directiveProvider.createFromType( WithLink ); const ddo: NgmDirective = directiveFactory(); expect( isFunction( ddo.link ) ).to.equal( true ); expect( ddo.link ).to.equal( WithLink.link ); expect( ddo ).to.deep.equal( { restrict: 'A', require: [ 'withCompile' ], controller: ddo.controller, link: WithLink.link as ng.IDirectiveLinkFn, _ngOnInitBound: ddo._ngOnInitBound } ); expect( spyFromLink.called ).to.equal( false ); (ddo.link as ng.IDirectiveLinkFn)( {} as ng.IScope, {} as ng.IAugmentedJQuery, {} as ng.IAttributes, noop, noop as ng.ITranscludeFunction ); expect( spyFromLink.called ).to.equal( true ); } ); } ); } ); describe( `life cycles`, ()=> { let $element; let $scope; let $attrs; let $transclude; beforeEach( ()=> { $element = ElementFactory(); $scope = new $Scope(); $attrs = new $Attrs(); $transclude = noop(); } ); it( `should call ngOnDestroy only if it's implemented from postLink`, ()=> { @Directive({selector:'[myDir]'}) class MyDirective{ ngOnDestroy(){} } const ctrl = [ new MyDirective() ]; const spy = sinon.spy( ctrl[0],'ngOnDestroy' ); const directiveProviderArr = directiveProvider.createFromType( MyDirective ); const ddo = directiveProviderArr[ 1 ](); const link = (ddo.link as ng.IDirectivePrePost).post as ng.IDirectiveLinkFn; expect( isFunction( link ) ).to.equal( true ); expect( spy.called ).to.equal( false ); link( $scope, $element, $attrs, ctrl, $transclude ); expect( spy.called ).to.equal( false ); $scope.$emit( '$destroy' ); expect( spy.called ).to.equal( true ); spy.restore(); } ); it( `should call ngAfterContentInit only if it's implemented from postLink`, ()=> { @Directive({selector:'[myDir]'}) class MyDirective implements AfterContentInit{ ngAfterContentInit(){} } const ctrl = [ new MyDirective() ]; const spy = sinon.spy( ctrl[0],'ngAfterContentInit' ); const directiveProviderArr = directiveProvider.createFromType( MyDirective ); const ddo = directiveProviderArr[ 1 ](); const link = (ddo.link as ng.IDirectivePrePost).post as ng.IDirectiveLinkFn; expect( isFunction( link ) ).to.equal( true ); expect( spy.called ).to.equal( false ); link( $scope, $element, $attrs, ctrl, $transclude ); expect( spy.called ).to.equal( true ); spy.restore(); } ); it( `should call ngAfterViewInit from @Component only if it's implemented from postLink`, ()=> { @Component({selector:'my-cmp'}) class MyComponent implements AfterViewInit{ ngAfterViewInit() {} } const ctrl = [ new MyComponent() ]; const spy = sinon.spy( ctrl[0],'ngAfterViewInit' ); const directiveProviderArr = directiveProvider.createFromType( MyComponent ); const ddo = directiveProviderArr[ 1 ](); const link = (ddo.link as ng.IDirectivePrePost).post as ng.IDirectiveLinkFn; expect( isFunction( link ) ).to.equal( true ); expect( spy.called ).to.equal( false ); link( $scope, $element, $attrs, ctrl, $transclude ); expect( spy.called ).to.equal( true ); spy.restore(); } ); it( `should call all hooks if they are implemented from postLink expect ngOnInit which is called form preLink`, ()=> { @Directive({selector:'[myDir]'}) class MyDirective{ constructor(){} ngOnInit(){} ngAfterContentInit(){} ngOnDestroy(){} } const ctrl = [ new MyDirective() ]; // mock _ngOnInitBound const _ngOnInitBound = function () {ctrl[ 0 ].ngOnInit()}; const spyInit = sinon.spy( ctrl[0],'ngOnInit' ); const spyAfterContentInit = sinon.spy( ctrl[0],'ngAfterContentInit' ); const spyDestroy = sinon.spy( ctrl[0],'ngOnDestroy' ); const directiveProviderArr = directiveProvider.createFromType( MyDirective ); const ddo = directiveProviderArr[ 1 ](); sinon.stub( ddo.link, 'pre', ()=>_ngOnInitBound() ); const { pre:preLink, post:postLink } = ddo.link as ng.IDirectivePrePost; expect( isFunction( preLink ) ).to.equal( true ); expect( isFunction( postLink ) ).to.equal( true ); expect( spyInit.called ).to.equal( false ); expect( spyAfterContentInit.called ).to.equal( false ); expect( spyDestroy.called ).to.equal( false ); preLink( $scope, $element, $attrs, ctrl, $transclude ); expect( spyInit.called ).to.equal( true ); postLink( $scope, $element, $attrs, ctrl, $transclude ); expect( spyAfterContentInit.called ).to.equal( true ); expect( spyDestroy.called ).to.equal( false ); $scope.$emit( '$destroy' ); expect( spyAfterContentInit.called ).to.equal( true ); expect( spyDestroy.called ).to.equal( true ); spyInit.restore(); spyAfterContentInit.restore(); spyDestroy.restore(); (ddo.link as any).pre.restore(); } ); it( `should allow @Directive to implements AfterViewInit/AfterViewCheck`, ()=> { @Directive( { selector: '[myDir]' } ) class MyDirective implements AfterViewInit, AfterContentInit { ngAfterViewInit() {} ngAfterContentInit() {} } const ctrl = [ new MyDirective() ]; const spyAfterViewInit = sinon.spy( ctrl[0],'ngAfterViewInit' ); const spyAfterContentInit = sinon.spy( ctrl[0],'ngAfterContentInit' ); const ddo = directiveProvider.createFromType( MyDirective )[1](); const { pre:preLink, post:postLink } = ddo.link as ng.IDirectivePrePost; expect( ()=>directiveProvider.createFromType( MyDirective ) ).to.not.throw(); expect( isFunction( preLink ) ).to.equal( true ); expect( isFunction( postLink ) ).to.equal( true ); expect( spyAfterContentInit.called ).to.equal( false ); expect( spyAfterViewInit.called ).to.equal( false ); postLink( $scope, $element, $attrs, ctrl, $transclude ); expect( spyAfterContentInit.called ).to.equal( true ); expect( spyAfterViewInit.called ).to.equal( true ); spyAfterContentInit.restore(); spyAfterViewInit.restore(); } ); describe( `error handling`, ()=> { it( `should throw if @Component implements both AfterViewInit and AfterContentInit`, ()=> { @Component({selector:'my-cmp'}) class MyComponent implements AfterViewInit,AfterContentInit{ ngAfterContentInit() {} ngAfterViewInit() {} } expect( ()=>directiveProvider.createFromType( MyComponent ) ).to.throw(); } ); } ); } ); describe( `ngComponentRouter life cycles`, () => { it( `should enable $routeConfig withing legacy property and set it do directiveFactory as a property`, () => { @Component( { selector: 'root', template: `<h1>hello</h1><ng-outlet></ng-outlet>`, legacy: { $routeConfig: [ { path: '/users', name: 'Users', component: 'users', useAsDefault: true }, { path: '/users/:id', name: 'UserDetail', component: 'usersDetail' } ] } } ) class RootComponent { } const [name,factory]:[string,any] = directiveProvider.createFromType( RootComponent ); const expected = [ { path: '/users', name: 'Users', component: 'users', useAsDefault: true }, { path: '/users/:id', name: 'UserDetail', component: 'usersDetail' } ]; expect( factory.$routeConfig ).to.deep.equal( expected ); } ); it( `should set all component router lc hooks to direcitveFactory function as static properties`, () => { @Component( { selector: 'root', template: `<h1>hello</h1><ng-outlet></ng-outlet>`, legacy: { $routeConfig: [ { path: '/users', name: 'Users', component: 'users', useAsDefault: true }, { path: '/users/:id', name: 'UserDetail', component: 'usersDetail' } ] } } ) class RootComponent { static $canActivate() {} $routeOnActivate() {} $routeOnDeactivate() {} } const [name,factory]:[string,any] = directiveProvider.createFromType( RootComponent ); expect( factory.$canActivate ).to.equal( RootComponent.$canActivate ); } ); } ); describe( `private API`, ()=> { describe( `#_createRequires`, ()=> { it( `should return require array from require map`, ()=> { const requireMap = { clicker: '^clicker', api: '?^api', ngModel: 'ngModel' } as {[key:string]:string}; const directiveName = 'own'; const actual = directiveProvider._createRequires( requireMap, directiveName ); const expected = [ 'own', '^clicker', '?^api', 'ngModel' ]; expect( actual ).to.deep.equal( expected ); } ); } ); describe( `#_createDDO`, ()=> { it( `should create DDO from shell and provided ddo`, ()=> { const actual = directiveProvider._createDDO( { scope: {}, bindToController: { item: '=' }, require: [ 'foo' ], controller: class Foo {}, controllerAs: 'ctrl', template: 'hello' }, {} ); const expected = { scope: {}, bindToController: { item: '=' }, require: [ 'foo' ], controller: actual.controller, controllerAs: 'ctrl', template: 'hello', link: actual.link }; expect( actual ).to.deep.equal( expected ); } ); it( `should overwrite any property with legacy DDO`, ()=> { const actual = directiveProvider._createDDO( { scope: {}, bindToController: { item: '=' }, require: [ 'foo' ], controller: class Foo {}, controllerAs: 'ctrl', template: 'hello' }, { scope: true, controllerAs: 'foo', transclude: false } ); const expected = { scope: true, bindToController: { item: '=' }, require: [ 'foo' ], controller: actual.controller, controllerAs: 'foo', template: 'hello', link: actual.link, transclude: false }; expect( actual ).to.deep.equal( expected ); } ); } ); } ); } );
the_stack
import cx from 'classnames' import mime from 'mime-types' import * as R from 'ramda' import * as React from 'react' import { useDropzone } from 'react-dropzone' import type * as RF from 'react-final-form' import { fade } from '@material-ui/core/styles' import * as M from '@material-ui/core' import JsonEditor from 'components/JsonEditor' import { JsonValue, ValidationErrors } from 'components/JsonEditor/constants' import JsonValidationErrors from 'components/JsonValidationErrors' import MetadataEditor from 'components/MetadataEditor' import * as Notifications from 'containers/Notifications' import Delay from 'utils/Delay' import useDragging from 'utils/dragging' import { JsonSchema } from 'utils/json-schema' import * as spreadsheets from 'utils/spreadsheets' import { readableBytes } from 'utils/string' import { JsonRecord } from 'utils/types' const MAX_META_FILE_SIZE = 10 * 1000 * 1000 // 10MB const useDialogStyles = M.makeStyles({ paper: { height: '100vh', }, }) const useStyles = M.makeStyles({ content: { height: '100%', }, switch: { marginRight: 'auto', }, }) interface DialogProps { onChange: (value: JsonValue) => void onClose: () => void open: boolean value: JsonValue schema?: JsonSchema } function Dialog({ onChange, onClose, open, schema, value }: DialogProps) { const [innerValue, setInnerValue] = React.useState(value) const classes = useStyles() const dialogClasses = useDialogStyles() const [isRaw, setRaw] = React.useState(false) const handleSubmit = React.useCallback(() => { onChange(innerValue) onClose() }, [innerValue, onChange, onClose]) const handleCancel = React.useCallback(() => { setInnerValue(value) onClose() }, [onClose, value]) return ( <M.Dialog fullWidth maxWidth="xl" onClose={handleCancel} open={open} classes={dialogClasses} > <M.DialogTitle>Package-level metadata</M.DialogTitle> <M.DialogContent className={classes.content}> <MetadataEditor multiColumned isRaw={isRaw} value={innerValue} onChange={setInnerValue} schema={schema} /> </M.DialogContent> <M.DialogActions> <M.FormControlLabel className={classes.switch} control={<M.Switch checked={isRaw} onChange={() => setRaw(!isRaw)} />} label="Edit as JSON" /> <M.Button onClick={handleCancel}>Discard</M.Button> <M.Button onClick={handleSubmit} variant="contained" color="primary"> Save </M.Button> </M.DialogActions> </M.Dialog> ) } const readTextFile = (file: File): Promise<string> => new Promise((resolve, reject) => { const reader = new FileReader() reader.onabort = () => { reject(new Error('abort')) } reader.onerror = () => { reject(reader.error) } reader.onload = () => { resolve(reader.result as string) } reader.readAsText(file) }) const readFile = (file: File, schema?: JsonSchema): Promise<string | {}> => { const mimeType = mime.extension(file.type) if (mimeType && /ods|odt|csv|xlsx|xls/.test(mimeType)) return spreadsheets.readAgainstSchema(file, schema) return readTextFile(file) } const useMetaInputStyles = M.makeStyles((t) => ({ header: { alignItems: 'center', display: 'flex', marginBottom: t.spacing(2), height: 24, }, btn: { fontSize: 11, height: 24, paddingBottom: 0, paddingLeft: 7, paddingRight: 7, paddingTop: 0, }, errors: { marginTop: t.spacing(1), }, add: { marginTop: t.spacing(2), }, row: { alignItems: 'center', display: 'flex', marginTop: t.spacing(1), }, sep: { ...t.typography.body1, marginLeft: t.spacing(1), marginRight: t.spacing(1), }, json: { alignItems: 'flex-start', display: 'flex', }, jsonTrigger: { marginLeft: 'auto', }, key: { flexBasis: 100, flexGrow: 1, }, value: { flexBasis: 100, flexGrow: 2, }, dropzone: { display: 'flex', flexDirection: 'column', overflowY: 'auto', position: 'relative', }, metaContent: { display: 'flex', flexDirection: 'column', }, outlined: { bottom: '1px', left: 0, outline: `2px dashed ${t.palette.primary.light}`, outlineOffset: '-2px', position: 'absolute', right: 0, top: '1px', zIndex: 1, }, overlay: { background: 'rgba(255,255,255,0.6)', bottom: 0, left: 0, position: 'absolute', right: 0, top: 0, transition: 'background 0.15s ease', zIndex: 1, }, overlayDraggable: { bottom: '3px', left: '2px', right: '2px', top: '3px', }, overlayDragActive: { background: fade(t.palette.grey[200], 0.8), }, overlayContents: { alignItems: 'center', display: 'flex', height: '100%', justifyContent: 'center', maxHeight: 120, }, overlayText: { ...t.typography.body1, color: t.palette.text.secondary, }, overlayProgress: { marginRight: t.spacing(1), }, })) export const EMPTY_META_VALUE = {} interface MetaInputProps { className?: string schemaError: React.ReactNode input: RF.FieldInputProps<{}> meta: RF.FieldMetaState<{}> schema?: JsonSchema } export const MetaInput = React.forwardRef<HTMLDivElement, MetaInputProps>( function MetaInput( { className, schemaError, input: { value, onChange }, meta, schema }, ref, ) { const classes = useMetaInputStyles() const errors: ValidationErrors = schemaError || ((meta.modified || meta.submitFailed) && meta.error) const disabled = meta.submitting || meta.submitSucceeded const [open, setOpen] = React.useState(false) const closeEditor = React.useCallback(() => setOpen(false), [setOpen]) const openEditor = React.useCallback(() => setOpen(true), [setOpen]) const onChangeFullscreen = React.useCallback( (json: JsonRecord) => { setJsonInlineEditorKey(R.inc) onChange(json) }, [onChange], ) const onChangeInline = React.useCallback( (json: JsonRecord) => { setJsonFullscreenEditorKey(R.inc) onChange(json) }, [onChange], ) const { push: notify } = Notifications.use() const [locked, setLocked] = React.useState(false) // used to force json editor re-initialization const [jsonInlineEditorKey, setJsonInlineEditorKey] = React.useState(1) const [jsonFullscreenEditorKey, setJsonFullscreenEditorKey] = React.useState(1) const onDrop = React.useCallback( ([file]) => { if (file.size > MAX_META_FILE_SIZE) { notify( <> File too large ({readableBytes(file.size)}), must be under{' '} {readableBytes(MAX_META_FILE_SIZE)}. </>, ) return } setLocked(true) readFile(file, schema) .then((contents: string | {}) => { if (R.is(Object, contents)) { onChange(contents) } else { try { JSON.parse(contents as string) } catch (e) { notify('The file does not contain valid JSON') } // FIXME: show error } // force json editor to re-initialize setJsonInlineEditorKey(R.inc) setJsonFullscreenEditorKey(R.inc) }) .catch((e) => { if (e.message === 'abort') return // eslint-disable-next-line no-console console.log('Error reading file') // eslint-disable-next-line no-console console.error(e) notify("Couldn't read that file") }) .finally(() => { setLocked(false) }) }, [ schema, setLocked, onChange, setJsonInlineEditorKey, setJsonFullscreenEditorKey, notify, ], ) const isDragging = useDragging() const { getRootProps, isDragActive } = useDropzone({ onDrop }) return ( <div className={className}> <div className={classes.header}> {/* eslint-disable-next-line no-nested-ternary */} <M.Typography color={disabled ? 'textSecondary' : errors ? 'error' : undefined}> Metadata </M.Typography> <M.Button className={classes.jsonTrigger} disabled={disabled} onClick={openEditor} size="small" title="Expand JSON editor" variant="outlined" endIcon={ <M.Icon fontSize="inherit" color="primary"> fullscreen </M.Icon> } > Expand </M.Button> </div> <Dialog schema={schema} key={jsonFullscreenEditorKey} onChange={onChangeFullscreen} onClose={closeEditor} open={open} value={value} /> <div {...getRootProps({ className: classes.dropzone })} tabIndex={undefined}> <div className={classes.metaContent} ref={ref}> {isDragging && <div className={classes.outlined} />} <div className={classes.json}> <JsonEditor disabled={disabled} errors={errors} key={jsonInlineEditorKey} onChange={onChangeInline} schema={schema} value={value} /> </div> <JsonValidationErrors className={classes.errors} error={errors} /> </div> {locked && ( <div className={classes.overlay}> <Delay ms={500} alwaysRender> {(ready) => ( <M.Fade in={ready}> <div className={classes.overlayContents}> <M.CircularProgress size={20} className={classes.overlayProgress} /> <div className={classes.overlayText}>Reading file contents</div> </div> </M.Fade> )} </Delay> </div> )} {isDragging && ( <div className={cx(classes.overlay, classes.overlayDraggable, { [classes.overlayDragActive]: isDragActive, })} > <div className={classes.overlayContents}> <div className={classes.overlayText}> Drop metadata file (XLSX, CSV, JSON) </div> </div> </div> )} </div> </div> ) }, )
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * A connection allows BigQuery connections to external data sources.. * * To get more information about Connection, see: * * * [API documentation](https://cloud.google.com/bigquery/docs/reference/bigqueryconnection/rest/v1beta1/projects.locations.connections/create) * * How-to Guides * * [Cloud SQL federated queries](https://cloud.google.com/bigquery/docs/cloud-sql-federated-queries) * * > **Warning:** All arguments including `cloud_sql.credential.password` will be stored in the raw * state as plain-text. [Read more about sensitive data in state](https://www.terraform.io/docs/state/sensitive-data.html). * * ## Example Usage * ### Bigquery Connection Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * import * as random from "@pulumi/random"; * * const instance = new gcp.sql.DatabaseInstance("instance", { * databaseVersion: "POSTGRES_11", * region: "us-central1", * settings: { * tier: "db-f1-micro", * }, * deletionProtection: "true", * }, { * provider: google_beta, * }); * const db = new gcp.sql.Database("db", {instance: instance.name}, { * provider: google_beta, * }); * const pwd = new random.RandomPassword("pwd", { * length: 16, * special: false, * }); * const user = new gcp.sql.User("user", { * instance: instance.name, * password: pwd.result, * }, { * provider: google_beta, * }); * const connection = new gcp.bigquery.Connection("connection", { * friendlyName: "👋", * description: "a riveting description", * cloudSql: { * instanceId: instance.connectionName, * database: db.name, * type: "POSTGRES", * credential: { * username: user.name, * password: user.password, * }, * }, * }, { * provider: google_beta, * }); * ``` * ### Bigquery Connection Full * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * import * as random from "@pulumi/random"; * * const instance = new gcp.sql.DatabaseInstance("instance", { * databaseVersion: "POSTGRES_11", * region: "us-central1", * settings: { * tier: "db-f1-micro", * }, * deletionProtection: "true", * }, { * provider: google_beta, * }); * const db = new gcp.sql.Database("db", {instance: instance.name}, { * provider: google_beta, * }); * const pwd = new random.RandomPassword("pwd", { * length: 16, * special: false, * }); * const user = new gcp.sql.User("user", { * instance: instance.name, * password: pwd.result, * }, { * provider: google_beta, * }); * const connection = new gcp.bigquery.Connection("connection", { * connectionId: "my-connection", * location: "US", * friendlyName: "👋", * description: "a riveting description", * cloudSql: { * instanceId: instance.connectionName, * database: db.name, * type: "POSTGRES", * credential: { * username: user.name, * password: user.password, * }, * }, * }, { * provider: google_beta, * }); * ``` * * ## Import * * Connection can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:bigquery/connection:Connection default projects/{{project}}/locations/{{location}}/connections/{{connection_id}} * ``` * * ```sh * $ pulumi import gcp:bigquery/connection:Connection default {{project}}/{{location}}/{{connection_id}} * ``` * * ```sh * $ pulumi import gcp:bigquery/connection:Connection default {{location}}/{{connection_id}} * ``` */ export class Connection extends pulumi.CustomResource { /** * Get an existing Connection resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ConnectionState, opts?: pulumi.CustomResourceOptions): Connection { return new Connection(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:bigquery/connection:Connection'; /** * Returns true if the given object is an instance of Connection. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Connection { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Connection.__pulumiType; } /** * Cloud SQL properties. * Structure is documented below. */ public readonly cloudSql!: pulumi.Output<outputs.bigquery.ConnectionCloudSql>; /** * Optional connection id that should be assigned to the created connection. */ public readonly connectionId!: pulumi.Output<string>; /** * A descriptive description for the connection */ public readonly description!: pulumi.Output<string | undefined>; /** * A descriptive name for the connection */ public readonly friendlyName!: pulumi.Output<string | undefined>; /** * True if the connection has credential assigned. */ public /*out*/ readonly hasCredential!: pulumi.Output<boolean>; /** * The geographic location where the connection should reside. * Cloud SQL instance must be in the same location as the connection * with following exceptions: Cloud SQL us-central1 maps to BigQuery US, Cloud SQL europe-west1 maps to BigQuery EU. * Examples: US, EU, asia-northeast1, us-central1, europe-west1. The default value is US. */ public readonly location!: pulumi.Output<string | undefined>; /** * The resource name of the connection in the form of: * "projects/{project_id}/locations/{location_id}/connections/{connectionId}" */ public /*out*/ readonly name!: pulumi.Output<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * Create a Connection resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: ConnectionArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ConnectionArgs | ConnectionState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ConnectionState | undefined; inputs["cloudSql"] = state ? state.cloudSql : undefined; inputs["connectionId"] = state ? state.connectionId : undefined; inputs["description"] = state ? state.description : undefined; inputs["friendlyName"] = state ? state.friendlyName : undefined; inputs["hasCredential"] = state ? state.hasCredential : undefined; inputs["location"] = state ? state.location : undefined; inputs["name"] = state ? state.name : undefined; inputs["project"] = state ? state.project : undefined; } else { const args = argsOrState as ConnectionArgs | undefined; if ((!args || args.cloudSql === undefined) && !opts.urn) { throw new Error("Missing required property 'cloudSql'"); } inputs["cloudSql"] = args ? args.cloudSql : undefined; inputs["connectionId"] = args ? args.connectionId : undefined; inputs["description"] = args ? args.description : undefined; inputs["friendlyName"] = args ? args.friendlyName : undefined; inputs["location"] = args ? args.location : undefined; inputs["project"] = args ? args.project : undefined; inputs["hasCredential"] = undefined /*out*/; inputs["name"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Connection.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Connection resources. */ export interface ConnectionState { /** * Cloud SQL properties. * Structure is documented below. */ cloudSql?: pulumi.Input<inputs.bigquery.ConnectionCloudSql>; /** * Optional connection id that should be assigned to the created connection. */ connectionId?: pulumi.Input<string>; /** * A descriptive description for the connection */ description?: pulumi.Input<string>; /** * A descriptive name for the connection */ friendlyName?: pulumi.Input<string>; /** * True if the connection has credential assigned. */ hasCredential?: pulumi.Input<boolean>; /** * The geographic location where the connection should reside. * Cloud SQL instance must be in the same location as the connection * with following exceptions: Cloud SQL us-central1 maps to BigQuery US, Cloud SQL europe-west1 maps to BigQuery EU. * Examples: US, EU, asia-northeast1, us-central1, europe-west1. The default value is US. */ location?: pulumi.Input<string>; /** * The resource name of the connection in the form of: * "projects/{project_id}/locations/{location_id}/connections/{connectionId}" */ name?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; } /** * The set of arguments for constructing a Connection resource. */ export interface ConnectionArgs { /** * Cloud SQL properties. * Structure is documented below. */ cloudSql: pulumi.Input<inputs.bigquery.ConnectionCloudSql>; /** * Optional connection id that should be assigned to the created connection. */ connectionId?: pulumi.Input<string>; /** * A descriptive description for the connection */ description?: pulumi.Input<string>; /** * A descriptive name for the connection */ friendlyName?: pulumi.Input<string>; /** * The geographic location where the connection should reside. * Cloud SQL instance must be in the same location as the connection * with following exceptions: Cloud SQL us-central1 maps to BigQuery US, Cloud SQL europe-west1 maps to BigQuery EU. * Examples: US, EU, asia-northeast1, us-central1, europe-west1. The default value is US. */ location?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; }
the_stack
import { Context } from '@nuxt/types'; import { Inject } from '@nuxt/types/app'; import { AxiosError } from 'axios'; import filesize from 'filesize'; // TODO fix it complaining about no type declaration file // @ts-ignore // import { contrastRatio, HexToRGBA, parseHex } from 'vuetify/es5/util/colorUtils'; // TODO remove or fix import { HangarApiException, HangarValidationException, MultiHangarApiException } from 'hangar-api'; import { HangarProject, HangarUser } from 'hangar-internal'; import { TranslateResult } from 'vue-i18n'; import { NamedPermission, Visibility } from '~/types/enums'; import { RootState } from '~/store'; import { NotifPayload } from '~/store/snackbar'; import { AuthState } from '~/store/auth'; // for page request errors function handleRequestError(err: AxiosError, error: Context['error'], i18n: Context['app']['i18n']) { if (!err.isAxiosError) { // everything should be an AxiosError error({ statusCode: 500, }); console.log(err); } else if (err.response) { if (err.response.data.isHangarApiException) { const data: HangarApiException = err.response.data.isMultiException ? err.response.data.exceptions[0] : err.response.data; error({ statusCode: data.httpError.statusCode, message: i18n.te(data.message) ? <string>i18n.t(data.message) : data.message, }); } else if (err.response.data.isHangarValidationException) { const data: HangarValidationException = err.response.data; error({ statusCode: data.httpError.statusCode, message: data.fieldErrors.map((f) => f.errorMsg).join(', '), }); } else { error({ statusCode: err.response.status, message: err.response.statusText, }); } } else { error({ message: "This shouldn't happen...", }); console.log(err); } } function collectErrors(exception: HangarApiException | MultiHangarApiException, i18n: Context['app']['i18n']): TranslateResult[] { if (!exception.isMultiException) { return [i18n.te(exception.message) ? i18n.t(exception.message, [exception.messageArgs]) : exception.message]; } else { const res: TranslateResult[] = []; for (const ex of exception.exceptions) { res.push(i18n.te(ex.message) ? i18n.t(ex.message, ex.messageArgs) : ex.message); } return res; } } const createUtil = ({ store, error, app: { i18n } }: Context) => { class Util { dummyUser(): HangarUser { return { name: 'Dummy', id: 42, tagline: null, createdAt: this.prettyDate(new Date()), roles: [], headerData: { globalPermission: '', unreadNotifications: 1, projectApprovals: 3, reviewQueueCount: 0, unresolvedFlags: 2, }, joinDate: this.prettyDate(new Date()), } as unknown as HangarUser; } dummyProject(): HangarProject { return { namespace: { owner: 'test', slug: 'test2' }, visibility: Visibility.NEW } as unknown as HangarProject; } avatarUrl(name: string): string { return `/avatar/${name}?size=120x120`; } projectUrl(owner: string, slug: string): string { return `/api/internal/projects/project/${owner}/${slug}/icon`; } forumUrl(name: string): string { return 'https://papermc.io/forums/u/' + name; } prettyDate(date: Date | string | number): string { if (typeof date === 'string' || typeof date === 'number') { date = new Date(date); } return date.toLocaleDateString(undefined, { day: 'numeric', month: 'long', year: 'numeric', }); } prettyDateTime(date: Date | string | number): string { if (typeof date === 'string' || typeof date === 'number') { date = new Date(date); } return date.toLocaleDateString(undefined, { day: 'numeric', month: '2-digit', year: 'numeric', hour: 'numeric', minute: 'numeric', }); } /** * Requires yyyy-MM-DD format * @param dateString */ fromISOString(dateString: string): Date { const ds = dateString.split('-').map((s) => parseInt(s)); return new Date(ds[0], ds[1] - 1, ds[2]); } toISODateString(date: Date): string { return `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${('0' + date.getDate()).slice(-2)}`; } formatSize(input: any) { return filesize(input); } // TODO either fix or remove this // white = HexToRGBA(parseHex('#ffffff')); // black = HexToRGBA(parseHex('#000000')); isDark(hex: string): boolean { // const rgba = HexToRGBA(parseHex(hex)); // return contrastRatio(rgba, this.white) > 2; return hex === null; } isLight(hex: string): boolean { // const rgba = HexToRGBA(parseHex(hex)); // return contrastRatio(rgba, this.black) > 2; return hex === null; } /** * Checks if the supplier permission has all named permissions. * @param namedPermission perms required */ hasPerms(...namedPermission: NamedPermission[]): boolean { const perms = (store.state.auth as AuthState).routePermissions; if (!perms) return false; const _perms: bigint = BigInt('0b' + perms); let result = true; for (const np of namedPermission) { const perm = (store.state as RootState).permissions.get(np); if (!perm) { throw new Error(namedPermission + ' is not valid'); } const val = BigInt('0b' + perm.permission.toString(2)); result = result && (_perms & val) === val; } return result; } isCurrentUser(id: number): boolean { return (store.state.auth as AuthState).user?.id === id; } /** * Used when an auth error should redirect to 404 * @param err the axios request error */ handlePageRequestError(err: AxiosError) { handleRequestError(err, error, i18n); } /** * Used for showing error popups. See handlePageRequestError to show an error page. * @param err the axios request error * @param msg optional error message (should be i18n) */ handleRequestError(err: AxiosError, msg: string | undefined = undefined) { if (process.server) { handleRequestError(err, error, i18n); return; } if (!err.isAxiosError) { // everything should be an AxiosError error({ statusCode: 500, }); console.log(err); } else if (err.response) { if (err.response.data.isHangarApiException) { for (const errorMsg of collectErrors(err.response.data, i18n)) { store.dispatch('snackbar/SHOW_NOTIF', { message: msg ? `${i18n.t(msg)}: ${errorMsg}` : errorMsg, color: 'error', timeout: 3000, } as NotifPayload); } } else if (err.response.data.isHangarValidationException) { const data: HangarValidationException = err.response.data; for (const fieldError of data.fieldErrors) { store.dispatch('snackbar/SHOW_NOTIF', { message: fieldError.errorMsg, color: 'error', timeout: 3000, } as NotifPayload); } if (msg) { store.dispatch('snackbar/SHOW_NOTIF', { message: i18n.t(msg), color: 'error', timeout: 3000, } as NotifPayload); } } else { store.dispatch('snackbar/SHOW_NOTIF', { message: msg ? `${i18n.t(msg)}: ${err.response.statusText}` : err.response.statusText, color: 'error', timeout: 2000, } as NotifPayload); } } else { console.log(err); } } $vc = { required: (name: TranslateResult = 'Field') => (v: string) => !!v || i18n.t('validation.required', [name]), maxLength: (maxLength: number) => (v: string | any[]) => { return ( ((v === null || typeof v === 'undefined' || typeof v === 'string') && !v) || (Array.isArray(v) && v.length === 0) || v.length <= maxLength || i18n.t('validation.maxLength', [maxLength]) ); }, minLength: (minLength: number) => (v: string | any[]) => { return ( ((v === null || typeof v === 'string') && !v) || (Array.isArray(v) && v.length === 0) || v.length >= minLength || i18n.t('validation.minLength', [minLength]) ); }, requireNonEmptyArray: (name: TranslateResult = 'Field') => (v: any[]) => v.length > 0 || i18n.t('validation.required', [name]), url: (v: string) => !v || new RegExp((store.state as RootState).validations.urlRegex).test(v) || i18n.t('validation.invalidUrl'), regex: (name: TranslateResult = 'Field', regexp: string) => (v: string) => { return !v || new RegExp(regexp).test(v) || i18n.t('validation.invalidFormat', [name]); }, requireNumberArray: () => (v: string | any[]) => { return ( ((v === null || typeof v === 'undefined' || typeof v === 'string') && !v) || (Array.isArray(v) && v.length === 0) || (v as any[]).some((i) => !isNaN(i)) || i18n.t('validation.numberArray') ); }, }; error(err: TranslateResult | NotifPayload) { if (typeof err === 'string') { store.dispatch('snackbar/SHOW_NOTIF', { message: err, color: 'error' } as NotifPayload); } else { store.dispatch('snackbar/SHOW_NOTIF', err); } } success(msg: TranslateResult) { store.dispatch('snackbar/SHOW_NOTIF', { message: msg, color: 'success' } as NotifPayload); } } return new Util(); }; type utilType = ReturnType<typeof createUtil>; declare module 'vue/types/vue' { interface Vue { $util: utilType; } } declare module '@nuxt/types' { interface NuxtAppOptions { $util: utilType; } interface Context { $util: utilType; } } declare module 'vuex/types/index' { // eslint-disable-next-line no-unused-vars,@typescript-eslint/no-unused-vars interface Store<S> { $util: utilType; } } export default (ctx: Context, inject: Inject) => { inject('util', createUtil(ctx)); };
the_stack
import * as t from 'io-ts'; import { RTTI_id } from '../Scalar/RTTI_id'; import { RTTI_Meta, IMeta } from './RTTI_Meta'; import { RTTI_uri } from '../Scalar/RTTI_uri'; import { RTTI_Element, IElement } from './RTTI_Element'; import { RTTI_code } from '../Scalar/RTTI_code'; import { RTTI_Narrative, INarrative } from './RTTI_Narrative'; import { RTTI_ResourceList, IResourceList } from '../Union/RTTI_ResourceList'; import { RTTI_Extension, IExtension } from './RTTI_Extension'; import { RTTI_Identifier, IIdentifier } from './RTTI_Identifier'; import { RTTI_Reference, IReference } from './RTTI_Reference'; import { RTTI_CodeableConcept, ICodeableConcept } from './RTTI_CodeableConcept'; import { RTTI_Period, IPeriod } from './RTTI_Period'; import { RTTI_Timing, ITiming } from './RTTI_Timing'; import { RTTI_instant } from '../Scalar/RTTI_instant'; import { RTTI_Quantity, IQuantity } from './RTTI_Quantity'; import { RTTI_Range, IRange } from './RTTI_Range'; import { RTTI_Ratio, IRatio } from './RTTI_Ratio'; import { RTTI_SampledData, ISampledData } from './RTTI_SampledData'; import { RTTI_Annotation, IAnnotation } from './RTTI_Annotation'; import { RTTI_Observation_ReferenceRange, IObservation_ReferenceRange } from './RTTI_Observation_ReferenceRange'; import { RTTI_Observation_Component, IObservation_Component } from './RTTI_Observation_Component'; export enum ObservationStatusKind { _registered = 'registered', _preliminary = 'preliminary', _final = 'final', _amended = 'amended', _corrected = 'corrected', _cancelled = 'cancelled', _enteredInError = 'entered-in-error', _unknown = 'unknown' } import { createEnumType } from '../../EnumType'; import { IDomainResource } from './IDomainResource'; export interface IObservation extends IDomainResource { /** * This is a Observation resource */ resourceType: 'Observation'; /** * Describes what was observed. Sometimes this is called the observation "name". */ code: ICodeableConcept; /** * The logical id of the resource, as used in the URL for the resource. Once assigned, this value never changes. */ id?: string; /** * The metadata about the resource. This is content that is maintained by the infrastructure. Changes to the content might not always be associated with version changes to the resource. */ meta?: IMeta; /** * A reference to a set of rules that were followed when the resource was constructed, and which must be understood when processing the content. Often, this is a reference to an implementation guide that defines the special rules along with other profiles etc. */ implicitRules?: string; /** * Extensions for implicitRules */ _implicitRules?: IElement; /** * The base language in which the resource is written. */ language?: string; /** * Extensions for language */ _language?: IElement; /** * A human-readable narrative that contains a summary of the resource and can be used to represent the content of the resource to a human. The narrative need not encode all the structured data, but is required to contain sufficient detail to make it "clinically safe" for a human to just read the narrative. Resource definitions may define what content should be represented in the narrative to ensure clinical safety. */ text?: INarrative; /** * These resources do not have an independent existence apart from the resource that contains them - they cannot be identified independently, and nor can they have their own independent transaction scope. */ contained?: IResourceList[]; /** * May be used to represent additional information that is not part of the basic definition of the resource. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. */ extension?: IExtension[]; /** * May be used to represent additional information that is not part of the basic definition of the resource and that modifies the understanding of the element that contains it and/or the understanding of the containing element's descendants. Usually modifier elements provide negation or qualification. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions. Modifier extensions SHALL NOT change the meaning of any elements on Resource or DomainResource (including cannot change the meaning of modifierExtension itself). */ modifierExtension?: IExtension[]; /** * A unique identifier assigned to this observation. */ identifier?: IIdentifier[]; /** * A plan, proposal or order that is fulfilled in whole or in part by this event. For example, a MedicationRequest may require a patient to have laboratory test performed before it is dispensed. */ basedOn?: IReference[]; /** * A larger event of which this particular Observation is a component or step. For example, an observation as part of a procedure. */ partOf?: IReference[]; /** * The status of the result value. */ status?: ObservationStatusKind; /** * Extensions for status */ _status?: IElement; /** * A code that classifies the general type of observation being made. */ category?: ICodeableConcept[]; /** * The patient, or group of patients, location, or device this observation is about and into whose record the observation is placed. If the actual focus of the observation is different from the subject (or a sample of, part, or region of the subject), the `focus` element or the `code` itself specifies the actual focus of the observation. */ subject?: IReference; /** * The actual focus of an observation when it is not the patient of record representing something or someone associated with the patient such as a spouse, parent, fetus, or donor. For example, fetus observations in a mother's record. The focus of an observation could also be an existing condition, an intervention, the subject's diet, another observation of the subject, or a body structure such as tumor or implanted device. An example use case would be using the Observation resource to capture whether the mother is trained to change her child's tracheostomy tube. In this example, the child is the patient of record and the mother is the focus. */ focus?: IReference[]; /** * The healthcare event (e.g. a patient and healthcare provider interaction) during which this observation is made. */ encounter?: IReference; /** * The time or time-period the observed value is asserted as being true. For biological subjects - e.g. human patients - this is usually called the "physiologically relevant time". This is usually either the time of the procedure or of specimen collection, but very often the source of the date/time is not known, only the date/time itself. */ effectiveDateTime?: string; /** * Extensions for effectiveDateTime */ _effectiveDateTime?: IElement; /** * The time or time-period the observed value is asserted as being true. For biological subjects - e.g. human patients - this is usually called the "physiologically relevant time". This is usually either the time of the procedure or of specimen collection, but very often the source of the date/time is not known, only the date/time itself. */ effectivePeriod?: IPeriod; /** * The time or time-period the observed value is asserted as being true. For biological subjects - e.g. human patients - this is usually called the "physiologically relevant time". This is usually either the time of the procedure or of specimen collection, but very often the source of the date/time is not known, only the date/time itself. */ effectiveTiming?: ITiming; /** * The time or time-period the observed value is asserted as being true. For biological subjects - e.g. human patients - this is usually called the "physiologically relevant time". This is usually either the time of the procedure or of specimen collection, but very often the source of the date/time is not known, only the date/time itself. */ effectiveInstant?: string; /** * Extensions for effectiveInstant */ _effectiveInstant?: IElement; /** * The date and time this version of the observation was made available to providers, typically after the results have been reviewed and verified. */ issued?: string; /** * Extensions for issued */ _issued?: IElement; /** * Who was responsible for asserting the observed value as "true". */ performer?: IReference[]; /** * The information determined as a result of making the observation, if the information has a simple value. */ valueQuantity?: IQuantity; /** * The information determined as a result of making the observation, if the information has a simple value. */ valueCodeableConcept?: ICodeableConcept; /** * The information determined as a result of making the observation, if the information has a simple value. */ valueString?: string; /** * Extensions for valueString */ _valueString?: IElement; /** * The information determined as a result of making the observation, if the information has a simple value. */ valueBoolean?: boolean; /** * Extensions for valueBoolean */ _valueBoolean?: IElement; /** * The information determined as a result of making the observation, if the information has a simple value. */ valueInteger?: number; /** * Extensions for valueInteger */ _valueInteger?: IElement; /** * The information determined as a result of making the observation, if the information has a simple value. */ valueRange?: IRange; /** * The information determined as a result of making the observation, if the information has a simple value. */ valueRatio?: IRatio; /** * The information determined as a result of making the observation, if the information has a simple value. */ valueSampledData?: ISampledData; /** * The information determined as a result of making the observation, if the information has a simple value. */ valueTime?: string; /** * Extensions for valueTime */ _valueTime?: IElement; /** * The information determined as a result of making the observation, if the information has a simple value. */ valueDateTime?: string; /** * Extensions for valueDateTime */ _valueDateTime?: IElement; /** * The information determined as a result of making the observation, if the information has a simple value. */ valuePeriod?: IPeriod; /** * Provides a reason why the expected value in the element Observation.value[x] is missing. */ dataAbsentReason?: ICodeableConcept; /** * A categorical assessment of an observation value. For example, high, low, normal. */ interpretation?: ICodeableConcept[]; /** * Comments about the observation or the results. */ note?: IAnnotation[]; /** * Indicates the site on the subject's body where the observation was made (i.e. the target site). */ bodySite?: ICodeableConcept; /** * Indicates the mechanism used to perform the observation. */ method?: ICodeableConcept; /** * The specimen that was used when this observation was made. */ specimen?: IReference; /** * The device used to generate the observation data. */ device?: IReference; /** * Guidance on how to interpret the value by comparison to a normal or recommended range. Multiple reference ranges are interpreted as an "OR". In other words, to represent two distinct target populations, two `referenceRange` elements would be used. */ referenceRange?: IObservation_ReferenceRange[]; /** * This observation is a group observation (e.g. a battery, a panel of tests, a set of vital sign measurements) that includes the target as a member of the group. */ hasMember?: IReference[]; /** * The target resource that represents a measurement from which this observation value is derived. For example, a calculated anion gap or a fetal measurement based on an ultrasound image. */ derivedFrom?: IReference[]; /** * Some observations have multiple component observations. These component observations are expressed as separate code value pairs that share the same attributes. Examples include systolic and diastolic component observations for blood pressure measurement and multiple component observations for genetics observations. */ component?: IObservation_Component[]; } export const RTTI_Observation: t.Type<IObservation> = t.recursion( 'IObservation', () => t.intersection([ t.type({ resourceType: t.literal('Observation'), code: RTTI_CodeableConcept }), t.partial({ id: RTTI_id, meta: RTTI_Meta, implicitRules: RTTI_uri, _implicitRules: RTTI_Element, language: RTTI_code, _language: RTTI_Element, text: RTTI_Narrative, contained: t.array(RTTI_ResourceList), extension: t.array(RTTI_Extension), modifierExtension: t.array(RTTI_Extension), identifier: t.array(RTTI_Identifier), basedOn: t.array(RTTI_Reference), partOf: t.array(RTTI_Reference), status: createEnumType<ObservationStatusKind>( ObservationStatusKind, 'ObservationStatusKind' ), _status: RTTI_Element, category: t.array(RTTI_CodeableConcept), subject: RTTI_Reference, focus: t.array(RTTI_Reference), encounter: RTTI_Reference, effectiveDateTime: t.string, _effectiveDateTime: RTTI_Element, effectivePeriod: RTTI_Period, effectiveTiming: RTTI_Timing, effectiveInstant: t.string, _effectiveInstant: RTTI_Element, issued: RTTI_instant, _issued: RTTI_Element, performer: t.array(RTTI_Reference), valueQuantity: RTTI_Quantity, valueCodeableConcept: RTTI_CodeableConcept, valueString: t.string, _valueString: RTTI_Element, valueBoolean: t.boolean, _valueBoolean: RTTI_Element, valueInteger: t.number, _valueInteger: RTTI_Element, valueRange: RTTI_Range, valueRatio: RTTI_Ratio, valueSampledData: RTTI_SampledData, valueTime: t.string, _valueTime: RTTI_Element, valueDateTime: t.string, _valueDateTime: RTTI_Element, valuePeriod: RTTI_Period, dataAbsentReason: RTTI_CodeableConcept, interpretation: t.array(RTTI_CodeableConcept), note: t.array(RTTI_Annotation), bodySite: RTTI_CodeableConcept, method: RTTI_CodeableConcept, specimen: RTTI_Reference, device: RTTI_Reference, referenceRange: t.array(RTTI_Observation_ReferenceRange), hasMember: t.array(RTTI_Reference), derivedFrom: t.array(RTTI_Reference), component: t.array(RTTI_Observation_Component) }) ]) );
the_stack
import { ColorInput } from '@ctrl/tinycolor'; import { ColorObject, ColorScheme, VariableColor, VariantsObject, VariantInput, ColorVariant, OpacityVariant, VariantTransformer, CustomVariant, Variant, VariantType, } from './color'; import { flattenColorObject } from '../util/flattenColorObject'; import { isMappedVariant } from '../util/isMappedVariant'; import { VariableInput, Variable } from './variable'; import { generateTailwindConfiguration } from '../util/generateTailwindConfiguration'; import { generateCssConfiguration } from '../util/generateCssConfiguration'; import { Strategy } from './strategy'; import _ from 'lodash'; import { isColorInput } from '../util/isColorInput'; /** * The plugin's theme builder. It is an object that contains the * configured themes for the application, as well as other settings needed * to generate anything the user wants to be customized. */ export class ThemeManager { private _themes: Theme[]; private _strategy?: Strategy; private _prefix?: string; /** * Creates a theme manager. */ constructor() { this._themes = []; } /* |-------------------------------------------------------------------------- | Default Theme Setters |-------------------------------------------------------------------------- */ /** * Defines the default theme for every color scheme. */ setDefaultTheme(theme: Theme): this { theme = _.cloneDeep(theme); // We can't have more than one default theme. if (this.getDefaultTheme()) { throw new Error('Tried to set a default theme, but there was already one.'); } // The default theme has no color scheme. this._themes.push(theme.setDefault().setColorScheme(ColorScheme.Undefined)); return this; } setDefaultLightTheme(theme: Theme): this { theme = _.cloneDeep(theme); // We can't have more than one default light theme. if (this.getDefaultLightTheme()) { throw new Error('Tried to set a default light theme, but there was already one.'); } this._themes.push(theme.setDefault().setColorScheme(ColorScheme.Light)); return this; } setDefaultDarkTheme(theme: Theme): this { theme = _.cloneDeep(theme); // We can't have more than one default dark theme. if (this.getDefaultDarkTheme()) { throw new Error('Tried to set a default dark theme, but there was already one.'); } this._themes.push(theme.setDefault().setColorScheme(ColorScheme.Dark)); return this; } /* |-------------------------------------------------------------------------- | Other Theme Adders |-------------------------------------------------------------------------- */ /** * Add a theme. */ addTheme(theme: Theme): this { theme = _.cloneDeep(theme); this._themes.push(theme); return this; } /** * Add a light theme. */ addLightTheme(theme: Theme): this { theme = _.cloneDeep(theme); return this.addTheme(theme.setColorScheme(ColorScheme.Light)); } /** * Add a dark theme. */ addDarkTheme(theme: Theme): this { theme = _.cloneDeep(theme); return this.addTheme(theme.setColorScheme(ColorScheme.Dark)); } /* |-------------------------------------------------------------------------- | Theme getters. |-------------------------------------------------------------------------- */ /** * Gets every themes. */ getAllThemes(): Theme[] { return this._themes; } /** * Get every theme, except the default one. */ getThemes(): Theme[] { return this.getThemesFor(ColorScheme.Undefined); } /** * Get light-schemed themes, except the default one. */ getLightThemes(): Theme[] { return this.getThemesFor(ColorScheme.Light); } /** * Get dark-schemed themes, except the default one. */ getDarkThemes(): Theme[] { return this.getThemesFor(ColorScheme.Dark); } /** * Gets the default theme. */ getDefaultTheme(): Theme | undefined { return this.getDefaultThemeFor(ColorScheme.Undefined); } /** * Gets the default light theme. */ getDefaultLightTheme(): Theme | undefined { return this.getDefaultThemeFor(ColorScheme.Light); } /** * Gets the default dark theme. */ getDefaultDarkTheme(): Theme | undefined { return this.getDefaultThemeFor(ColorScheme.Dark); } /** * Gets the default theme for the given scheme. */ private getDefaultThemeFor(scheme: ColorScheme): Theme | undefined { return this._themes.find( (theme) => theme.isDefault() && scheme === theme.getColorScheme() ); } /** * Gets all themes for the given scheme, except the default one. */ private getThemesFor(scheme: ColorScheme): Theme[] { return this._themes.filter( (theme) => !theme.isDefault() && scheme === theme.getColorScheme() ); } /* |-------------------------------------------------------------------------- | Strategy-related |-------------------------------------------------------------------------- */ /** * Defines the prefix used for the strategy. */ setPrefix(prefix: string): this { this._prefix = prefix; return this; } /** * Gets the prefix used for the strategy. */ getPrefix(): string | undefined { return this._prefix; } /** * Defines the strategy used for theme selection. */ setStrategy(strategy: Strategy): this { this._strategy = strategy; return this; } /** * Gets the strategy used for theme selection. */ getStrategy(): Strategy | undefined { return this._strategy; } /* |-------------------------------------------------------------------------- | Strategies |-------------------------------------------------------------------------- */ /** * Each theme will be exported as a `data-theme` attribute. * You will be able to use a theme by setting the attribute `data-theme` with the value `<themeName>` on a node. * The CSS rule will be `[data-theme=<themeName>]`. */ asDataThemeAttributes(): this { this.setStrategy(Strategy.DataThemeAttribute); return this; } /** * Each theme will be exported as a data attribute. * You will be able to use a theme by setting the attribute `data-<themeName>` on a node. The CSS rule will be `[data-<themeName>]`. */ asDataAttributes(): this { this.setStrategy(Strategy.DataAttribute); return this; } /** * Each theme will be exported in a class. * You will be able to use a theme by applying the class `.<themeName>` on a node. The CSS rule will be `.<themeName>`. */ asClasses(): this { this.setStrategy(Strategy.Class); return this; } /** * Each theme will be exported as an attribute with a prefix. * You will be able to use a theme by setting the attribute `<choosenPrefix>-<themeName>` on a node. * The CSS rule will be `[<choosenPrefix>-<themeName>]`. */ asPrefixedAttributes(prefix: string = 'theme'): this { this.setStrategy(Strategy.PrefixedAttribute); this.setPrefix(prefix); return this; } /** * Each theme will be exported in a class with a prefix. * You will be able to use a theme by applying the class `.<choosenPrefix>-<themeName>` on a node. * The CSS rule will be `.<choosenPrefix>-<themeName>`. */ asPrefixedClasses(prefix: string = 'theme'): this { this.setStrategy(Strategy.PrefixedClass); this.setPrefix(prefix); return this; } /* |-------------------------------------------------------------------------- | Plugin |-------------------------------------------------------------------------- */ /** * Gets the Tailwind configuration for this theme manager. */ getTailwindConfiguration(): any { return generateTailwindConfiguration(this); } /** * Gets an object that generates the themes' CSS inside the addBase helper. */ getCssConfiguration(): any { return generateCssConfiguration(this); } } export class Theme { private _name?: string; private _default: boolean; private _colorScheme: ColorScheme; private _targetable: boolean; private _colors: VariableColor[]; private _variables: Variable[]; /** * Creates a new theme. */ constructor() { // We don't want a theme to be targetable by default. this._targetable = false; // Whether or not this theme is the default is changed by the theme // manager. This is still accessible to user-land but as an advanced // toggle. this._default = false; // By default, a theme has no specific color scheme. It's the theme // manager's responsibility to set one, even though the option is // accessible to user-land as an advanced feature. this._colorScheme = ColorScheme.Undefined; // We set the colors and variables. this._colors = []; this._variables = []; } /* |-------------------------------------------------------------------------- | Name |-------------------------------------------------------------------------- */ /** * Defines this theme's name. */ setName(name: string): this { this._name = name; return this; } /** * Gets this theme's name. */ getName(): string { return this._name ?? (this.hasScheme() ? this.getColorScheme() : 'default'); } /* |-------------------------------------------------------------------------- | Targetable |-------------------------------------------------------------------------- */ /** * Defines this theme as targetable, which means it can be selected * with a CSS selector. */ targetable(): this { this._targetable = true; return this; } /** * Defines this theme as untargetable, which means it can not be selected * with a CSS selector. */ untargetable(): this { this._targetable = false; return this; } /** * Determines if this theme is targetable. */ isTargetable(): boolean { return this._targetable; } /* |-------------------------------------------------------------------------- | Default |-------------------------------------------------------------------------- */ /** * Defines whether or not this theme is the default for * its color scheme. */ setDefault(shouldBeDefault: boolean = true): this { this._default = shouldBeDefault; return this; } /** * Determines if this theme is the default for its color * scheme. */ isDefault(): boolean { return this._default; } /* |-------------------------------------------------------------------------- | Color Schemes |-------------------------------------------------------------------------- */ /** * Defines the color scheme of this theme. */ setColorScheme(colorScheme: ColorScheme): this { this._colorScheme = colorScheme; return this; } /** * Gets the color scheme of this theme. */ getColorScheme(): ColorScheme { return this._colorScheme; } /** * Determines if the theme is for a light scheme. */ isLight(): boolean { return ColorScheme.Light === this._colorScheme; } /** * Determines if the theme is for a dark scheme. */ isDark(): boolean { return ColorScheme.Dark === this._colorScheme; } /** * Determines if the theme has no color scheme. */ hasNoScheme(): boolean { return !this.hasScheme(); } /** * Determines if the theme has a color scheme. */ hasScheme(): boolean { return ColorScheme.Undefined !== this._colorScheme; } /** * Sets this theme's color scheme to light. */ light(): this { this.setColorScheme(ColorScheme.Light); return this; } /** * Sets this theme's color scheme to dark. */ dark(): this { this.setColorScheme(ColorScheme.Dark); return this; } /* |-------------------------------------------------------------------------- | Colors |-------------------------------------------------------------------------- */ /** * Adds the given colors to the theme. * * @param colorObject An object of colors, the same format as Tailwind's, but any TinyColor value can be used. */ addColors(colorObject: ColorObject): this { const colors = flattenColorObject(colorObject); Object.entries(colors).forEach((color) => { this.color(...color); }); return this; } /** * Adds a color to the theme. * * @param name The name of the color. Will be used for class names. * @param color */ color(name: string, color: ColorInput): this { this._colors.push(new VariableColor(name, color)); return this; } /** * Gets all colors in the theme. * * @param colors A string or an array of color names to filter. */ getColors(colors?: string | string[]): VariableColor[] { if (!colors) { return this._colors; } if (!Array.isArray(colors)) { colors = [colors]; } return this._colors.filter((color) => colors?.includes(color.getName())); } /* |-------------------------------------------------------------------------- | Variants |-------------------------------------------------------------------------- */ /** * Adds the given variants. * * @param variants A variant object. */ addVariants(variants: VariantsObject): this { // Detects the type of the variant depending of its // content, and adds it const detectAndAddVariant = ( name: string, value: VariantInput, colors?: string | string[] ) => { // It's a custom one if (_.isFunction(value)) { return this.addCustomVariant(name, value, colors); } // It's an opacity one if (_.isNumber(value)) { return this.addOpacityVariant(name, value, colors); } // It's a color one if (_.isString(value)) { return this.addColorVariant(name, value, colors); } throw new Error(`Unrecoginized variant '${name}' of value '${value}'.`); }; // Loop through the variants Object.entries(variants).forEach(([name, value]) => { // If it's an object, it's mapped to some colors if (isMappedVariant(value)) { return detectAndAddVariant(name, value.variant, value.colors); } // It's a scalar value detectAndAddVariant(name, value); }); return this; } /** * Add the given color variant to a color or a list of colors. * * @param name The variant name. * @param value The variant value. * @param colorNames The color name, or list of color names. */ addColorVariant(name: string, value: ColorInput, colorNames?: string | string[]): this { return this.addVariant(new ColorVariant(name, value), colorNames); } /** * Add the given opacity variant to a color or a list of colors. * * @param name The variant name. * @param opacity The opacity value. * @param colorNames The color name, or list of color names. */ addOpacityVariant(name: string, opacity: number, colorNames?: string | string[]): this { return this.addVariant(new OpacityVariant(name, opacity), colorNames); } /** * Add the given custom variant to a color or a list of colors. * * @param name The variant name. * @param value The variant value. * @param colorNames The color name, or list of color names. */ addCustomVariant( name: string, transformer: VariantTransformer, colorNames?: string | string[] ): this { return this.addVariant(new CustomVariant(name, transformer), colorNames); } /** * Add the given variant to a color or a list of colors. * * @param name The variant name. * @param colorNames The color name, or list of color names. */ addVariant(variant: CustomVariant, colorNames?: string | string[]): this { // If no color name is used, adding to all colors. if (!colorNames) { colorNames = this._colors.map((color) => color.getName()); } if (!Array.isArray(colorNames)) { colorNames = [colorNames]; } // Running through each color name to add the variant to it. colorNames.forEach((colorName) => { const predicate = (color: VariableColor) => color.getName() === colorName; const index = this._colors.findIndex(predicate); if (-1 !== index) { this._colors[index].setVariant(variant); } else { throw new Error( `Could not find the color '${colorName}' on which to add variant '${variant.getName()}'.` ); } }); return this; } /** * Get all variants. */ getVariants(): Variant[] { return _.flatten(this._colors.map((color) => color.getVariants())); } /** * Get all color variants. */ getColorVariants(): ColorVariant[] { return _.flatten( this._colors.map((color) => color.getVariants().filter((variant) => variant.getType() === VariantType.Color) ) ) as ColorVariant[]; } /** * Get all opacity variants. */ getOpacityVariants(): ColorVariant[] { return _.flatten( this._colors.map((color) => color.getVariants().filter((variant) => variant.getType() === VariantType.Opacity) ) ) as ColorVariant[]; } /** * Get all custom variants. */ getCustomVariants(): CustomVariant[] { return _.flatten( this._colors.map((color) => color.getVariants().filter((variant) => variant.getType() === VariantType.Custom) ) ) as CustomVariant[]; } /* |-------------------------------------------------------------------------- | Variables |-------------------------------------------------------------------------- */ /** * Adds an arbitrary variable to the theme. * * @param name The name of the variable. * @param value The value of the variable. * @param path An optional path to a Tailwind configuration key. * @param prefix An optional prefix to be appended to the variable name. */ setVariable( name: string, value: VariableInput | VariableInput[], path?: string, prefix?: string ): this { this._variables.push(new Variable(name, value, path, prefix)); return this; } /** * Gets every variable. */ getVariables(): Variable[] { return this._variables; } }
the_stack
import BaseFoundation, { DefaultAdapter } from '../base/foundation'; import { format, getWeeksInMonth, getWeekOfMonth, isSameMonth, startOfMonth, endOfMonth, isBefore, isAfter, addDays, startOfWeek, differenceInCalendarDays, isSameDay, startOfDay, isSameWeek, Locale } from 'date-fns'; import { parseEvent, parseAllDayEvent, calcWeekData, getCurrDate, parseWeeklyAllDayEvent, sortDate, collectDailyEvents, round, getPos, convertEventsArrToMap, filterWeeklyEvents, renderDailyEvent, calcRangeData, filterEvents, parseRangeAllDayEvent, DateObj, checkWeekend } from './eventUtil'; export interface EventObject { [x: string]: any; key: string; allDay?: boolean; start?: Date; end?: Date; children?: React.ReactNode; } export interface ParsedEventsWithArray { day: Array<any>; allDay: Array<any>; } export interface ParsedEvents { day?: Map<string, Array<EventObject>>; allDay?: Map<string, Array<EventObject>>; } export interface ParsedRangeEvent extends EventObject { leftPos?: number; width?: number; topInd?: number; } export interface MonthlyEvent { day: ParsedRangeEvent[][]; display: ParsedRangeEvent[]; } export interface RangeData { month: string; week: any[]; } export interface WeeklyData { month: string; week: DateObj[]; } export type MonthData = Record<number, DateObj[]>; // export interface CalendarAdapter extends DefaultAdapter { // updateScrollHeight: (scrollHeight: number) => void; // setParsedEvents: (parsedEvents: ParsedEvents) => void; // cacheEventKeys: (cachedKeys: Array<string>) => void; // } export type ParsedEventsType = ParsedEvents | ParsedEventsWithArray | MonthlyEvent; export interface CalendarAdapter<P = Record<string, any>, S = Record<string, any>> extends DefaultAdapter<P, S> { updateCurrPos?: (currPos: number) => void; updateShowCurrTime?: () => void; updateScrollHeight?: (scrollHeight: number) => void; setParsedEvents?: (parsedEvents: ParsedEventsType) => void; cacheEventKeys?: (cachedKeys: Array<string>) => void; setRangeData?: (data: RangeData) => void; getRangeData?: () => RangeData; setWeeklyData?: (data: WeeklyData) => void; getWeeklyData?: () => WeeklyData; registerClickOutsideHandler?: (key: string, cb: () => void) => void; unregisterClickOutsideHandler?: () => void; setMonthlyData?: (data: MonthData) => void; getMonthlyData?: () => MonthData; notifyClose?: (e: any, key: string) => void; openCard?: (key: string, spacing: boolean) => void; setItemLimit?: (itemLimit: number) => void; } export default class CalendarFoundation<P = Record<string, any>, S = Record<string, any>> extends BaseFoundation<CalendarAdapter<P, S>, P, S> { raf: number; constructor(adapter: CalendarAdapter<P, S>) { super({ ...adapter }); } // eslint-disable-next-line @typescript-eslint/no-empty-function init() { } destroy() { this.raf && cancelAnimationFrame(this.raf); } initCurrTime() { const { showCurrTime, displayValue } = this.getProps(); if (showCurrTime && isSameDay(displayValue, getCurrDate())) { this._adapter.updateShowCurrTime(); this.getCurrLocation(); } } notifyScrollHeight(height: number) { this._adapter.updateScrollHeight(height); } closeCard(e: any, key: string) { this._adapter.unregisterClickOutsideHandler(); this._adapter.notifyClose(e, key); } _getDate() { const { displayValue } = this.getProps(); return displayValue || getCurrDate(); } showCard(e: any, key: string) { this._adapter.unregisterClickOutsideHandler(); const bodyWidth = document.querySelector('body').clientWidth; const popoverWidth = 110; const spacing = bodyWidth - e.target.getBoundingClientRect().right - popoverWidth; this._adapter.openCard(key, spacing > 0); this._adapter.registerClickOutsideHandler(key, () => { this.closeCard(null, key); }); } formatCbValue(val: [Date, number, number, number] | [Date]) { const date = val.shift() as Date; const dateArr = [date.getFullYear(), date.getMonth(), date.getDate(), ...val]; // @ts-ignore skip return new Date(...dateArr); } /** * * find the location of showCurrTime red line */ getCurrLocation() { let startTime: number = null; let pos = getPos(getCurrDate()); this._adapter.updateCurrPos(round(pos)); const frameFunc = () => { const timestamp = Date.now(); if (!startTime) { startTime = timestamp; } const time = timestamp - startTime; if (time > 30000) { pos = getPos(getCurrDate()); this._adapter.updateCurrPos(round(pos)); startTime = timestamp; } this.raf = requestAnimationFrame(frameFunc); }; this.raf = requestAnimationFrame(frameFunc); } getWeeklyData(value: Date, dateFnsLocale: Locale) { const data = {} as WeeklyData; data.month = format(value, 'LLL', { locale: dateFnsLocale }); data.week = calcWeekData(value, 'week', dateFnsLocale); this._adapter.setWeeklyData(data); return data; } getRangeData(value: Date, dateFnsLocale: Locale) { const data = {} as { month: string; week: Array<DateObj> }; const { range } = this.getProps(); const len = differenceInCalendarDays(range[1], range[0]); data.month = format(value, 'LLL', { locale: dateFnsLocale }); data.week = calcRangeData(value, range[0], len, 'week', dateFnsLocale); this._adapter.setRangeData(data); return data; } getMonthlyData(value: Date, dateFnsLocale: Locale) { const monthStart = startOfMonth(value); const data = {} as MonthData; const numberOfWeek = getWeeksInMonth(value); [...Array(numberOfWeek).keys()].map(ind => { data[ind] = calcWeekData(addDays(monthStart, ind * 7), 'month', dateFnsLocale); }); this._adapter.setMonthlyData(data); return data; } // ================== Daily Event ================== _parseEvents(events: EventObject[]) { const parsed: ParsedEventsWithArray = { allDay: [], day: [] }; events.map(event => parseEvent(event)).forEach(item => { item.forEach(i => { i.allDay ? parsed.allDay.push(i) : parsed.day.push(i); }); }); return parsed; } getParseDailyEvents(events: EventObject[], date: Date) { if (!date) { date = this._getDate(); } const parsed = this._parseEvents(events); const { displayValue } = this.getProps(); const key = startOfDay(date).toString(); parsed.allDay = convertEventsArrToMap(parsed.allDay, 'date', startOfDay, displayValue).get(key); parsed.day = convertEventsArrToMap(parsed.day, 'date', null, displayValue).get(key); if (!parsed.allDay) { parsed.allDay = []; } if (!parsed.day) { parsed.day = []; } parsed.day = parsed.day.map(item => renderDailyEvent(item)); return parsed; } parseDailyEvents() { const { events, displayValue } = this.getProps(); const parsed = this.getParseDailyEvents(events, displayValue); this._adapter.setParsedEvents(parsed); this._adapter.cacheEventKeys((events as EventObject[]).map(i => i.key)); } // ================== Weekly Event ================== _parseWeeklyEvents(events: ParsedEvents['allDay'], weekStart: Date) { let parsed = [[]] as ParsedRangeEvent[][]; const filtered = filterWeeklyEvents(events, weekStart); [...filtered.keys()].sort((a, b) => sortDate(a, b)).forEach(item => { const startDate = new Date(item); const curr = filtered.get(item).filter(event => isSameDay(event.date, startDate)); parsed = parseWeeklyAllDayEvent(curr, startDate, weekStart, parsed); }); return parsed; } _renderWeeklyAllDayEvent(events: ParsedRangeEvent[][]) { const res = [] as ParsedRangeEvent[]; events.forEach(row => { const event = row.filter(item => 'leftPos' in item); res.push(...event); }); return res; } // return parsed weekly allday events parseWeeklyAllDayEvents(events: ParsedEvents['allDay']) { const { week } = this._adapter.getWeeklyData(); const weekStart = week[0].date; const parsed = this._parseWeeklyEvents(events, weekStart); const res = this._renderWeeklyAllDayEvent(parsed); return res; } getParsedWeeklyEvents(events: EventObject[]) { const parsed = this._parseEvents(events); const { displayValue } = this.getProps(); const result: ParsedEvents = {}; result.allDay = convertEventsArrToMap(parsed.allDay, 'start', startOfDay, displayValue); result.day = convertEventsArrToMap(parsed.day, 'date', null, displayValue); return result; } // return parsed weekly allday events parseWeeklyEvents() { const { events } = this.getProps(); const parsed = this.getParsedWeeklyEvents(events); this._adapter.setParsedEvents(parsed); this._adapter.cacheEventKeys((events as EventObject[]).map(i => i.key)); } // ================== Monthly Event ================== pushDayEventIntoWeekMap(item: EventObject, index: number, map: Record<string, EventObject[]>) { if (index in map) { map[index].push(item); } else { map[index] = [item]; } } convertMapToArray(weekMap: Map<string, EventObject[]>, weekStart: Date) { const eventArray = []; for (const entry of weekMap.entries()) { const [key, value] = entry; const map = new Map(); map.set(key, value); const weekEvents = this._parseWeeklyEvents(map, weekStart); eventArray.push(...weekEvents); } return eventArray; } getParseMonthlyEvents(itemLimit: number) { const parsed: any = {}; const { displayValue, events } = this.getProps(); const currDate = this._getDate(); const firstDayOfMonth = startOfMonth(displayValue); const lastDayOfMonth = endOfMonth(displayValue); const res: EventObject[] = []; (events as EventObject[]).sort((prev, next) => { if (isBefore(prev.start, next.start)) { return -1; } if (isAfter(prev.start, next.start)) { return 1; } return 0; }).forEach(event => { const parsedEvent = parseAllDayEvent(event, event.allDay, currDate); res.push(...parsedEvent); }); res.filter(item => isSameMonth(item.date, displayValue)); res.forEach(item => { // WeekInd calculation error, need to consider the boundary situation at the beginning/end of the month // When the date falls within the month if (isSameMonth(item.date, displayValue)) { const weekInd = getWeekOfMonth(item.date) - 1; this.pushDayEventIntoWeekMap(item, weekInd, parsed); return; } // When the date is within the previous month if (isBefore(item.date, firstDayOfMonth)) { if (isSameWeek(item.date, firstDayOfMonth)) { this.pushDayEventIntoWeekMap(item, 0, parsed); } return; } // When the date is within the next month if (isAfter(item.date, lastDayOfMonth)) { if (isSameWeek(item.date, lastDayOfMonth)) { const weekInd = getWeekOfMonth(lastDayOfMonth) - 1; this.pushDayEventIntoWeekMap(item, weekInd, parsed); } return; } }); Object.keys(parsed).forEach(key => { const week = parsed[key]; parsed[key] = {}; const weekStart = startOfWeek(week[0].date); const weekMap = convertEventsArrToMap(week, 'start', startOfDay); // When there are multiple events in a week, multiple events should be parsed // const oldParsedWeeklyEvent = this._parseWeeklyEvents(weekMap, weekStart); const parsedWeeklyEvent = this.convertMapToArray(weekMap, weekStart); parsed[key].day = collectDailyEvents(parsedWeeklyEvent); parsed[key].display = this._renderDisplayEvents(parsedWeeklyEvent); }); return parsed as MonthlyEvent; } parseMonthlyEvents(itemLimit: number) { const { events } = this.getProps(); const parsed = this.getParseMonthlyEvents(itemLimit); this._adapter.setParsedEvents(parsed); this._adapter.setItemLimit(itemLimit); this._adapter.cacheEventKeys((events as EventObject[]).map(i => i.key)); } _renderDisplayEvents(events: ParsedRangeEvent[][]) { // Limits should not be added when calculating the relative position of each event, because there will be calculations that separate two events in the middle of the week let displayEvents: ParsedRangeEvent[] | ParsedRangeEvent[][] = events.slice(); if (displayEvents.length) { displayEvents = this._renderWeeklyAllDayEvent(displayEvents); } return displayEvents; } // ================== Range Event ================== _parseRangeEvents(events: Map<string, EventObject[]>) { let parsed: Array<Array<ParsedRangeEvent>> = [[]]; const [start, end] = this.getProp('range'); const filtered = filterEvents(events, start, end); [...filtered.keys()].sort((a, b) => sortDate(a, b)).forEach(item => { const startDate = new Date(item); const curr = filtered.get(item).filter(event => isSameDay(event.date, startDate)); parsed = parseRangeAllDayEvent(curr, startDate, start, end, parsed); }); return parsed; } _renderRangeAllDayEvent(events: Array<Array<ParsedRangeEvent>>) { let res: Array<ParsedRangeEvent> = []; events.forEach(row => { const event = row.filter(item => 'leftPos' in item); res = [...res, ...event]; }); return res; } // return parsed weekly allday events parseRangeAllDayEvents(events: ParsedEvents['allDay']) { const parsed = this._parseRangeEvents(events); const res = this._renderRangeAllDayEvent(parsed); return res; } getParsedRangeEvents(events: EventObject[]) { const parsed = this._parseEvents(events); const [start] = this.getProp('range'); (parsed as unknown as ParsedEvents).allDay = convertEventsArrToMap(parsed.allDay, 'start', startOfDay, start); ((parsed as unknown as ParsedEvents)).day = convertEventsArrToMap(parsed.day, 'date', null, start); return parsed as unknown as ParsedEvents; } // return parsed weekly allday events parseRangeEvents() { const { events } = this.getProps() as { events: EventObject[] }; const parsed = this.getParsedRangeEvents(events); this._adapter.setParsedEvents(parsed); this._adapter.cacheEventKeys(events.map(i => i.key)); } checkWeekend(val: Date) { return checkWeekend(val); } }
the_stack
import * as d3Axis from 'd3-axis'; import { ScaleLinear, ScalePoint } from 'd3-scale'; import * as d3Shape from 'd3-shape'; import * as d3Drag from 'd3-drag'; import * as d3Selection from 'd3-selection'; import * as d3Transition from 'd3-transition'; import ReactDOM from 'react-dom'; import { d3Scale } from '../../index'; import _ from 'lodash'; import * as d3Array from 'd3-array'; import { StandardProps } from '../../util/component-types'; import { lucidClassNames } from '../../util/style-helpers'; import { IXAxisRenderProp, getGroup, lucidXAxis, ISelection, } from './d3-helpers'; const cx = lucidClassNames.bind('&-DraggableLineChart'); export interface IChartData { x: string; y: number; ref?: any; } export type IOnDragEnd = (newYValue: string, xValue: string) => void; export type IData = IChartData[]; export type ISelectedChartData = IChartData & { isSelected: boolean }; export type IOnPreselect = (data: ISelectedChartData[]) => void; interface IDraggableLineChartMargin { top: number; right: number; bottom: number; left: number; } const getAttributes = function (selection: ISelection, obj: string[]): any { return _.reduce( obj, (acc, value) => { // @ts-ignore acc[value] = selection.attr(value); return acc; }, {} ); }; export interface IDraggableLineChart extends StandardProps { /** Height of the chart. */ height?: number; /** Width of the chart. */ width?: number; /** Margin is an object defining the margins of the chart. These margins will contain the axis and labels. */ margin?: IDraggableLineChartMargin; /** Data for the chart. Basic example: [ { x: new Date('2015-01-01') , y: 1 } , { x: new Date('2015-01-02') , y: 2 } , { x: new Date('2015-01-03') , y: 3 } , { x: new Date('2015-01-04') , y: 2 } , { x: new Date('2015-01-05') , y: 5 } , ] If you want to be able to navigate to one of the components, you can use ref as well: [ { x: new Date('2015-01-01') , y: 1, ref: React.createRef() } , { x: new Date('2015-01-02') , y: 2, ref: React.createRef() } , { x: new Date('2015-01-03') , y: 3, ref: React.createRef() } , { x: new Date('2015-01-04') , y: 2, ref: React.createRef() } , { x: new Date('2015-01-05') , y: 5, ref: React.createRef() } , ] */ data: IData; /** Drag handler function which is a callable function executed at the end of drag. Called when the user stops to dragging an item. Signature: `({ event, props }) => {}` */ onDragEnd?: IOnDragEnd; /** Drag handler function which is a callable function executed at the end of drag. Called when the user stops to dragging an item. Signature: `({ event, props }) => {}` When defined show draggable pane. */ onPreselect?: IOnPreselect; /** Flag for if xAxis tick labels are vertical. */ xAxisTicksVertical?: boolean; /** Flag for if data is center aligned rather than default left aligned. */ dataIsCentered?: boolean; /** Flag for yAxis sticking to minimum (not readjusting minimum). */ yAxisMin?: number; /** Optional react component to render within X-Axis. Note: If you are using input boxes or similar and you want to navigate to the next component on tab, you will might need to provide refs in the data. This react component will always be passed the following props: ({x, y, ref }: { x: string; y: number; ref?: any }) */ xAxisRenderProp?: IXAxisRenderProp; /** * Text to show to users when there is no data selection */ preSelectText?: string; yAxisFormatter?: ((value: string) => string) | null; } interface IDraggableLineChartParams extends IDraggableLineChart { IDraggableLineChart?: boolean; cx: (d: any) => void; height: number; width: number; margin: IDraggableLineChartMargin; yAxisMin: number; isMouseDown?: boolean; mouseDownStep?: number; hasRenderedPoint?: boolean; hasRenderedLine?: boolean; emptyRenderProp?: () => JSX.Element; } class DraggableLineChartD3 { selection: ISelection; params: IDraggableLineChartParams; xScale: ScalePoint<string>; yScale: ScaleLinear<number, number>; constructor(selection: ISelection, params: IDraggableLineChartParams) { this.selection = selection; this.params = params; if (params.dataIsCentered) { this.xScale = d3Scale .scalePoint() .domain([...this.params.data.map((d: any) => d.x), '']) .range([ this.params.margin.left, this.params.width - this.params.margin.right - this.params.margin.left, ]); } else { this.xScale = d3Scale .scalePoint() .domain(this.params.data.map((d: any) => d.x)) .range([ this.params.margin.left, this.params.width - this.params.margin.right - this.params.margin.left, ]); } this.yScale = d3Scale .scaleLinear() .domain([ _.isUndefined(this.params.yAxisMin) ? d3Array.min(this.params.data, (d: any) => d.y) : this.params.yAxisMin, d3Array.max(this.params.data, (d: any) => d.y) || 10, ]) .nice() .range([ this.params.height - this.params.margin.bottom, this.params.margin.top, ]); } setMouseDown = (isMouseDown: boolean, mouseDownStep?: number) => { this.params.isMouseDown = isMouseDown; this.params.mouseDownStep = mouseDownStep; }; getIsMouseDown = () => { return this.params.isMouseDown; }; getMouseDownStep = () => { return this.params.mouseDownStep || 0; }; getHasRenderedPoint = () => { return !!this.params.hasRenderedPoint; }; getHasRenderedLine = () => { return !!this.params.hasRenderedLine; }; setHasRenderedPoint = () => { this.params.hasRenderedPoint = true; }; setHasRenderedLine = () => { this.params.hasRenderedLine = true; }; shouldShowPreselect = () => { const hasUserValues = _.some(this.params.data, ({ y }) => y > 0); return !!this.params.onPreselect && !hasUserValues; }; drag: any = () => { const { xScale, yScale, renderLine, renderPoints, selection } = this; const { cx, onDragEnd } = this.params; let initialPosition: number; return d3Drag .drag() .on('start', function () { const activeDot = d3Selection.select(this); initialPosition = Number(activeDot.attr('cy')); }) .on('drag', function (pointData: any) { const [max, min] = yScale.range(); const activeDot = d3Selection.select(this); const adjMouseY = initialPosition + d3Selection.event.y; const newPointY = adjMouseY < min ? min : adjMouseY > max ? max : adjMouseY; const lines = selection.selectAll(`path.${cx('&-Line')}`); pointData.y = Number(yScale.invert(newPointY)); activeDot.attr('cy', newPointY); const line: any = d3Shape .line<IChartData>() .x((chartData: IChartData) => xScale(chartData.x) || 0) .y((chartData: IChartData) => yScale(chartData.y) as any); lines.attr('d', line); }) .on('end', (d: any) => { if (onDragEnd) onDragEnd(d.y, d.x); renderLine(); renderPoints(); }); }; renderXAxis = () => { const { margin, height, xAxisTicksVertical, dataIsCentered, cx, xAxisRenderProp, data, } = this.params; const xGroup = getGroup(this.selection, `${cx('&-Axis')}`); xGroup .call((xAxis: any) => { xAxis .attr('transform', `translate(${0},${margin.top})`) .call(lucidXAxis, { xScale: this.xScale, tickSize: margin.top + margin.bottom - height, xAxisRenderProp, dataIsCentered, data, }); if (xAxisTicksVertical) { xAxis.classed('Vert', true); } else { xAxis.classed('NoVert', true); } if (dataIsCentered) { xAxis.classed('Center', true); } }) .call(() => xGroup); }; renderYAxis = () => { const yGroup = getGroup(this.selection, 'yAxisGroup'); yGroup .call((yAxis: any) => { const { margin, cx, yAxisFormatter } = this.params; yAxis .attr('transform', `translate(${margin.left},${0})`) .classed(`${cx('&-Axis')}`, true) .transition() .duration(500) .call( d3Axis .axisLeft(this.yScale) .tickFormat( yAxisFormatter as (domainValue: any, index: number) => string ) ); }) .call(() => yGroup); }; renderLine = () => { if (this.shouldShowPreselect()) { return; } const { dataIsCentered, cx } = this.params; if (!this.getHasRenderedLine()) { if (dataIsCentered) { const innerXTickWidth = this.xScale.step(); this.selection .append('g') .append('path') .attr('class', `${cx('&-Line')}`) .attr('transform', `translate(${innerXTickWidth / 2}, 0)`); } else { this.selection .append('g') .append('path') .attr('class', `${cx('&-Line')}`); } this.setHasRenderedLine(); } const lines: any = this.selection.selectAll(`path.${cx('&-Line')}`); lines.datum(this.params.data).enter(); lines .transition(d3Transition.transition().duration(100)) .attr('fill', 'none') .attr( 'd', d3Shape .line() .x((d: any) => this.xScale(d.x) || 0) .y((d: any) => this.yScale(d.y) as any) ); }; renderEmptyRenderProp = (height: number, width: number) => { const { emptyRenderProp } = this.params; if (!emptyRenderProp || !this.shouldShowPreselect()) { return; } const emptyDataObject = this.selection.selectAll('.emptyRender'); if (emptyDataObject.empty()) { const emptyRender: ISelection = this.selection .selectAll('.overlayContainer') .append('foreignObject') .attr('height', height) .attr('width', width) .attr('x', this.params.margin.left) .classed('emptyRender', true); emptyRender.html((value: any, num: any, node: any): any => { ReactDOM.render(emptyRenderProp(), node[0]); }); } }; renderPoints = () => { if (this.shouldShowPreselect()) { return; } const { data, dataIsCentered } = this.params; const circle = this.getHasRenderedPoint() ? this.selection.selectAll('circle').data(data).join('circle') : this.selection .append('g') .selectAll('circle') .data(data) .join('circle'); if (dataIsCentered) { const innerXTickWidth = this.xScale.step(); circle .transition() .duration(100) .attr('cx', (d: any) => this.xScale(d.x) || 0) .attr('cy', (d: any) => this.yScale(d.y) as any) .attr('r', 5) .attr('transform', `translate(${innerXTickWidth / 2}, 0)`) .style('fill', '#587EBA') .style('stroke', 'white') .style('stroke-width', 1); } else { circle .transition() .duration(100) .attr('cx', (d: any) => this.xScale(d.x) || 0) .attr('cy', (d: any) => this.yScale(d.y) as any) .attr('r', 5) .style('fill', '#587EBA') .style('stroke', 'white') .style('stroke-width', 1); } if (!this.getHasRenderedPoint()) circle.call(this.drag()); this.setHasRenderedPoint(); }; reRenderDragBox = ({ dragBox, mouseX, xLeft, xRight, stepWidth, stepCount, }: { dragBox: any; mouseX: number; xLeft: number; xRight: number; stepWidth: number; stepCount: number; }) => { const isLeft = xLeft >= mouseX; const isRight = xRight <= mouseX; const mouseDownStep = this.getMouseDownStep(); if (isLeft) { const difference = _.max([xLeft - mouseX, 0]) || 0; const rawStepsSelected = Math.floor(difference / stepWidth) + 2; const maxStepsAvailable = mouseDownStep + 1; const stepsSelected = _.min([rawStepsSelected, maxStepsAvailable]) || 1; const activeBoxWidth = stepsSelected * stepWidth; const nextXLeft = xRight - activeBoxWidth; dragBox.attr('x', nextXLeft); dragBox.attr('width', activeBoxWidth); } else if (isRight) { const difference = _.max([mouseX - xRight, 0]) || 0; const rawStepsSelected = Math.floor(difference / stepWidth) + 2; const maxStepsAvailable = stepCount - mouseDownStep; const stepsSelected = _.min([rawStepsSelected, maxStepsAvailable]) || 1; const activeBoxWidth = stepsSelected * stepWidth; dragBox.attr('x', xLeft); dragBox.attr('width', activeBoxWidth); } else { dragBox.attr('x', xLeft); dragBox.attr('width', stepWidth); } }; renderHoverTracker = () => { const { height, margin: { top, bottom }, data, onPreselect, } = this.params; const { shouldShowPreselect, setMouseDown, getIsMouseDown, getMouseDownStep, reRenderDragBox, xScale, selection, } = this; if (!shouldShowPreselect()) { selection.selectAll('.overlayContainer').remove(); return; } const innerHeight = height - top - bottom; const stepWidth = xScale.step(); const stepCount = data.length; const overlayContainer = selection .append('g') .classed('overlayContainer', true) .attr('transform', `translate(${0},${top})`); this.renderEmptyRenderProp(innerHeight, stepCount * stepWidth); const overlayTrack = overlayContainer.selectAll('rect').data(data).enter(); overlayTrack .append('rect') .attr('x', (chartData) => this.xScale(chartData.x) || 0) .attr('y', 0) .attr('width', (chartData) => this.xScale.step()) .attr('height', innerHeight) .classed(cx('&-overlayTrack'), true) .on('mouseenter', (d, i, nodes) => { if (!getIsMouseDown()) { d3Selection.select(nodes[i]).classed('active', true); } }) .on('mouseout', function (d, i, nodes) { if (!getIsMouseDown()) { d3Selection.select(nodes[i]).classed('active', false); } }) .on('mousedown', function (d, i) { d3Selection.selectAll('.active').classed('active', false); const currentTarget = d3Selection.select(this); const { x, y, width, height }: any = getAttributes(currentTarget, [ 'x', 'y', 'width', 'height', ]); setMouseDown(true, i); const xLeft = +x; const xRight = +x + +width; // @ts-ignore const container = d3Selection.select(this.parentNode); container .append('rect') .attr('x', x) .attr('y', y) .attr('width', width) .attr('height', height) .classed(cx('&-overlayTrack'), true) .classed('active', true) .classed('dragBox', true) .on('mouseout', function () { // @ts-ignore const [mouseX] = d3Selection.mouse(this); const dragBox = selection.selectAll('.dragBox'); reRenderDragBox({ dragBox, mouseX, xLeft, xRight, stepWidth, stepCount, }); }) .on('mousemove', function () { // @ts-ignore const [mouseX] = d3Selection.mouse(this); const dragBox = selection.selectAll('.dragBox'); reRenderDragBox({ dragBox, mouseX, xLeft, xRight, stepWidth, stepCount, }); }) .on('mouseup', function () { const clickStep = getMouseDownStep(); const activeBox = selection.selectAll('.dragBox'); const { x, width } = getAttributes(activeBox, ['x', 'width']); const isRight = xLeft === +x; const steps = Math.round(+width / stepWidth); const startingIndex = isRight ? clickStep : clickStep - steps + 1; const endingIndex = startingIndex + steps - 1; const updatedData = data.map((step, i) => ({ ...step, isSelected: i >= startingIndex && i <= endingIndex, })); !!onPreselect && onPreselect(updatedData); setMouseDown(false); selection.selectAll('.dragBox').remove(); selection.selectAll('.overlayContainer').remove(); }); }); }; renderLineChart = () => { this.renderXAxis(); this.renderYAxis(); this.renderHoverTracker(); this.renderLine(); this.renderPoints(); }; updateLineChart = (data: IData) => { this.params.data = data; this.yScale.domain([ _.isUndefined(this.params.yAxisMin) ? d3Array.min(this.params.data, (d: any) => d.y) : this.params.yAxisMin, d3Array.max(this.params.data, (d: any) => d.y) || 10, ]); this.renderLineChart(); }; } export default DraggableLineChartD3;
the_stack
import { createBrotliCompress, createGzip } from 'zlib'; import Multistream from 'multistream'; import assert from 'assert'; import { execFileSync } from 'child_process'; import fs from 'fs-extra'; import intoStream from 'into-stream'; import path from 'path'; import streamMeter from 'stream-meter'; import { Readable } from 'stream'; import { STORE_BLOB, STORE_CONTENT, isDotNODE, snapshotify } from './common'; import { log, wasReported } from './log'; import { fabricateTwice } from './fabricator'; import { platform, SymLinks, Target } from './types'; import { Stripe } from './packer'; import { CompressType } from './compress_type'; interface NotFound { notFound: true; } interface Placeholder { position: number; size: number; padder: string; } type PlaceholderTypes = | 'BAKERY' | 'PAYLOAD_POSITION' | 'PAYLOAD_SIZE' | 'PRELUDE_POSITION' | 'PRELUDE_SIZE'; type PlaceholderMap = Record<PlaceholderTypes, Placeholder | NotFound>; function discoverPlaceholder( binaryBuffer: Buffer, searchString: string, padder: string ): Placeholder | NotFound { const placeholder = Buffer.from(searchString); const position = binaryBuffer.indexOf(placeholder); if (position === -1) { return { notFound: true }; } return { position, size: placeholder.length, padder }; } function injectPlaceholder( fd: number, placeholder: Placeholder | NotFound, value: string | number | Buffer, cb: ( err: NodeJS.ErrnoException | null, written: number, buffer: Buffer ) => void ) { if ('notFound' in placeholder) { assert(false, 'Placeholder for not found'); } const { position, size, padder } = placeholder; let stringValue: Buffer = Buffer.from(''); if (typeof value === 'number') { stringValue = Buffer.from(value.toString()); } else if (typeof value === 'string') { stringValue = Buffer.from(value); } else { stringValue = value; } const padding = Buffer.from(padder.repeat(size - stringValue.length)); stringValue = Buffer.concat([stringValue, padding]); fs.write(fd, stringValue, 0, stringValue.length, position, cb); } function discoverPlaceholders(binaryBuffer: Buffer) { return { BAKERY: discoverPlaceholder( binaryBuffer, `\0${'// BAKERY '.repeat(20)}`, '\0' ), PAYLOAD_POSITION: discoverPlaceholder( binaryBuffer, '// PAYLOAD_POSITION //', ' ' ), PAYLOAD_SIZE: discoverPlaceholder(binaryBuffer, '// PAYLOAD_SIZE //', ' '), PRELUDE_POSITION: discoverPlaceholder( binaryBuffer, '// PRELUDE_POSITION //', ' ' ), PRELUDE_SIZE: discoverPlaceholder(binaryBuffer, '// PRELUDE_SIZE //', ' '), }; } function injectPlaceholders( fd: number, placeholders: PlaceholderMap, values: Record<PlaceholderTypes, number | string | Buffer>, cb: (error?: Error | null) => void ) { injectPlaceholder(fd, placeholders.BAKERY, values.BAKERY, (error) => { if (error) { return cb(error); } injectPlaceholder( fd, placeholders.PAYLOAD_POSITION, values.PAYLOAD_POSITION, (error2) => { if (error2) { return cb(error2); } injectPlaceholder( fd, placeholders.PAYLOAD_SIZE, values.PAYLOAD_SIZE, (error3) => { if (error3) { return cb(error3); } injectPlaceholder( fd, placeholders.PRELUDE_POSITION, values.PRELUDE_POSITION, (error4) => { if (error4) { return cb(error4); } injectPlaceholder( fd, placeholders.PRELUDE_SIZE, values.PRELUDE_SIZE, cb ); } ); } ); } ); }); } function makeBakeryValueFromBakes(bakes: string[]) { const parts = []; if (bakes.length) { for (let i = 0; i < bakes.length; i += 1) { parts.push(Buffer.from(bakes[i])); parts.push(Buffer.alloc(1)); } parts.push(Buffer.alloc(1)); } return Buffer.concat(parts); } function replaceDollarWise(s: string, sf: string, st: string) { return s.replace(sf, () => st); } function makePreludeBufferFromPrelude(prelude: string) { return Buffer.from( `(function(process, require, console, EXECPATH_FD, PAYLOAD_POSITION, PAYLOAD_SIZE) { ${prelude}\n})` // dont remove \n ); } function findPackageJson(nodeFile: string) { let dir = nodeFile; while (dir !== '/') { dir = path.dirname(dir); if (fs.existsSync(path.join(dir, 'package.json'))) { break; } } if (dir === '/') { throw new Error(`package.json not found for "${nodeFile}"`); } return dir; } function nativePrebuildInstall(target: Target, nodeFile: string) { const prebuildInstall = path.join( __dirname, '../node_modules/.bin/prebuild-install' ); const dir = findPackageJson(nodeFile); // parse the target node version from the binaryPath const nodeVersion = path.basename(target.binaryPath).split('-')[1]; if (!/^v[0-9]+\.[0-9]+\.[0-9]+$/.test(nodeVersion)) { throw new Error(`Couldn't find node version, instead got: ${nodeVersion}`); } const nativeFile = `${nodeFile}.${target.platform}.${nodeVersion}`; if (fs.existsSync(nativeFile)) { return nativeFile; } // prebuild-install will overwrite the target .node file, so take a backup if (!fs.existsSync(`${nodeFile}.bak`)) { fs.copyFileSync(nodeFile, `${nodeFile}.bak`); } // run prebuild execFileSync( prebuildInstall, [ '--target', nodeVersion, '--platform', platform[target.platform], '--arch', target.arch, ], { cwd: dir } ); // move the prebuild to a new name with a platform/version extension fs.copyFileSync(nodeFile, nativeFile); // put the backed up file back fs.moveSync(`${nodeFile}.bak`, nodeFile, { overwrite: true }); return nativeFile; } interface ProducerOptions { backpack: { entrypoint: string; stripes: Stripe[]; prelude: string }; bakes: string[]; slash: string; target: Target; symLinks: SymLinks; doCompress: CompressType; nativeBuild: boolean; } /** * instead of creating a vfs dicionnary with actual path as key * we use a compression mechanism that can reduce significantly * the memory footprint of the vfs in the code. * * without vfs compression: * * vfs = { * "/folder1/folder2/file1.js": {}; * "/folder1/folder2/folder3/file2.js": {}; * "/folder1/folder2/folder3/file3.js": {}; * } * * with compression : * * fileDictionary = { * "folder1": "1", * "folder2": "2", * "file1": "3", * "folder3": "4", * "file2": "5", * "file3": "6", * } * vfs = { * "/1/2/3": {}; * "/1/2/4/5": {}; * "/1/2/4/6": {}; * } * * note: the key is computed in base36 for further compression. */ const fileDictionary: { [key: string]: string } = {}; let counter = 0; function getOrCreateHash(fileOrFolderName: string) { let existingKey = fileDictionary[fileOrFolderName]; if (!existingKey) { const newkey = counter; counter += 1; existingKey = newkey.toString(36); fileDictionary[fileOrFolderName] = existingKey; } return existingKey; } const separator = '/'; function makeKey( doCompression: CompressType, fullpath: string, slash: string ): string { if (doCompression === CompressType.None) return fullpath; return fullpath.split(slash).map(getOrCreateHash).join(separator); } export default function producer({ backpack, bakes, slash, target, symLinks, doCompress, nativeBuild, }: ProducerOptions) { return new Promise<void>((resolve, reject) => { if (!Buffer.alloc) { throw wasReported( 'Your node.js does not have Buffer.alloc. Please upgrade!' ); } const { prelude } = backpack; let { entrypoint, stripes } = backpack; entrypoint = snapshotify(entrypoint, slash); stripes = stripes.slice(); const vfs: Record<string, Record<string, [number, number]>> = {}; for (const stripe of stripes) { let { snap } = stripe; snap = snapshotify(snap, slash); const vfsKey = makeKey(doCompress, snap, slash); if (!vfs[vfsKey]) vfs[vfsKey] = {}; } const snapshotSymLinks: SymLinks = {}; for (const [key, value] of Object.entries(symLinks)) { const k = snapshotify(key, slash); const v = snapshotify(value, slash); const vfsKey = makeKey(doCompress, k, slash); snapshotSymLinks[vfsKey] = makeKey(doCompress, v, slash); } let meter: streamMeter.StreamMeter; let count = 0; function pipeToNewMeter(s: Readable) { meter = streamMeter(); return s.pipe(meter); } function pipeMayCompressToNewMeter(s: Readable): streamMeter.StreamMeter { if (doCompress === CompressType.GZip) { return pipeToNewMeter(s.pipe(createGzip())); } if (doCompress === CompressType.Brotli) { return pipeToNewMeter(s.pipe(createBrotliCompress())); } return pipeToNewMeter(s); } function next(s: Readable) { count += 1; return pipeToNewMeter(s); } const binaryBuffer = fs.readFileSync(target.binaryPath); const placeholders = discoverPlaceholders(binaryBuffer); let track = 0; let prevStripe: Stripe; let payloadPosition: number; let payloadSize: number; let preludePosition: number; let preludeSize: number; new Multistream((cb) => { if (count === 0) { return cb(null, next(intoStream(binaryBuffer))); } if (count === 1) { payloadPosition = meter.bytes; return cb(null, next(intoStream(Buffer.alloc(0)))); } if (count === 2) { if (prevStripe && !prevStripe.skip) { const { store } = prevStripe; let { snap } = prevStripe; snap = snapshotify(snap, slash); const vfsKey = makeKey(doCompress, snap, slash); vfs[vfsKey][store] = [track, meter.bytes]; track += meter.bytes; } if (stripes.length) { // clone to prevent 'skip' propagate // to other targets, since same stripe // is used for several targets const stripe = { ...(stripes.shift() as Stripe) }; prevStripe = stripe; if (stripe.buffer) { if (stripe.store === STORE_BLOB) { const snap = snapshotify(stripe.snap, slash); return fabricateTwice( bakes, target.fabricator, snap, stripe.buffer, (error, buffer) => { if (error) { log.warn(error.message); stripe.skip = true; return cb(null, intoStream(Buffer.alloc(0))); } cb( null, pipeMayCompressToNewMeter( intoStream(buffer || Buffer.from('')) ) ); } ); } return cb( null, pipeMayCompressToNewMeter(intoStream(stripe.buffer)) ); } if (stripe.file) { if (stripe.file === target.output) { return cb( wasReported( 'Trying to take executable into executable', stripe.file ), null ); } assert.strictEqual(stripe.store, STORE_CONTENT); // others must be buffers from walker if (isDotNODE(stripe.file) && nativeBuild) { try { const platformFile = nativePrebuildInstall(target, stripe.file); if (fs.existsSync(platformFile)) { return cb( null, pipeMayCompressToNewMeter(fs.createReadStream(platformFile)) ); } } catch (err) { log.debug( `prebuild-install failed[${stripe.file}]:`, (err as Error).message ); } } return cb( null, pipeMayCompressToNewMeter(fs.createReadStream(stripe.file)) ); } assert(false, 'producer: bad stripe'); } else { payloadSize = track; preludePosition = payloadPosition + payloadSize; return cb( null, next( intoStream( makePreludeBufferFromPrelude( replaceDollarWise( replaceDollarWise( replaceDollarWise( replaceDollarWise( replaceDollarWise( prelude, '%VIRTUAL_FILESYSTEM%', JSON.stringify(vfs) ), '%DEFAULT_ENTRYPOINT%', JSON.stringify(entrypoint) ), '%SYMLINKS%', JSON.stringify(snapshotSymLinks) ), '%DICT%', JSON.stringify(fileDictionary) ), '%DOCOMPRESS%', JSON.stringify(doCompress) ) ) ) ) ); } } else { return cb(null, null); } }) .on('error', (error) => { reject(error); }) .pipe(fs.createWriteStream(target.output)) .on('error', (error) => { reject(error); }) .on('close', () => { preludeSize = meter.bytes; fs.open(target.output, 'r+', (error, fd) => { if (error) return reject(error); injectPlaceholders( fd, placeholders, { BAKERY: makeBakeryValueFromBakes(bakes), PAYLOAD_POSITION: payloadPosition, PAYLOAD_SIZE: payloadSize, PRELUDE_POSITION: preludePosition, PRELUDE_SIZE: preludeSize, }, (error2) => { if (error2) return reject(error2); fs.close(fd, (error3) => { if (error3) return reject(error3); resolve(); }); } ); }); }); }); }
the_stack
import * as React from 'react'; import { arraysEqual, search, branchIn } from '../Utils'; import { ITableProps } from '../Table/Table'; import Emerge from '../Emerge/Emerge'; import Toolbar from '../Toolbar/Toolbar'; import Button from '../Button/Button'; import { IColumn } from './IColumn'; export interface IDataSourceProps extends ITableProps { // initial dataSource loaded as prop dataSource?: Array<Object> | Array<number> | Array<string>; columns?: Array<IColumn>; emptyText: string; loading?: boolean; loadingText?: string; addColumns?: Array<IColumn>; } const DataSource: any = (Component: JSX.Element) => class Enhance extends React.Component<IDataSourceProps, any> { constructor(props: IDataSourceProps) { super(props); this.state = { // dataSource dataSource: [], isArray: false, columns: [], activeRows: [], // page rowCount: props.rowCount || 0, pageSize: props.pageSize || 10, page: props.page || 0, numberOfPages: 0, numberPerPage: 0, // table selected options detailTemplateSelectedElements: props.detailTemplateSelectedElements || [], selectedElements: props.selectedElements || [], // table search searchTerm: '', searchedItems: [], // table sort sortType: props.sortType || 'asc', sortKey: props.sortKey || null }; } static getDerivedStateFromProps(props, state) { if ( (!!props.selectedElements && props.selectedElements !== state.selectedElements) || (!!props.detailTemplateSelectedElements && props.detailTemplateSelectedElements !== state.detailTemplateSelectedElements) ) { return { selectedElements: props.selectedElements ? props.selectedElements : state.selectedElements, detailTemplateSelectedElements: props.detailTemplateSelectedElements ? props.detailTemplateSelectedElements : state.detailTemplateSelectedElements }; } else { return { selectedElements: state.selectedElements, detailTemplateSelectedElements: state.detailTemplateSelectedElements }; } } componentDidUpdate(prevProps: IDataSourceProps, prevState) { let { dataSource, sortKey, sortType, pageSize, rowCount, searchValue, searchableKeys, page } = this.props; if ((page !== null && page !== undefined && page !== prevState.page) || prevProps.pageSize !== pageSize) { this.setState( { page: page !== null && page !== undefined ? page : prevState.page, pageSize: prevProps.pageSize !== pageSize ? pageSize : prevProps.pageSize }, () => { this.renderActiveRows(prevState.dataSource); } ); } if (!!this.props.sortKey && this.props.sortKey !== prevProps.sortKey) { this.sortDataSource(dataSource, sortType, sortKey); } else { if (this.props.dataSource && !prevProps.page) { dataSource.length > 0 && prevProps.dataSource !== dataSource ? this.loadDataSource(dataSource) : null; dataSource.length === 0 && prevProps.dataSource !== dataSource ? this.loadDataSource([]) : null; } } if (!!searchValue && searchValue !== prevProps.searchValue) { this.filterItems(searchValue, searchableKeys); } if (prevProps.pageSize !== pageSize) { this.setState({ pageSize: pageSize, rowCount: rowCount ? rowCount : prevState.rowCount }); } } componentDidMount() { const self = this; const props = self.props; let { dataSource } = props; (dataSource && Object.keys(dataSource).length) || (dataSource && dataSource.length) ? self.loadDataSource(dataSource) : self.loadDataSource([]); } loadDataSource<T>(dataSource: Array<T>) { const self = this; let dataSourceIsObject = typeof dataSource === 'object'; let dataSourceIsArray = dataSource instanceof Array; let dataSourceIsArrayOfStingsOrNumbers = typeof dataSource[0] === 'string' || typeof dataSource[0] === 'number'; let { sortKey } = this.props; let { sortType, page } = this.state; let setDataSourceState = (dataSource: Array<T> | Array<Array<T>>, isArray: boolean) => { self.setState( { dataSource: dataSource, isArray: isArray }, () => { this.defineColumns(dataSource); if (sortKey && sortType) { self.sortDataSource(dataSource, sortType, sortKey); } else { self.gotoPage(dataSource, page); } } ); }; if (dataSourceIsArray) { if (dataSourceIsArrayOfStingsOrNumbers) { let newDataSource: Array<T> = []; dataSource.forEach((element) => { newDataSource.push(element); }); setDataSourceState(newDataSource, true); } else { setDataSourceState(dataSource, false); } } else if (dataSourceIsObject) { setDataSourceState([ dataSource ], false); } else { setDataSourceState(dataSource, false); } } sortDataSource(dataSource: Array<any>, sortType: string, sortKey: string) { const self = this; let { searchedItems, searchTerm } = self.state; let sortOrderSearchedItems: Array<any>; let sortOrderDataSource: Array<any>; let sort = (dataSource: Array<any>) => { return dataSource.sort(function(a, b) { let aKey = branchIn(a, sortKey); let bKey = branchIn(b, sortKey); switch (typeof aKey) { case 'string': let itemPrev = aKey && aKey.toLowerCase(); let itemNext = bKey && bKey.toLowerCase(); if (itemPrev < itemNext) //string asc return -1; if (itemPrev > itemNext) return 1; break; case 'number': return aKey - bKey; default: return null; } return null; }); }; if (sortType === 'asc') { sortOrderDataSource = sort(dataSource); sortOrderSearchedItems = sort(searchedItems); } else { sortOrderDataSource = sort(dataSource).reverse(); sortOrderSearchedItems = sort(searchedItems).reverse(); } if (searchTerm !== '') { self.setState( { dataSource: sortOrderDataSource, searchedItems: sortOrderSearchedItems }, () => { self.gotoPage(sortOrderSearchedItems, this.state.page); } ); } else { self.setState( { dataSource: sortOrderDataSource }, () => { self.gotoPage(sortOrderDataSource, this.state.page); } ); } } defineColumns(dataSource: Array<any>) { const self = this; const props = self.props; let state = self.state; let { columns } = props; let { isArray } = state; let columnsArray: Array<any>; // columns are defined if (dataSource.length > 0) { if (columns) { columnsArray = columns; } else { // else automatically create them columnsArray = []; if (isArray) { columnsArray.push({ name: '_Array' }); } else { Object.keys(dataSource[0]).map((key) => { columnsArray.push({ name: key }); }); } } } this.setState( { columns: columnsArray }, () => { if (props.addColumns) { let updatedColumns = self.state.columns; for (let col of props.addColumns) { updatedColumns.push(col); } self.setState({ columns: updatedColumns }); } } ); } renderActiveRows(dataSource: Array<any>) { const self = this; const props = self.props; let { rowCount } = props; let activeRows: Array<any> = []; let numberPerPage, numberOfPages, renderedPage; let { page, pageSize } = self.state; if (this.state.searchTerm !== '') { renderedPage = this.state.searchedItems; } else { renderedPage = dataSource; } if (rowCount) { numberPerPage = pageSize; numberOfPages = Math.ceil(rowCount / pageSize); } else { numberPerPage = pageSize; numberOfPages = Math.ceil(renderedPage.length / pageSize); } this.setState({ numberPerPage: numberPerPage, numberOfPages: numberOfPages }); let begin = page * parseInt(numberPerPage); let end = begin + parseInt(numberPerPage); let pageList = renderedPage.slice(begin, end); pageList.map((item: Array<any>) => { activeRows.push(item); }); this.setState({ activeRows: activeRows }); //this.props.searchValue ? this.filterItems(this.props.searchValue, this.props.searchableKeys) : null; } detailTemplateToggleAll(dataSource: Array<any>) { let { detailTemplateSelectedElements } = this.state; this.setState({ detailTemplateSelectedElements: arraysEqual(dataSource, detailTemplateSelectedElements) ? [] : dataSource }); } detailTemplateToggleSelectedElements(element: Array<any>) { const self = this; let { detailTemplateOpenOnRowSelect, selectedKey } = this.props; let { detailTemplateSelectedElements } = self.state; let selectedElementsArray: any; let setSelectedElementsState = (data: Array<any>) => { self.setState({ detailTemplateSelectedElements: data }); }; if (detailTemplateOpenOnRowSelect === 'single') { selectedElementsArray = detailTemplateSelectedElements.length ? [ detailTemplateSelectedElements[0] ] : []; self.props.detailTemplateOnOpen ? self.props.detailTemplateOnOpen(element) : null; } else { selectedElementsArray = detailTemplateSelectedElements.slice(); } if (selectedElementsArray.includes(selectedKey ? element[selectedKey] : element)) { selectedElementsArray.map((data: string, key: string | number) => { if (data === selectedKey ? element[selectedKey] : element) { selectedElementsArray.splice(key, 1); setSelectedElementsState(selectedElementsArray); } }); } else { if (detailTemplateOpenOnRowSelect === 'single') { selectedElementsArray = []; selectedElementsArray.push(selectedKey ? element[selectedKey] : element); setSelectedElementsState(selectedElementsArray); } else { selectedElementsArray.push(selectedKey ? element[selectedKey] : element); setSelectedElementsState(selectedElementsArray); } } } selectAll(dataSource: Array<any>) { let { selectedElements } = this.state; this.setState({ selectedElements: arraysEqual(dataSource, selectedElements ? selectedElements : []) ? [] : dataSource }); } toggleSelectedElements(element: Array<any>, index: string | number) { const self = this; let { selectedElements } = self.state; let { rowIsSelectable, onCheck, selectedKey } = self.props; let selectedElement = selectedKey ? element[selectedKey] : element; let selectedElementsArray: any; if (rowIsSelectable === 'single') { selectedElementsArray = []; } else { selectedElementsArray = !!selectedElements ? selectedElements.slice() : []; } if (selectedElementsArray.includes(selectedElement)) { for (let i = 0; i < selectedElementsArray.length; i++) { if (selectedElementsArray[i] === selectedElement) { selectedElementsArray.splice(i, 1); self.setState( { selectedElements: selectedElementsArray }, () => { this.props.onRowSelect ? this.props.onRowSelect(element, index, selectedElementsArray) : null; } ); } } } else { selectedElementsArray.push(selectedElement); self.setState( { selectedElements: selectedElementsArray }, () => { this.props.onRowSelect ? this.props.onRowSelect(element, index, selectedElementsArray) : null; } ); onCheck ? onCheck(selectedElement) : null; } } firstPage() { this.setState( { page: 0 }, () => { this.renderActiveRows(this.state.dataSource); } ); this.props.onPageChange ? this.props.onPageChange(0) : null; } previousPage() { let pageNumber = this.state.page; this.props.onPageChange ? this.props.onPageChange(this.state.page - 1) : null; if (!this.props.serverSide) { this.setState( { page: (pageNumber -= 1) }, () => { this.renderActiveRows(this.state.dataSource); } ); } } nextPage() { let pageNumber = this.state.page; this.setState( { page: (pageNumber += 1) }, () => { this.renderActiveRows(this.state.dataSource); this.props.onPageChange ? this.props.onPageChange(this.state.page) : null; } ); } lastPage(numberOfPages: number) { this.setState( { page: numberOfPages - 1 }, () => { this.renderActiveRows(this.state.dataSource); } ); this.props.onPageChange ? this.props.onPageChange(numberOfPages - 1) : null; } gotoPage(datasource, i: number) { this.setState( { page: i, pageSize: this.state.pageSize }, () => { this.renderActiveRows(datasource); } ); } changePageSize(pageSize: any) { this.setState( { pageSize: pageSize, page: 0 }, () => { this.renderActiveRows(this.state.dataSource); } ); this.props.onPageSizeChange ? this.props.onPageSizeChange(pageSize) : null; } sortCollection(dataSource: Array<any>, key: string, sortType: string) { const self = this; let sortKey = this.props.sortKey ? this.props.sortKey : key; self.setState( { sortKey: sortKey, sortType: sortType }, () => { self.sortDataSource(dataSource, sortType, sortKey); } ); } toggleSorting(dataSource: Array<any>, key: string, sortType: string) { const self = this; self.sortCollection(dataSource, key, sortType); } filterItems(term: string, keys: Array<any>) { const self = this; let state = self.state; self.setState( { searchedItems: search(state.dataSource, term, keys, self.props.searchFilter), searchTerm: term, page: 0 }, () => { self.renderActiveRows(state.dataSource); } ); } render() { const self = this; const props = self.props; let { columns, dataSource, activeRows } = self.state; //let {emptyText} = props; let renderedObject = { // methods gotoPage: this.gotoPage.bind(this, dataSource), previousPage: this.previousPage.bind(this), nextPage: this.nextPage.bind(this), lastPage: this.lastPage.bind(this), firstPage: this.firstPage.bind(this), changePageSize: this.changePageSize.bind(this), detailTemplateToggleSelectedElements: this.detailTemplateToggleSelectedElements.bind(this), detailTemplateToggleAll: this.detailTemplateToggleAll.bind(this), selectAll: this.selectAll.bind(this), toggleSelectedElements: this.toggleSelectedElements.bind(this), sortCollection: this.sortCollection.bind(this), toggleSorting: this.toggleSorting.bind(this), filterItems: this.filterItems.bind(this) }; if (props.loading) { return ( <Emerge className="e-fill"> <Toolbar block textCenter> <Button loading={true} block size="large" simple> {props.loadingText} </Button> </Toolbar> </Emerge> ); } else if ((activeRows.length || dataSource.length) && columns && columns.length) { const newProps = Object.assign({}, props, self.state, renderedObject); // clone the original component and add the new props const updatedComponent = React.cloneElement(Component, newProps, Component.props); // only if a dataSource exists return the new element - else return original return dataSource.length ? updatedComponent : Component; } else { return props.emptyText ? ( <Emerge enter="fadeIn" className="e-fill"> <Toolbar block textCenter> <Button block size="small" simple> {props.emptyText} </Button> </Toolbar> </Emerge> ) : null; } } }; export default DataSource;
the_stack
import type { Fn, IObjectOf, MaybeDeref, NumOrString } from "@thi.ng/api"; export type CDataContent = ["!CDATA", ...string[]]; export type AttribVal<T> = MaybeDeref<T | undefined>; export type BooleanAttrib = AttribVal<boolean>; export type NumericAttrib = AttribVal<number>; export type StringAttrib = AttribVal<string>; export type MultiStringAttrib = AttribVal<string | string[]>; export type EventAttribVal<T> = | Fn<T, any> | [Fn<T, any>, boolean | AddEventListenerOptions] | string; export type EventAttribs<K extends string, T> = Record<K, EventAttribVal<T>>; export type AnimationEventAttribs = EventAttribs< | "onanimationcancel" | "onanimationend" | "onanimationiteration" | "onanimationstart", AnimationEvent >; export type DragEventAttribs = EventAttribs< | "ondrag" | "ondragend" | "ondragenter" | "ondragexit" | "ondragleave" | "ondragover" | "ondragstart" | "ondrop", DragEvent >; export type FocusEventAttribs = EventAttribs< "onblur" | "onfocus" | "onfocusin" | "onfocusout", FocusEvent >; export type InputEventAttribs = EventAttribs< "onchange" | "oninput", InputEvent >; export type KeyboardEventAttribs = EventAttribs< "onkeydown" | "onkeypress" | "onkeyup", KeyboardEvent >; export type MouseEventAttribs = EventAttribs< | "onclick" | "ondblclick" | "oncontextmenu" | "onmousedown" | "onmouseenter" | "onmouseleave" | "onmousemove" | "onmouseout" | "onmouseover" | "onmouseup", MouseEvent >; export type PointerEventAttribs = EventAttribs< | "ongotpointercapture" | "onlostpointercapture" | "onpointercancel" | "onpointerdown" | "onpointerenter" | "onpointerleave" | "onpointermove" | "onpointerout" | "onpointerover" | "onpointerup", PointerEvent >; export type SelectionEventAttribs = EventAttribs< "onselect" | "onselectionchange" | "onselectstart", Event >; export type TouchEventAttribs = EventAttribs< "ontouchcancel" | "ontouchend" | "ontouchmove" | "ontouchstart", TouchEvent >; export type TransitionEventAttribs = EventAttribs< | "ontransitioncancel" | "ontransitionend" | "ontransitionrun" | "ontransitionstart", TransitionEvent >; export type WheelEventAttribs = EventAttribs<"onwheel", WheelEvent>; export interface GlobalEventAttribs extends AnimationEventAttribs, DragEventAttribs, FocusEventAttribs, InputEventAttribs, KeyboardEventAttribs, MouseEventAttribs, PointerEventAttribs, SelectionEventAttribs, TouchEventAttribs, TransitionEventAttribs, WheelEventAttribs { onresize: EventAttribVal<UIEvent>; onscroll: EventAttribVal<Event>; onsubmit: EventAttribVal<Event>; } export interface MicroformatAttribs { itemid: StringAttrib; itemprop: StringAttrib; itemref: StringAttrib; itemscope: BooleanAttrib; itemtype: StringAttrib; } /** * RDFa attributes * * @remarks * - https://www.w3.org/TR/html-rdfa/ * - https://www.w3.org/TR/rdfa-core/#rdfa-attributes */ export interface RDFaAttribs { about: StringAttrib; content: StringAttrib; datatype: StringAttrib; href: StringAttrib; inlist: BooleanAttrib; prefix: MultiStringAttrib; property: MultiStringAttrib; rel: MultiStringAttrib; resource: StringAttrib; rev: MultiStringAttrib; src: StringAttrib; typeof: MultiStringAttrib; vocab: StringAttrib; } export type LinkRel = | "alternate" | "author" | "bookmark" | "canonical" | "dns-prefetch" | "external" | "help" | "icon" | "import" | "license" | "manifest" | "modulepreload" | "next" | "nofollow" | "noopener" | "noreferrer" | "opener" | "pingback" | "preconnect" | "prefetch" | "preload" | "prerender" | "prev" | "search" | "shortlink" | "stylesheet" | "tag"; /** * All CSS property names for auto-completion with `style` attrib. * * @remarks * Scraped from: https://developer.mozilla.org/en-US/docs/Web/CSS/Reference */ export type CSSProperty = | "align-content" | "align-items" | "align-self" | "all" | "animation" | "animation-delay" | "animation-direction" | "animation-duration" | "animation-fill-mode" | "animation-iteration-count" | "animation-name" | "animation-play-state" | "animation-timing-function" | "backdrop-filter" | "backface-visibility" | "background" | "background-attachment" | "background-blend-mode" | "background-clip" | "background-color" | "background-image" | "background-origin" | "background-position" | "background-repeat" | "background-size" | "block-size" | "border" | "border-block" | "border-block-color" | "border-block-end" | "border-block-end-color" | "border-block-end-style" | "border-block-end-width" | "border-block-start" | "border-block-start-color" | "border-block-start-style" | "border-block-start-width" | "border-block-style" | "border-block-width" | "border-bottom" | "border-bottom-color" | "border-bottom-left-radius" | "border-bottom-right-radius" | "border-bottom-style" | "border-bottom-width" | "border-collapse" | "border-color" | "border-end-end-radius" | "border-end-start-radius" | "border-image" | "border-image-outset" | "border-image-repeat" | "border-image-slice" | "border-image-source" | "border-image-width" | "border-inline" | "border-inline-color" | "border-inline-end" | "border-inline-end-color" | "border-inline-end-style" | "border-inline-end-width" | "border-inline-start" | "border-inline-start-color" | "border-inline-start-style" | "border-inline-start-width" | "border-inline-style" | "border-inline-width" | "border-left" | "border-left-color" | "border-left-style" | "border-left-width" | "border-radius" | "border-right" | "border-right-color" | "border-right-style" | "border-right-width" | "border-spacing" | "border-start-end-radius" | "border-start-start-radius" | "border-style" | "border-top" | "border-top-color" | "border-top-left-radius" | "border-top-right-radius" | "border-top-style" | "border-top-width" | "border-width" | "bottom" | "box-decoration-break" | "box-shadow" | "box-sizing" | "break-after" | "break-before" | "break-inside" | "caption-side" | "caret-color" | "clear" | "clip" | "clip-path" | "color" | "color-adjust" | "column-count" | "column-fill" | "column-gap" | "column-rule" | "column-rule-color" | "column-rule-style" | "column-rule-width" | "column-span" | "column-width" | "columns" | "contain" | "content" | "counter-increment" | "counter-reset" | "counter-set" | "cursor" | "direction" | "display" | "empty-cells" | "filter" | "flex" | "flex-basis" | "flex-direction" | "flex-flow" | "flex-grow" | "flex-shrink" | "flex-wrap" | "float" | "font" | "font-family" | "font-feature-settings" | "font-kerning" | "font-language-override" | "font-optical-sizing" | "font-size" | "font-size-adjust" | "font-stretch" | "font-style" | "font-synthesis" | "font-variant" | "font-variant-alternates" | "font-variant-caps" | "font-variant-east-asian" | "font-variant-ligatures" | "font-variant-numeric" | "font-variant-position" | "font-variation-settings" | "font-weight" | "gap" | "grid" | "grid-area" | "grid-auto-columns" | "grid-auto-flow" | "grid-auto-rows" | "grid-column" | "grid-column-end" | "grid-column-start" | "grid-gap" | "grid-row" | "grid-row-end" | "grid-row-start" | "grid-template" | "grid-template-areas" | "grid-template-columns" | "grid-template-rows" | "hanging-punctuation" | "height" | "hyphens" | "image-orientation" | "image-rendering" | "inline-size" | "inset" | "inset-block" | "inset-block-end" | "inset-block-start" | "inset-inline" | "inset-inline-end" | "inset-inline-start" | "isolation" | "justify-content" | "justify-items" | "justify-self" | "left" | "letter-spacing" | "line-break" | "line-height" | "list-style" | "list-style-image" | "list-style-position" | "list-style-type" | "margin" | "margin-block" | "margin-block-end" | "margin-block-start" | "margin-bottom" | "margin-inline" | "margin-inline-end" | "margin-inline-start" | "margin-left" | "margin-right" | "margin-top" | "mask" | "mask-border" | "mask-border-mode" | "mask-border-outset" | "mask-border-repeat" | "mask-border-slice" | "mask-border-source" | "mask-border-width" | "mask-clip" | "mask-composite" | "mask-image" | "mask-mode" | "mask-origin" | "mask-position" | "mask-repeat" | "mask-size" | "mask-type" | "max-block-size" | "max-height" | "max-inline-size" | "max-width" | "min-block-size" | "min-height" | "min-inline-size" | "min-width" | "mix-blend-mode" | "object-fit" | "object-position" | "offset" | "offset-anchor" | "offset-distance" | "offset-path" | "offset-rotate" | "opacity" | "order" | "orphans" | "outline" | "outline-color" | "outline-offset" | "outline-style" | "outline-width" | "overflow" | "overflow-anchor" | "overflow-block" | "overflow-inline" | "overflow-wrap" | "overflow-x" | "overflow-y" | "overscroll-behavior" | "overscroll-behavior-block" | "overscroll-behavior-inline" | "overscroll-behavior-x" | "overscroll-behavior-y" | "padding" | "padding-block" | "padding-block-end" | "padding-block-start" | "padding-bottom" | "padding-inline" | "padding-inline-end" | "padding-inline-start" | "padding-left" | "padding-right" | "padding-top" | "page-break-after" | "page-break-before" | "page-break-inside" | "paint-order" | "perspective" | "perspective-origin" | "place-content" | "place-items" | "place-self" | "pointer-events" | "position" | "quotes" | "resize" | "right" | "rotate" | "row-gap" | "scale" | "scroll-behavior" | "scroll-margin" | "scroll-margin-block" | "scroll-margin-block-end" | "scroll-margin-block-start" | "scroll-margin-bottom" | "scroll-margin-inline" | "scroll-margin-inline-end" | "scroll-margin-inline-start" | "scroll-margin-left" | "scroll-margin-right" | "scroll-margin-top" | "scroll-padding" | "scroll-padding-block" | "scroll-padding-block-end" | "scroll-padding-block-start" | "scroll-padding-bottom" | "scroll-padding-inline" | "scroll-padding-inline-end" | "scroll-padding-inline-start" | "scroll-padding-left" | "scroll-padding-right" | "scroll-padding-top" | "scroll-snap-align" | "scroll-snap-stop" | "scroll-snap-type" | "scrollbar-color" | "scrollbar-width" | "shape-image-threshold" | "shape-margin" | "shape-outside" | "tab-size" | "table-layout" | "text-align" | "text-align-last" | "text-combine-upright" | "text-decoration" | "text-decoration-color" | "text-decoration-line" | "text-decoration-skip-ink" | "text-decoration-style" | "text-decoration-thickness" | "text-emphasis" | "text-emphasis-color" | "text-emphasis-position" | "text-emphasis-style" | "text-indent" | "text-justify" | "text-orientation" | "text-overflow" | "text-rendering" | "text-shadow" | "text-transform" | "text-underline-offset" | "text-underline-position" | "top" | "touch-action" | "transform" | "transform-box" | "transform-origin" | "transform-style" | "transition" | "transition-delay" | "transition-duration" | "transition-property" | "transition-timing-function" | "translate" | "turn" | "unicode-bidi" | "unset" | "vertical-align" | "visibility" | "white-space" | "widows" | "width" | "will-change" | "word-break" | "word-spacing" | "word-wrap" | "writing-mode" | "z-index"; /** * Additional CSS properties for SVG elements. * * @remarks * Reference: * * - https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/Presentation * - https://css-tricks.com/svg-properties-and-css/ */ export type CSSSVGProperty = | "alignment-baseline" | "baseline-shift" | "clip" | "clip-path" | "clip-rule" | "color-interpolation" | "color-interpolation-filters" | "color-profile" | "color-rendering" | "cursor" | "d" | "direction" | "display" | "dominant-baseline" | "enable-background" | "fill" | "fill-opacity" | "fill-rule" | "filter" | "flood-color" | "flood-opacity" | "font-family" | "font-size" | "font-size-adjust" | "font-stretch" | "font-variant" | "font-weight" | "glyph-orientation-horizontal" | "glyph-orientation-vertical" | "image-rendering" | "kerning" | "letter-spacing" | "lighting-color" | "marker" | "marker-end" | "marker-mid" | "marker-start" | "mask" | "opacity" | "overflow" | "pointer-events" | "shape-rendering" | "solid-color" | "solid-opacity" | "stop-color" | "stop-opacity" | "stroke" | "stroke-dasharray" | "stroke-dashoffset" | "stroke-linecap" | "stroke-linejoin" | "stroke-miterlimit" | "stroke-opacity" | "stroke-width" | "text-anchor" | "text-decoration" | "text-rendering" | "transform" | "unicode-bidi" | "vector-effect" | "visibility" | "word-spacing" | "writing-mode"; export interface Attribs extends GlobalEventAttribs, MicroformatAttribs, RDFaAttribs { accesskey: StringAttrib; autocapitalize: AttribVal< "off" | "on" | "sentences" | "words" | "characters" >; class: AttribVal<string | IObjectOf<BooleanAttrib>>; contenteditable: BooleanAttrib; data: IObjectOf<AttribVal<string | number | boolean>>; dir: AttribVal<"rtl" | "ltr">; draggable: BooleanAttrib; hidden: BooleanAttrib; id: StringAttrib; is: StringAttrib; lang: StringAttrib; scrollLeft: NumericAttrib; scrollTop: NumericAttrib; spellcheck: BooleanAttrib; style: AttribVal< | string | Partial< Record< CSSProperty | CSSSVGProperty, AttribVal<NumOrString | Fn<any, NumOrString>> > > >; tabindex: NumericAttrib; title: StringAttrib; translate: BooleanAttrib; [id: string]: any; } export interface CORSAttribs { crossorigin: AttribVal<"anonymous" | "use-credentials">; } export interface ReferrerAttribs { referrerpolicy: AttribVal<ReferrerPolicy>; } export interface ImportanceAttribs { importance: AttribVal<"high" | "low" | "auto">; } export interface RelAttribs extends Omit<Attribs, "rel"> { rel: AttribVal<LinkRel | LinkRel[]>; } export interface DimensionAttribs { width: NumericAttrib; height: NumericAttrib; } export interface LoadingAttribs { loading: AttribVal<"eager" | "lazy">; }
the_stack
'use strict'; import { Range } from 'vscode-languageclient'; import { LuaParse } from './LuaParse'; import { CLog } from './Utils' import { LuaFiledCompletionInfo } from "./provider/LuaFiledCompletionInfo"; /** * lua info */ export class LuaInfo { public moduleName: string; private comments: Array<LuaComment> = null; public type: LuaInfoType; public name: string; public aliasName: string = null;// 别名 public parent: LuaInfo; public isPointFun:boolean = false /**是否是多变量 */ public ismultipleVariables: boolean = false public localLuaInfo: Array<LuaInfo>; public params: Array<string>; public isValue: boolean = false; public value: LuaInfo; public multipleRoot: LuaInfo; /** : 的数量 */ public punctuatorNumber_1: number = 0; /** . 的数量 */ public punctuatorNumber_2: number = 0; /** [] 的数量 */ public punctuatorNumber_3: number = 0; /**用于table 第一次判断 , */ public tableIsFistItem: boolean = true; public bracket_Gs: Array<LuaInfo>; /**是否是包含在 [] 中的 */ public isBracket_G: boolean = false //==============================华丽的分割线 新版本用到的===================================== /**后置的二元运算符号 用于预判值的计算 */ public operatorToken: TokenInfo; /**一元数组 */ public unarys: Array<TokenInfo>; /**是否是局部变量 */ public isLocal = false; /** 所在文件 */ public filePath: string; /** . : 连接的下一个info */ private nextLuaInfo: LuaInfo; private upLuaInfo: LuaInfo; /**lua对应的值 */ public valueType: LuaInfoTypeValue; public isVar: boolean; public isAddToFiled: boolean = true public tableFileds: Array<LuaInfo>; public startToken: TokenInfo; public endToken: TokenInfo; public tableFiledType: number = 0; public isAnonymousFunction: boolean = false public isNextCheck: boolean = true; constructor(startToken: TokenInfo) { this.comments = new Array<LuaComment>(); this.isVar = false this.startToken = startToken; this.type = LuaInfoType.Field; this.localLuaInfo = new Array<LuaInfo>(); this.params = new Array<string>(); this.unarys = new Array<TokenInfo>(); this.tableFileds = new Array<LuaInfo>(); } public getNextLuaInfo() { return this.nextLuaInfo; } public getUpInfo() { return this.upLuaInfo; } public setNextLuaInfo(nextLuaInfo: LuaInfo) { this.nextLuaInfo = nextLuaInfo; nextLuaInfo.ismultipleVariables = this.ismultipleVariables nextLuaInfo.isLocal = this.isLocal nextLuaInfo.isVar = this.isValue; nextLuaInfo.upLuaInfo = this; nextLuaInfo.comments = this.comments; this.comments = null } public getTopLuaInfo(): LuaInfo { while (true) { CLog(); if (this.upLuaInfo) { return this.upLuaInfo.getTopLuaInfo(); } else { return this } } } public getLastLuaInfo(): LuaInfo { while (true) { CLog(); if (this.nextLuaInfo) { return this.nextLuaInfo.getLastLuaInfo(); } else { return this } } } public setEndToken(token: TokenInfo) { this.endToken = token; if (this.type == LuaInfoType.Table) { return; } LuaParse.lp.luaInfoManager.addCompletionItem(this, token) // LuaParse.lp.luaInfoManager.addFiledLuaInfo(this,token); // this.endToken = token; // var tokens:Array<TokenInfo> = LuaParse.lp.tokens; // var startIndex:number =this.startToken.range.start; // var endIndex:number = this.endToken.range.end; // var input = LuaParse.lp.lpt.input; // var name = input.substr(startIndex,endIndex-startIndex) // this.filePath = LuaParse.filePath; // this.moduleName = this.filePath.substring(0, this.filePath.lastIndexOf('.lua')) // var varName1 = ""; // var varName2 = ""; // if(this.startToken.index == this.endToken.index) // { // if(this.startToken.type == TokenTypes.BooleanLiteral || // this.startToken.type == TokenTypes.NumericLiteral || // this.startToken.type == TokenTypes.VarargLiteral // ){ // return; // } // } // // var currentFunctionLuaInfo:LuaInfo = LuaParse.lp.getCurrentFunctionLuaInfo(); // var isLocal =false; // var isFunction = false; // var startIndex:number = this.startToken.index // for(var i = startIndex;i <= this.endToken.index;i++) // { // //获取初始 // var token:TokenInfo =tokens[i]; // if(LuaParse.lp.consume('local',token,TokenTypes.Keyword)) // { // isLocal = true // continue; // } // if(LuaParse.lp.consume('function',token,TokenTypes.Keyword)) // { // isFunction = true // continue; // } // if(LuaParse.lp.consume('[',token,TokenTypes.Punctuator) && this.endToken.index >= i+2 ) // { // var token1:TokenInfo = tokens[i+1] // var token2:TokenInfo = tokens[i+2] // if(token1.type == TokenTypes.StringLiteral && // LuaParse.lp.consume(']',token2,TokenTypes.Punctuator)) // { // var x = parseInt(token1.value); // if(isNaN(parseInt(token1.value))) // { // varName1 += "[\""+ token1.value +"\"]" // varName2 += "."+token1.value; // i+=2; // continue; // }else // { // i+=2; // varName1 += "[\""+ token1.value +"\"]" // varName2 += "[\""+ token1.value +"\"]" // continue; // } // } // } // if(token.type == TokenTypes.StringLiteral) // { // var value = "\""+ token.value + "\""; // varName1 += value; // varName2 += value // }else // { // varName1 += token.value; // varName2 += token.value; // } // } // console.log(varName1) // this.name = varName1; // if(varName1 == varName2) { // console.log("name1:" + varName1) // }else // { // console.log("name1:" + varName1) // console.log("name2:" + varName2) // } } /** * 添加参数名 */ public addParam(param): number { //需要检查是否有重复的参数名 for (var i = 0; i < this.params.length; i++) { if (this.params[i] === param) { return i + 1; } } this.params.push(param); return -1; } public setComments(comments: Array<LuaComment>) { this.comments = this.comments.concat(comments) } public getComments(): Array<LuaComment> { return this.comments; } } export enum LuaInfoType { /** 字段 */ Field = 1, /** Table */ Table = 2, /** 方法 function xxx */ Function = 3, /**模块方法function xx:xxx() end */ moduleFunction = 5, /**参数 */ Param = 6, /**匿名函数 */ AnonymousFunction = 7, /** for 循环 number */ FOR_I = 8, /** for 循环 pairs */ FOR_PAIRS = 9, FunctionCall1, /**返回值 */ RETURN = 11, WHILE = 12, ROOT = 13, IF = 14, ELSEIF = 15, ELSE = 16, Number, BOOLEAN, STRING, NIL, Vararg, Bracket_M } /** * 提示 */ export class LuaComment { constructor(content, range: Range, isLong: boolean) { this.content = content; this.range = range; this.isLong = isLong; } //1 短注释 //2 长注释 public isLong: boolean = false; public content: string = null; public range: Range = null; } export class TokenInfo { public type: TokenTypes = TokenTypes.EOF; public value: any = '<eof>'; public line: number = 0; public lineStart: number = 0; public nextToken:TokenInfo; public range: LuaRange = null; public error: LuaError = null; public index: number; public delimiter: string = null; public enddelimiter: string = null; public comments: Array<LuaComment>; public aftecomments: Array<LuaComment>; constructor() { this.comments = new Array<LuaComment>(); } public addAfterComment(comment: LuaComment) { if (this.aftecomments == null) { this.aftecomments = new Array<LuaComment>(); } this.aftecomments.push(comment); } public addComment(comment: LuaComment): void { this.comments.push(comment); } } export class LuaRange { public start: number; public end: number; constructor(start: number, end: number) { this.start = start; this.end = end; } } export enum TokenTypes { EOF = 1, StringLiteral = 2, Keyword = 3, Identifier = 4,//标示符 NumericLiteral = 5, Punctuator = 6,//标点符号 BooleanLiteral = 7, NilLiteral = 8, VarargLiteral = 9, Wrap = 10, Tab = 11 } export enum LuaErrorEnum { unexpected, expected, unfinishedString,//未完成的字符串 malformedNumber, invalidVar, expectedToken, unoperator, //不合法的运算符 } export class LuaError { public type: LuaErrorEnum; public msg: string; public constructor(type: LuaErrorEnum, msg: string) { this.type = type; this.msg = msg; } } export enum LuaInfoTypeValue { NUMBER, BOOL, STRING, ANY, NIL, Table, Function }
the_stack
import { serializeError, deserializeError, createCustomErrorClass, addCustomErrorDeserializer, } from "./helpers"; export { serializeError, deserializeError, createCustomErrorClass, addCustomErrorDeserializer, }; export const AccountNameRequiredError = createCustomErrorClass( "AccountNameRequired" ); export const AccountNotSupported = createCustomErrorClass( "AccountNotSupported" ); export const AmountRequired = createCustomErrorClass("AmountRequired"); export const BluetoothRequired = createCustomErrorClass("BluetoothRequired"); export const BtcUnmatchedApp = createCustomErrorClass("BtcUnmatchedApp"); export const CantOpenDevice = createCustomErrorClass("CantOpenDevice"); export const CashAddrNotSupported = createCustomErrorClass( "CashAddrNotSupported" ); export const CurrencyNotSupported = createCustomErrorClass( "CurrencyNotSupported" ); export const DeviceAppVerifyNotSupported = createCustomErrorClass( "DeviceAppVerifyNotSupported" ); export const DeviceGenuineSocketEarlyClose = createCustomErrorClass( "DeviceGenuineSocketEarlyClose" ); export const DeviceNotGenuineError = createCustomErrorClass("DeviceNotGenuine"); export const DeviceOnDashboardExpected = createCustomErrorClass( "DeviceOnDashboardExpected" ); export const DeviceOnDashboardUnexpected = createCustomErrorClass( "DeviceOnDashboardUnexpected" ); export const DeviceInOSUExpected = createCustomErrorClass( "DeviceInOSUExpected" ); export const DeviceHalted = createCustomErrorClass("DeviceHalted"); export const DeviceNameInvalid = createCustomErrorClass("DeviceNameInvalid"); export const DeviceSocketFail = createCustomErrorClass("DeviceSocketFail"); export const DeviceSocketNoBulkStatus = createCustomErrorClass( "DeviceSocketNoBulkStatus" ); export const DisconnectedDevice = createCustomErrorClass("DisconnectedDevice"); export const DisconnectedDeviceDuringOperation = createCustomErrorClass( "DisconnectedDeviceDuringOperation" ); export const EnpointConfigError = createCustomErrorClass("EnpointConfig"); export const EthAppPleaseEnableContractData = createCustomErrorClass( "EthAppPleaseEnableContractData" ); export const FeeEstimationFailed = createCustomErrorClass( "FeeEstimationFailed" ); export const FirmwareNotRecognized = createCustomErrorClass( "FirmwareNotRecognized" ); export const HardResetFail = createCustomErrorClass("HardResetFail"); export const InvalidXRPTag = createCustomErrorClass("InvalidXRPTag"); export const InvalidAddress = createCustomErrorClass("InvalidAddress"); export const InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass( "InvalidAddressBecauseDestinationIsAlsoSource" ); export const LatestMCUInstalledError = createCustomErrorClass( "LatestMCUInstalledError" ); export const UnknownMCU = createCustomErrorClass("UnknownMCU"); export const LedgerAPIError = createCustomErrorClass("LedgerAPIError"); export const LedgerAPIErrorWithMessage = createCustomErrorClass( "LedgerAPIErrorWithMessage" ); export const LedgerAPINotAvailable = createCustomErrorClass( "LedgerAPINotAvailable" ); export const ManagerAppAlreadyInstalledError = createCustomErrorClass( "ManagerAppAlreadyInstalled" ); export const ManagerAppRelyOnBTCError = createCustomErrorClass( "ManagerAppRelyOnBTC" ); export const ManagerAppDepInstallRequired = createCustomErrorClass( "ManagerAppDepInstallRequired" ); export const ManagerAppDepUninstallRequired = createCustomErrorClass( "ManagerAppDepUninstallRequired" ); export const ManagerDeviceLockedError = createCustomErrorClass( "ManagerDeviceLocked" ); export const ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass( "ManagerFirmwareNotEnoughSpace" ); export const ManagerNotEnoughSpaceError = createCustomErrorClass( "ManagerNotEnoughSpace" ); export const ManagerUninstallBTCDep = createCustomErrorClass( "ManagerUninstallBTCDep" ); export const NetworkDown = createCustomErrorClass("NetworkDown"); export const NoAddressesFound = createCustomErrorClass("NoAddressesFound"); export const NotEnoughBalance = createCustomErrorClass("NotEnoughBalance"); export const NotEnoughBalanceToDelegate = createCustomErrorClass( "NotEnoughBalanceToDelegate" ); export const NotEnoughBalanceInParentAccount = createCustomErrorClass( "NotEnoughBalanceInParentAccount" ); export const NotEnoughSpendableBalance = createCustomErrorClass( "NotEnoughSpendableBalance" ); export const NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass( "NotEnoughBalanceBecauseDestinationNotCreated" ); export const NoAccessToCamera = createCustomErrorClass("NoAccessToCamera"); export const NotEnoughGas = createCustomErrorClass("NotEnoughGas"); export const NotSupportedLegacyAddress = createCustomErrorClass( "NotSupportedLegacyAddress" ); export const GasLessThanEstimate = createCustomErrorClass( "GasLessThanEstimate" ); export const PasswordsDontMatchError = createCustomErrorClass( "PasswordsDontMatch" ); export const PasswordIncorrectError = createCustomErrorClass( "PasswordIncorrect" ); export const RecommendSubAccountsToEmpty = createCustomErrorClass( "RecommendSubAccountsToEmpty" ); export const RecommendUndelegation = createCustomErrorClass( "RecommendUndelegation" ); export const TimeoutTagged = createCustomErrorClass("TimeoutTagged"); export const UnexpectedBootloader = createCustomErrorClass( "UnexpectedBootloader" ); export const MCUNotGenuineToDashboard = createCustomErrorClass( "MCUNotGenuineToDashboard" ); export const RecipientRequired = createCustomErrorClass("RecipientRequired"); export const UnavailableTezosOriginatedAccountReceive = createCustomErrorClass( "UnavailableTezosOriginatedAccountReceive" ); export const UnavailableTezosOriginatedAccountSend = createCustomErrorClass( "UnavailableTezosOriginatedAccountSend" ); export const UpdateFetchFileFail = createCustomErrorClass( "UpdateFetchFileFail" ); export const UpdateIncorrectHash = createCustomErrorClass( "UpdateIncorrectHash" ); export const UpdateIncorrectSig = createCustomErrorClass("UpdateIncorrectSig"); export const UpdateYourApp = createCustomErrorClass("UpdateYourApp"); export const UserRefusedDeviceNameChange = createCustomErrorClass( "UserRefusedDeviceNameChange" ); export const UserRefusedAddress = createCustomErrorClass("UserRefusedAddress"); export const UserRefusedFirmwareUpdate = createCustomErrorClass( "UserRefusedFirmwareUpdate" ); export const UserRefusedAllowManager = createCustomErrorClass( "UserRefusedAllowManager" ); export const UserRefusedOnDevice = createCustomErrorClass( "UserRefusedOnDevice" ); // TODO rename because it's just for transaction refusal export const TransportOpenUserCancelled = createCustomErrorClass( "TransportOpenUserCancelled" ); export const TransportInterfaceNotAvailable = createCustomErrorClass( "TransportInterfaceNotAvailable" ); export const TransportRaceCondition = createCustomErrorClass( "TransportRaceCondition" ); export const TransportWebUSBGestureRequired = createCustomErrorClass( "TransportWebUSBGestureRequired" ); export const DeviceShouldStayInApp = createCustomErrorClass( "DeviceShouldStayInApp" ); export const WebsocketConnectionError = createCustomErrorClass( "WebsocketConnectionError" ); export const WebsocketConnectionFailed = createCustomErrorClass( "WebsocketConnectionFailed" ); export const WrongDeviceForAccount = createCustomErrorClass( "WrongDeviceForAccount" ); export const WrongAppForCurrency = createCustomErrorClass( "WrongAppForCurrency" ); export const ETHAddressNonEIP = createCustomErrorClass("ETHAddressNonEIP"); export const CantScanQRCode = createCustomErrorClass("CantScanQRCode"); export const FeeNotLoaded = createCustomErrorClass("FeeNotLoaded"); export const FeeRequired = createCustomErrorClass("FeeRequired"); export const FeeTooHigh = createCustomErrorClass("FeeTooHigh"); export const SyncError = createCustomErrorClass("SyncError"); export const PairingFailed = createCustomErrorClass("PairingFailed"); export const GenuineCheckFailed = createCustomErrorClass("GenuineCheckFailed"); export const LedgerAPI4xx = createCustomErrorClass("LedgerAPI4xx"); export const LedgerAPI5xx = createCustomErrorClass("LedgerAPI5xx"); export const FirmwareOrAppUpdateRequired = createCustomErrorClass( "FirmwareOrAppUpdateRequired" ); // db stuff, no need to translate export const NoDBPathGiven = createCustomErrorClass("NoDBPathGiven"); export const DBWrongPassword = createCustomErrorClass("DBWrongPassword"); export const DBNotReset = createCustomErrorClass("DBNotReset"); /** * TransportError is used for any generic transport errors. * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason. */ export function TransportError(message: string, id: string): void { this.name = "TransportError"; this.message = message; this.stack = new Error().stack; this.id = id; } TransportError.prototype = new Error(); addCustomErrorDeserializer( "TransportError", (e) => new TransportError(e.message, e.id) ); export const StatusCodes = { PIN_REMAINING_ATTEMPTS: 0x63c0, INCORRECT_LENGTH: 0x6700, MISSING_CRITICAL_PARAMETER: 0x6800, COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981, SECURITY_STATUS_NOT_SATISFIED: 0x6982, CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, INCORRECT_DATA: 0x6a80, NOT_ENOUGH_MEMORY_SPACE: 0x6a84, REFERENCED_DATA_NOT_FOUND: 0x6a88, FILE_ALREADY_EXISTS: 0x6a89, INCORRECT_P1_P2: 0x6b00, INS_NOT_SUPPORTED: 0x6d00, CLA_NOT_SUPPORTED: 0x6e00, TECHNICAL_PROBLEM: 0x6f00, OK: 0x9000, MEMORY_PROBLEM: 0x9240, NO_EF_SELECTED: 0x9400, INVALID_OFFSET: 0x9402, FILE_NOT_FOUND: 0x9404, INCONSISTENT_FILE: 0x9408, ALGORITHM_NOT_SUPPORTED: 0x9484, INVALID_KCV: 0x9485, CODE_NOT_INITIALIZED: 0x9802, ACCESS_CONDITION_NOT_FULFILLED: 0x9804, CONTRADICTION_SECRET_CODE_STATUS: 0x9808, CONTRADICTION_INVALIDATION: 0x9810, CODE_BLOCKED: 0x9840, MAX_VALUE_REACHED: 0x9850, GP_AUTH_FAILED: 0x6300, LICENSING: 0x6f42, HALTED: 0x6faa, }; export function getAltStatusMessage(code: number): string | undefined | null { switch (code) { // improve text of most common errors case 0x6700: return "Incorrect length"; case 0x6800: return "Missing critical parameter"; case 0x6982: return "Security not satisfied (dongle locked or have invalid access rights)"; case 0x6985: return "Condition of use not satisfied (denied by the user?)"; case 0x6a80: return "Invalid data received"; case 0x6b00: return "Invalid parameter received"; } if (0x6f00 <= code && code <= 0x6fff) { return "Internal error, please report"; } } /** * Error thrown when a device returned a non success status. * the error.statusCode is one of the `StatusCodes` exported by this library. */ export function TransportStatusError(statusCode: number): void { this.name = "TransportStatusError"; const statusText = Object.keys(StatusCodes).find((k) => StatusCodes[k] === statusCode) || "UNKNOWN_ERROR"; const smsg = getAltStatusMessage(statusCode) || statusText; const statusCodeStr = statusCode.toString(16); this.message = `Ledger device: ${smsg} (0x${statusCodeStr})`; this.stack = new Error().stack; this.statusCode = statusCode; this.statusText = statusText; } TransportStatusError.prototype = new Error(); addCustomErrorDeserializer( "TransportStatusError", (e) => new TransportStatusError(e.statusCode) );
the_stack
import $ from "jquery"; import type { Coordmap } from "./initCoordmap"; import { findOrigin } from "./initCoordmap"; import { equal, isnan, mapValues, roundSignif } from "../utils"; import type { Panel } from "./initPanelScales"; import type { Offset } from "./findbox"; import { findBox } from "./findbox"; import { shiftToRange } from "./shiftToRange"; type Bounds = { xmin: number; xmax: number; ymin: number; ymax: number; }; type BoundsCss = Bounds; type BoundsData = Bounds; type ImageState = { brushing?: boolean; dragging?: boolean; resizing?: boolean; // Offset of last mouse down and up events (in CSS pixels) down?: Offset; up?: Offset; // Which side(s) we're currently resizing resizeSides?: { left: boolean; right: boolean; top: boolean; bottom: boolean; }; boundsCss?: BoundsCss; boundsData?: BoundsData; // Panel object that the brush is in panel?: Panel; // The bounds at the start of a drag/resize (in CSS pixels) changeStartBounds?: Bounds; }; type BrushOpts = { brushDirection: "x" | "xy" | "y"; brushClip: boolean; brushFill: string; brushOpacity: string; brushStroke: string; brushDelayType?: "debounce" | "throttle"; brushDelay?: number; brushResetOnNew?: boolean; }; type Brush = { reset: () => void; importOldBrush: () => void; isInsideBrush: (offsetCss: Offset) => boolean; isInResizeArea: (offsetCss: Offset) => boolean; whichResizeSides: (offsetCss: Offset) => ImageState["resizeSides"]; // A callback when the wrapper div or img is resized. onResize: () => void; // TODO define this type as both a getter and a setter interfaces. // boundsCss: (boxCss: BoundsCss) => void; // boundsCss: () => BoundsCss; boundsCss: { (boxCss: BoundsCss): void; (): BoundsCss; }; boundsData: { (boxData: BoundsData): void; (): BoundsData; }; getPanel: () => ImageState["panel"]; down: { (): ImageState["down"]; (offsetCss): void; }; up: { (): ImageState["up"]; (offsetCss): void; }; isBrushing: () => ImageState["brushing"]; startBrushing: () => void; brushTo: (offsetCss: Offset) => void; stopBrushing: () => void; isDragging: () => ImageState["dragging"]; startDragging: () => void; dragTo: (offsetCss: Offset) => void; stopDragging: () => void; isResizing: () => ImageState["resizing"]; startResizing: () => void; resizeTo: (offsetCss: Offset) => void; stopResizing: () => void; }; // Returns an object that represents the state of the brush. This gets wrapped // in a brushHandler, which provides various event listeners. function createBrush( $el: JQuery<HTMLElement>, opts: BrushOpts, coordmap: Coordmap, expandPixels: number ): Brush { // Number of pixels outside of brush to allow start resizing const resizeExpand = 10; const el = $el[0]; let $div = null; // The div representing the brush const state: ImageState = {}; // Aliases for conciseness const cssToImg = coordmap.scaleCssToImg; const imgToCss = coordmap.scaleImgToCss; reset(); function reset() { // Current brushing/dragging/resizing state state.brushing = false; state.dragging = false; state.resizing = false; // Offset of last mouse down and up events (in CSS pixels) state.down = { x: NaN, y: NaN }; state.up = { x: NaN, y: NaN }; // Which side(s) we're currently resizing state.resizeSides = { left: false, right: false, top: false, bottom: false, }; // Bounding rectangle of the brush, in CSS pixel and data dimensions. We // need to record data dimensions along with pixel dimensions so that when // a new plot is sent, we can re-draw the brush div with the appropriate // coords. state.boundsCss = { xmin: NaN, xmax: NaN, ymin: NaN, ymax: NaN, }; state.boundsData = { xmin: NaN, xmax: NaN, ymin: NaN, ymax: NaN, }; // Panel object that the brush is in state.panel = null; // The bounds at the start of a drag/resize (in CSS pixels) state.changeStartBounds = { xmin: NaN, xmax: NaN, ymin: NaN, ymax: NaN, }; if ($div) $div.remove(); } // If there's an existing brush div, use that div to set the new brush's // settings, provided that the x, y, and panel variables have the same names, // and there's a panel with matching panel variable values. function importOldBrush() { const oldDiv = $el.find("#" + el.id + "_brush"); if (oldDiv.length === 0) return; const oldBoundsData = oldDiv.data("bounds-data"); const oldPanel = oldDiv.data("panel"); if (!oldBoundsData || !oldPanel) return; // Find a panel that has matching vars; if none found, we can't restore. // The oldPanel and new panel must match on their mapping vars, and the // values. for (let i = 0; i < coordmap.panels.length; i++) { const curPanel = coordmap.panels[i]; if ( equal(oldPanel.mapping, curPanel.mapping) && equal(oldPanel.panel_vars, curPanel.panel_vars) ) { // We've found a matching panel state.panel = coordmap.panels[i]; break; } } // If we didn't find a matching panel, remove the old div and return if (state.panel === null) { oldDiv.remove(); return; } $div = oldDiv; boundsData(oldBoundsData); updateDiv(); } // This will reposition the brush div when the image is resized, maintaining // the same data coordinates. Note that the "resize" here refers to the // wrapper div/img being resized; elsewhere, "resize" refers to the brush // div being resized. function onResize() { const boundsDataVal = boundsData(); // Check to see if we have valid boundsData for (const val in boundsDataVal) { if (isnan(boundsDataVal[val])) return; } boundsData(boundsDataVal); updateDiv(); } // Return true if the offset is inside min/max coords function isInsideBrush(offsetCss) { const bounds = state.boundsCss; return ( offsetCss.x <= bounds.xmax && offsetCss.x >= bounds.xmin && offsetCss.y <= bounds.ymax && offsetCss.y >= bounds.ymin ); } // Return true if offset is inside a region to start a resize function isInResizeArea(offsetCss) { const sides = whichResizeSides(offsetCss); return sides.left || sides.right || sides.top || sides.bottom; } // Return an object representing which resize region(s) the cursor is in. function whichResizeSides(offsetCss) { const b = state.boundsCss; // Bounds with expansion const e = { xmin: b.xmin - resizeExpand, xmax: b.xmax + resizeExpand, ymin: b.ymin - resizeExpand, ymax: b.ymax + resizeExpand, }; const res = { left: false, right: false, top: false, bottom: false, }; if ( (opts.brushDirection === "xy" || opts.brushDirection === "x") && offsetCss.y <= e.ymax && offsetCss.y >= e.ymin ) { if (offsetCss.x < b.xmin && offsetCss.x >= e.xmin) res.left = true; else if (offsetCss.x > b.xmax && offsetCss.x <= e.xmax) res.right = true; } if ( (opts.brushDirection === "xy" || opts.brushDirection === "y") && offsetCss.x <= e.xmax && offsetCss.x >= e.xmin ) { if (offsetCss.y < b.ymin && offsetCss.y >= e.ymin) res.top = true; else if (offsetCss.y > b.ymax && offsetCss.y <= e.ymax) res.bottom = true; } return res; } // Sets the bounds of the brush (in CSS pixels), given a box and optional // panel. This will fit the box bounds into the panel, so we don't brush // outside of it. This knows whether we're brushing in the x, y, or xy // directions, and sets bounds accordingly. If no box is passed in, just // return current bounds. function boundsCss(): ImageState["boundsCss"]; function boundsCss(boxCss: BoundsCss): void; function boundsCss(boxCss?: BoundsCss) { if (boxCss === undefined) { return $.extend({}, state.boundsCss); } let minCss = { x: boxCss.xmin, y: boxCss.ymin }; let maxCss = { x: boxCss.xmax, y: boxCss.ymax }; const panel = state.panel; const panelBoundsImg = panel.range; if (opts.brushClip) { minCss = imgToCss(panel.clipImg(cssToImg(minCss))); maxCss = imgToCss(panel.clipImg(cssToImg(maxCss))); } if (opts.brushDirection === "xy") { // No change } else if (opts.brushDirection === "x") { // Extend top and bottom of plotting area minCss.y = imgToCss({ y: panelBoundsImg.top }).y; maxCss.y = imgToCss({ y: panelBoundsImg.bottom }).y; } else if (opts.brushDirection === "y") { minCss.x = imgToCss({ x: panelBoundsImg.left }).x; maxCss.x = imgToCss({ x: panelBoundsImg.right }).x; } state.boundsCss = { xmin: minCss.x, xmax: maxCss.x, ymin: minCss.y, ymax: maxCss.y, }; // Positions in data space const minData = state.panel.scaleImgToData(cssToImg(minCss)); const maxData = state.panel.scaleImgToData(cssToImg(maxCss)); // For reversed scales, the min and max can be reversed, so use findBox // to ensure correct order. state.boundsData = findBox(minData, maxData); // Round to 14 significant digits to avoid spurious changes in FP values // (#1634). state.boundsData = mapValues(state.boundsData, (val) => roundSignif(val, 14) ) as BoundsData; // We also need to attach the data bounds and panel as data attributes, so // that if the image is re-sent, we can grab the data bounds to create a new // brush. This should be fast because it doesn't actually modify the DOM. $div.data("bounds-data", state.boundsData); $div.data("panel", state.panel); return undefined; } // Get or set the bounds of the brush using coordinates in the data space. function boundsData(): ImageState["boundsData"]; function boundsData(boxData: Parameters<Panel["scaleDataToImg"]>[0]): void; function boundsData(boxData?: Parameters<Panel["scaleDataToImg"]>[0]) { if (boxData === undefined) { return $.extend({}, state.boundsData); } let boxCss = imgToCss(state.panel.scaleDataToImg(boxData)); // Round to 13 significant digits to avoid spurious changes in FP values // (#2197). boxCss = mapValues(boxCss, (val) => roundSignif(val, 13)); // The scaling function can reverse the direction of the axes, so we need to // find the min and max again. boundsCss({ xmin: Math.min(boxCss.xmin, boxCss.xmax), xmax: Math.max(boxCss.xmin, boxCss.xmax), ymin: Math.min(boxCss.ymin, boxCss.ymax), ymax: Math.max(boxCss.ymin, boxCss.ymax), }); return undefined; } function getPanel() { return state.panel; } // Add a new div representing the brush. function addDiv() { if ($div) $div.remove(); // Start hidden; we'll show it when movement occurs $div = $(document.createElement("div")) .attr("id", el.id + "_brush") .css({ "background-color": opts.brushFill, opacity: opts.brushOpacity, "pointer-events": "none", position: "absolute", }) .hide(); const borderStyle = "1px solid " + opts.brushStroke; if (opts.brushDirection === "xy") { $div.css({ border: borderStyle, }); } else if (opts.brushDirection === "x") { $div.css({ "border-left": borderStyle, "border-right": borderStyle, }); } else if (opts.brushDirection === "y") { $div.css({ "border-top": borderStyle, "border-bottom": borderStyle, }); } $el.append($div); $div.offset({ x: 0, y: 0 }).width(0).outerHeight(0); } // Update the brush div to reflect the current brush bounds. function updateDiv() { // Need parent offset relative to page to calculate mouse offset // relative to page. const imgOffsetCss = findOrigin($el.find("img")); const b = state.boundsCss; $div .offset({ top: imgOffsetCss.y + b.ymin, left: imgOffsetCss.x + b.xmin, }) .outerWidth(b.xmax - b.xmin + 1) .outerHeight(b.ymax - b.ymin + 1); } function down(offsetCss?: Offset) { if (offsetCss === undefined) return state.down; state.down = offsetCss; return undefined; } function up(offsetCss?: Offset) { if (offsetCss === undefined) return state.up; state.up = offsetCss; return undefined; } function isBrushing() { return state.brushing; } function startBrushing() { state.brushing = true; addDiv(); state.panel = coordmap.getPanelCss(state.down, expandPixels); boundsCss(findBox(state.down, state.down)); updateDiv(); } function brushTo(offsetCss: Offset) { boundsCss(findBox(state.down, offsetCss)); $div.show(); updateDiv(); } function stopBrushing() { state.brushing = false; // Save the final bounding box of the brush boundsCss(findBox(state.down, state.up)); } function isDragging() { return state.dragging; } function startDragging() { state.dragging = true; state.changeStartBounds = $.extend({}, state.boundsCss); } function dragTo(offsetCss: Offset) { // How far the brush was dragged const dx = offsetCss.x - state.down.x; const dy = offsetCss.y - state.down.y; // Calculate what new positions would be, before clipping. const start = state.changeStartBounds; let newBoundsCss = { xmin: start.xmin + dx, xmax: start.xmax + dx, ymin: start.ymin + dy, ymax: start.ymax + dy, }; // Clip to the plotting area if (opts.brushClip) { const panelBoundsImg = state.panel.range; const newBoundsImg = cssToImg(newBoundsCss); // Convert to format for shiftToRange let xvalsImg = [newBoundsImg.xmin, newBoundsImg.xmax]; let yvalsImg = [newBoundsImg.ymin, newBoundsImg.ymax]; xvalsImg = shiftToRange( xvalsImg, panelBoundsImg.left, panelBoundsImg.right ); yvalsImg = shiftToRange( yvalsImg, panelBoundsImg.top, panelBoundsImg.bottom ); // Convert back to bounds format newBoundsCss = imgToCss({ xmin: xvalsImg[0], xmax: xvalsImg[1], ymin: yvalsImg[0], ymax: yvalsImg[1], }); } boundsCss(newBoundsCss); updateDiv(); } function stopDragging() { state.dragging = false; } function isResizing() { return state.resizing; } function startResizing() { state.resizing = true; state.changeStartBounds = $.extend({}, state.boundsCss); state.resizeSides = whichResizeSides(state.down); } function resizeTo(offsetCss: Offset) { // How far the brush was dragged const dCss = { x: offsetCss.x - state.down.x, y: offsetCss.y - state.down.y, }; const dImg = cssToImg(dCss); // Calculate what new positions would be, before clipping. const bImg = cssToImg(state.changeStartBounds); const panelBoundsImg = state.panel.range; if (state.resizeSides.left) { const xminImg = shiftToRange( bImg.xmin + dImg.x, panelBoundsImg.left, bImg.xmax )[0]; bImg.xmin = xminImg; } else if (state.resizeSides.right) { const xmaxImg = shiftToRange( bImg.xmax + dImg.x, bImg.xmin, panelBoundsImg.right )[0]; bImg.xmax = xmaxImg; } if (state.resizeSides.top) { const yminImg = shiftToRange( bImg.ymin + dImg.y, panelBoundsImg.top, bImg.ymax )[0]; bImg.ymin = yminImg; } else if (state.resizeSides.bottom) { const ymaxImg = shiftToRange( bImg.ymax + dImg.y, bImg.ymin, panelBoundsImg.bottom )[0]; bImg.ymax = ymaxImg; } boundsCss(imgToCss(bImg)); updateDiv(); } function stopResizing() { state.resizing = false; } return { reset: reset, importOldBrush: importOldBrush, isInsideBrush: isInsideBrush, isInResizeArea: isInResizeArea, whichResizeSides: whichResizeSides, onResize: onResize, // A callback when the wrapper div or img is resized. boundsCss: boundsCss, boundsData: boundsData, getPanel: getPanel, down: down, up: up, isBrushing: isBrushing, startBrushing: startBrushing, brushTo: brushTo, stopBrushing: stopBrushing, isDragging: isDragging, startDragging: startDragging, dragTo: dragTo, stopDragging: stopDragging, isResizing: isResizing, startResizing: startResizing, resizeTo: resizeTo, stopResizing: stopResizing, }; } export { createBrush }; export type { Bounds, BrushOpts, BoundsCss };
the_stack
import Marketplace = require('../Marketplace'); import Page = require('../../../base/Page'); import Response = require('../../../http/response'); import serialize = require('../../../base/serialize'); import { InstalledAddOnExtensionList } from './installedAddOn/installedAddOnExtension'; import { InstalledAddOnExtensionListInstance } from './installedAddOn/installedAddOnExtension'; import { SerializableClass } from '../../../interfaces'; /** * Initialize the InstalledAddOnList * * PLEASE NOTE that this class contains preview products that are subject to * change. Use them with caution. If you currently do not have developer preview * access, please contact help@twilio.com. * * @param version - Version of the resource */ declare function InstalledAddOnList(version: Marketplace): InstalledAddOnListInstance; /** * Options to pass to update * * @property configuration - The JSON object representing the configuration * @property uniqueName - The string that uniquely identifies this Add-on installation */ interface InstalledAddOnInstanceUpdateOptions { configuration?: object; uniqueName?: string; } interface InstalledAddOnListInstance { /** * @param sid - sid of instance */ (sid: string): InstalledAddOnContext; /** * create a InstalledAddOnInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ create(opts: InstalledAddOnListInstanceCreateOptions, callback?: (error: Error | null, item: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance>; /** * Streams InstalledAddOnInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Function to process each record */ each(opts?: InstalledAddOnListInstanceEachOptions, callback?: (item: InstalledAddOnInstance, done: (err?: Error) => void) => void): void; /** * Constructs a installed_add_on * * @param sid - The unique Installed Add-on Sid */ get(sid: string): InstalledAddOnContext; /** * Retrieve a single target page of InstalledAddOnInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param targetUrl - API-generated URL for the requested results page * @param callback - Callback to handle list of records */ getPage(targetUrl?: string, callback?: (error: Error | null, items: InstalledAddOnPage) => any): Promise<InstalledAddOnPage>; /** * Lists InstalledAddOnInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ list(opts?: InstalledAddOnListInstanceOptions, callback?: (error: Error | null, items: InstalledAddOnInstance[]) => any): Promise<InstalledAddOnInstance[]>; /** * Retrieve a single page of InstalledAddOnInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ page(opts?: InstalledAddOnListInstancePageOptions, callback?: (error: Error | null, items: InstalledAddOnPage) => any): Promise<InstalledAddOnPage>; /** * Provide a user-friendly representation */ toJSON(): any; } /** * Options to pass to create * * @property acceptTermsOfService - A boolean reflecting your acceptance of the Terms of Service * @property availableAddOnSid - A string that uniquely identifies the Add-on to install * @property configuration - The JSON object representing the configuration * @property uniqueName - The string that uniquely identifies this Add-on installation */ interface InstalledAddOnListInstanceCreateOptions { acceptTermsOfService: boolean; availableAddOnSid: string; configuration?: object; uniqueName?: string; } /** * Options to pass to each * * @property callback - * Function to process each record. If this and a positional * callback are passed, this one will be used * @property done - Function to be called upon completion of streaming * @property limit - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) */ interface InstalledAddOnListInstanceEachOptions { callback?: (item: InstalledAddOnInstance, done: (err?: Error) => void) => void; done?: Function; limit?: number; pageSize?: number; } /** * Options to pass to list * * @property limit - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) */ interface InstalledAddOnListInstanceOptions { limit?: number; pageSize?: number; } /** * Options to pass to page * * @property pageNumber - Page Number, this value is simply for client state * @property pageSize - Number of records to return, defaults to 50 * @property pageToken - PageToken provided by the API */ interface InstalledAddOnListInstancePageOptions { pageNumber?: number; pageSize?: number; pageToken?: string; } interface InstalledAddOnPayload extends InstalledAddOnResource, Page.TwilioResponsePayload { } interface InstalledAddOnResource { account_sid: string; configuration: object; date_created: Date; date_updated: Date; description: string; friendly_name: string; links: string; sid: string; unique_name: string; url: string; } interface InstalledAddOnSolution { } declare class InstalledAddOnContext { /** * Initialize the InstalledAddOnContext * * PLEASE NOTE that this class contains preview products that are subject to * change. Use them with caution. If you currently do not have developer preview * access, please contact help@twilio.com. * * @param version - Version of the resource * @param sid - The unique Installed Add-on Sid */ constructor(version: Marketplace, sid: string); extensions: InstalledAddOnExtensionListInstance; /** * fetch a InstalledAddOnInstance * * @param callback - Callback to handle processed record */ fetch(callback?: (error: Error | null, items: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance>; /** * remove a InstalledAddOnInstance * * @param callback - Callback to handle processed record */ remove(callback?: (error: Error | null, items: InstalledAddOnInstance) => any): void; /** * Provide a user-friendly representation */ toJSON(): any; /** * update a InstalledAddOnInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ update(opts?: InstalledAddOnInstanceUpdateOptions, callback?: (error: Error | null, items: InstalledAddOnInstance) => any): Promise<InstalledAddOnInstance>; } declare class InstalledAddOnInstance extends SerializableClass { /** * Initialize the InstalledAddOnContext * * PLEASE NOTE that this class contains preview products that are subject to * change. Use them with caution. If you currently do not have developer preview * access, please contact help@twilio.com. * * @param version - Version of the resource * @param payload - The instance payload * @param sid - The unique Installed Add-on Sid */ constructor(version: Marketplace, payload: InstalledAddOnPayload, sid: string); private _proxy: InstalledAddOnContext; accountSid: string; configuration: object; dateCreated: Date; dateUpdated: Date; description: string; /** * Access the extensions */ extensions(): InstalledAddOnExtensionListInstance; /** * fetch a InstalledAddOnInstance * * @param callback - Callback to handle processed record */ fetch(callback?: (error: Error | null, items: InstalledAddOnInstance) => any): void; friendlyName: string; links: string; /** * remove a InstalledAddOnInstance * * @param callback - Callback to handle processed record */ remove(callback?: (error: Error | null, items: InstalledAddOnInstance) => any): void; sid: string; /** * Provide a user-friendly representation */ toJSON(): any; uniqueName: string; /** * update a InstalledAddOnInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ update(opts?: InstalledAddOnInstanceUpdateOptions, callback?: (error: Error | null, items: InstalledAddOnInstance) => any): void; url: string; } declare class InstalledAddOnPage extends Page<Marketplace, InstalledAddOnPayload, InstalledAddOnResource, InstalledAddOnInstance> { /** * Initialize the InstalledAddOnPage * * PLEASE NOTE that this class contains preview products that are subject to * change. Use them with caution. If you currently do not have developer preview * access, please contact help@twilio.com. * * @param version - Version of the resource * @param response - Response from the API * @param solution - Path solution */ constructor(version: Marketplace, response: Response<string>, solution: InstalledAddOnSolution); /** * Build an instance of InstalledAddOnInstance * * @param payload - Payload response from the API */ getInstance(payload: InstalledAddOnPayload): InstalledAddOnInstance; /** * Provide a user-friendly representation */ toJSON(): any; } export { InstalledAddOnContext, InstalledAddOnInstance, InstalledAddOnList, InstalledAddOnListInstance, InstalledAddOnListInstanceCreateOptions, InstalledAddOnListInstanceEachOptions, InstalledAddOnListInstanceOptions, InstalledAddOnListInstancePageOptions, InstalledAddOnPage, InstalledAddOnPayload, InstalledAddOnResource, InstalledAddOnSolution }
the_stack
import { createEmptyBlock } from '@app/helpers/blockFactory' import type { Operation, Transcation } from '@app/hooks/useCommit' import { BlockSnapshot, getBlockFromSnapshot } from '@app/store/block' import { Editor } from '@app/types' import { addPrefixToBlockTitle, blockIdGenerator } from '@app/utils' import dayjs from 'dayjs' import { dequal } from 'dequal' import { cloneDeep } from 'lodash' import { toast } from 'react-toastify' import invariant from 'tiny-invariant' export const createTranscation = ({ operations }: { operations: Operation[] }) => { return { id: blockIdGenerator(), operations } } export const getIndentionOperations = ( block: Editor.BaseBlock, previousBlock: Editor.BaseBlock, parentBlock: Editor.BaseBlock, blockIds: string[] ) => { const operations: Operation[] = [] const previousId = previousBlock.id let parentId = '' operations.push({ cmd: 'listRemove', table: 'block', id: block.parentId, args: { id: block.id }, path: ['children'] }) if (previousBlock.children?.length) { operations.push({ cmd: 'listAfter', table: 'block', id: previousId, args: { id: block.id, after: previousBlock.children[previousBlock.children.length - 1] }, path: ['children'] }) } else { operations.push({ cmd: 'listBefore', table: 'block', id: previousId, args: { id: block.id }, path: ['children'] }) } parentId = previousId // list other blocks after first block let afterId = block.id for (const afterBlockId of blockIds.slice(1)) { operations.push({ cmd: 'listRemove', table: 'block', id: parentBlock.id, args: { id: afterBlockId }, path: ['children'] }) operations.push({ cmd: 'listAfter', table: 'block', id: parentId, args: { id: afterBlockId, after: afterId }, path: ['children'] }) afterId = afterBlockId } return operations } export const getOutdentionOperations = (blockId: string, parentBlock: Editor.BaseBlock, blockIds: string[]) => { const operations: Operation[] = [] let parentId = '' operations.push({ cmd: 'listRemove', table: 'block', id: parentBlock.id, args: { id: blockId }, path: ['children'] }) operations.push({ cmd: 'listAfter', table: 'block', id: parentBlock.parentId, args: { id: blockId, after: parentBlock.id }, path: ['children'] }) parentId = parentBlock.parentId // list other blocks after first block let afterId = blockId for (const afterBlockId of blockIds.slice(1)) { operations.push({ cmd: 'listRemove', table: 'block', id: parentBlock.id, args: { id: afterBlockId }, path: ['children'] }) operations.push({ cmd: 'listAfter', table: 'block', id: parentId, args: { id: afterBlockId, after: afterId }, path: ['children'] }) afterId = afterBlockId } return operations } export const findPreviouseBlock = ( blockId: string, parentBlockId: string, blockIds: string[], snapshot: BlockSnapshot ) => { const parentBlock = getBlockFromSnapshot(parentBlockId, snapshot) const peerBlockIds = parentBlock.children! const sourceIndex = peerBlockIds.findIndex((id) => id === blockId) if (sourceIndex !== undefined && sourceIndex >= 1 && blockIds.every((id) => parentBlock.children?.includes(id))) { const previousId = peerBlockIds[sourceIndex - 1] const previousBlock = getBlockFromSnapshot(previousId, snapshot) return previousBlock } } export const canOutdention = (parentBlock: Editor.BaseBlock, blockIds: string[]) => { return ( blockIds.every((id) => parentBlock.children?.includes(id)) && (parentBlock.type === Editor.BlockType.Story || parentBlock.type === Editor.BlockType.Thought) === false ) } export const getDuplicatedBlocksFragment = ( children: string[], data: Record<string, Editor.BaseBlock>, storyId: string | undefined, parentId: string | undefined, blockMapping: Record<string, string> = {} ) => { let result: Record<string, Editor.BaseBlock> = {} children.forEach((currentId) => { const currentBlock = data[currentId] const newId = blockIdGenerator() const fragment = getDuplicatedBlocksFragment(currentBlock.children ?? [], data, storyId, newId, blockMapping) let newBlock = null if (currentBlock.type === Editor.BlockType.Visualization) { const vizBlock = currentBlock as Editor.VisualizationBlock newBlock = createEmptyBlock<Editor.VisualizationBlock>({ type: vizBlock.type, id: newId, storyId, parentId: parentId, content: { ...vizBlock.content, fromQueryId: vizBlock.content?.queryId, queryId: vizBlock.content?.queryId ? blockMapping[vizBlock.content.queryId] ?? vizBlock.content?.queryId : undefined }, children: fragment.children, format: vizBlock.format }) } else { newBlock = createEmptyBlock({ type: currentBlock.type, id: newId, storyId, parentId: parentId, content: currentBlock.content, children: fragment.children, format: currentBlock.format }) } result[newId] = newBlock result = { ...result, ...fragment.data } blockMapping[currentId] = newId }) return { children: children.map((id) => blockMapping[id]), data: result } } export const getDuplicatedBlocks = ( blocks: Editor.BaseBlock[], storyId: string, snapshot: BlockSnapshot, resourceMapping?: Record<string, string> ) => { const duplicatedBlocks = blocks.map((block) => { if (block.type === Editor.BlockType.Visualization) { const fragBlock = block as Editor.VisualizationBlock const originalQueryId = fragBlock.content?.queryId if (originalQueryId) { const queryBlock = getBlockFromSnapshot(originalQueryId, snapshot) const isStoryQuery = queryBlock.storyId === block.storyId if (isStoryQuery && resourceMapping && resourceMapping[originalQueryId] === undefined) { const newId = blockIdGenerator() resourceMapping[originalQueryId] = newId } } const newId = originalQueryId ? resourceMapping?.[originalQueryId] ?? originalQueryId : undefined return createEmptyBlock<Editor.VisualizationBlock>({ type: fragBlock.type, storyId, parentId: storyId, content: { ...fragBlock.content, queryId: newId, fromQueryId: originalQueryId }, children: [], format: fragBlock.format }) } else { const fragBlock = block const newBlock = createEmptyBlock({ type: fragBlock.type, storyId, parentId: storyId, content: fragBlock.content, children: fragBlock.children, format: fragBlock.format }) if (resourceMapping?.[fragBlock.id]) { newBlock.id = resourceMapping[fragBlock.id] } return newBlock } }) return duplicatedBlocks } export const insertBlockAfterTranscation = ({ block, after }: { block: Editor.BaseBlock; after?: string }) => { return createTranscation({ operations: [ { cmd: 'set', id: block.id, path: [], args: block, table: 'block' }, after ? { cmd: 'listAfter', id: block.parentId, path: ['children'], table: 'block', args: { id: block.id, after: after } } : { cmd: 'listBefore', id: block.parentId, path: ['children'], table: 'block', args: { id: block.id } } ] }) } export const addInsertBlockOperations = ( blockIds: string[], targetParentBlockId: string, targetStoryId: string, operations: Operation[], snapshot: BlockSnapshot, resourceMapping?: Record<string, string> ) => { // const block = getBlockFromGlobalStore(blockId) const blocks = blockIds.map((id) => getBlockFromSnapshot(id, snapshot)) const duplicatedBlocks = getDuplicatedBlocks(blocks, targetStoryId, snapshot, resourceMapping) let afterId = '' for (let i = 0; i < duplicatedBlocks.length; i++) { const block = duplicatedBlocks[i] if (!block) { toast.error('block is null') } invariant(block, 'block is null') operations.push({ cmd: 'set', id: block.id, path: [], args: { ...block, parentId: targetParentBlockId, children: [] }, table: 'block' }) if (!afterId) { operations.push({ cmd: 'listBefore', id: targetParentBlockId, args: { id: block.id }, table: 'block', path: ['children'] }) } else { operations.push({ cmd: 'listAfter', id: targetParentBlockId, args: { id: block.id, after: afterId }, table: 'block', path: ['children'] }) } afterId = block.id addInsertBlockOperations(blocks[i].children ?? [], block.id, targetStoryId, operations, snapshot, resourceMapping) } return operations } export const duplicateStoryTranscation = ({ storyId, snapshot, newStoryId, wroskapceId }: { storyId: string snapshot: BlockSnapshot newStoryId: string wroskapceId: string }) => { const operations: Operation[] = [] const story = getBlockFromSnapshot(storyId, snapshot) const resourceMapping: Record<string, string> = {} operations.push({ cmd: 'set', id: newStoryId, path: [], args: createEmptyBlock({ id: newStoryId, alive: true, parentId: wroskapceId, parentTable: Editor.BlockParentType.WORKSPACE, content: { ...story.content, title: addPrefixToBlockTitle(story.content?.title, 'copy of ') }, children: [], type: Editor.BlockType.Story, storyId: newStoryId, format: { ...story.format }, permissions: [{ role: 'manager', type: 'workspace' }] }), table: 'block' }) addInsertBlockOperations(story.children ?? [], newStoryId, newStoryId, operations, snapshot, resourceMapping) // blocks.push(story) const transcation = createTranscation({ operations }) return transcation as Transcation } export const removeBlocksOperations = (targetBlocks: Editor.Block[], storyId: string) => { const operations: Operation[] = [] targetBlocks.forEach((targetBlock) => { operations.push( ...[ { cmd: 'listRemove', id: targetBlock.parentId, path: ['children'], args: { id: targetBlock.id }, table: 'block' } ] ) if (storyId === targetBlock.storyId) { operations.push({ cmd: 'update', id: targetBlock.id, path: ['alive'], args: false, table: 'block' }) } }) return operations } export const insertBlocksAndMoveOperations = ({ blocksFragment, targetBlock, storyId, direction, path = 'children' }: { blocksFragment: { children: string[]; data: Record<string, Editor.BaseBlock> } targetBlock: Editor.Block storyId: string direction: 'top' | 'left' | 'bottom' | 'right' | 'child' path?: 'children' }) => { const operations: Operation[] = [] const insertedBlocks = Object.values(blocksFragment.data) for (const block of insertedBlocks) { operations.push({ cmd: 'set', id: block.id, path: [], args: block, table: 'block' }) } operations.push( ...moveBlocksTranscation({ sourceBlockFragment: blocksFragment, targetBlock: targetBlock, storyId, direction, deleteSourceBlock: false, path }).operations ) return operations } export const createThoughtTranscation = ({ id, workspaceId, userId }: { id: string workspaceId: string userId: string }) => { return createTranscation({ operations: [ { cmd: 'set', id: id, path: [], table: 'block', args: { id: id, alive: true, parentId: workspaceId, // workspaceId parentTable: 'workspace', content: { date: dayjs().format('YYYY-MM-DD') }, children: [], permissions: [{ role: 'manager', type: 'user', id: userId }], type: 'thought', storyId: id, version: 0 } } ] }) } export const moveBlocksTranscation = ({ sourceBlockFragment, targetBlock, storyId, direction, deleteSourceBlock = true, path = 'children' }: { sourceBlockFragment: { children: string[]; data: Record<string, Editor.Block> } targetBlock: Editor.Block storyId: string direction: 'top' | 'left' | 'bottom' | 'right' | 'child' deleteSourceBlock: boolean path?: 'children' }) => { const operations: Operation[] = [] const leadingSourceBlockId = sourceBlockFragment.children[0]! const leadingSourceBlock = sourceBlockFragment.data[leadingSourceBlockId] const targetBlockId = targetBlock.id if (leadingSourceBlockId === targetBlockId) { invariant(false, 'illegal moveBlocksTranscation') } let newSourceBlockParentId: string | null = null if (direction === 'top' || direction === 'bottom') { deleteSourceBlock && operations.push( ...[ { cmd: 'listRemove', id: leadingSourceBlock.parentId, path: [path], args: { id: leadingSourceBlockId }, table: 'block' } ] ) if (direction === 'top') { operations.push( ...[ { cmd: 'listBefore', id: targetBlock.parentId, args: { id: leadingSourceBlockId, before: targetBlockId }, table: 'block', path: [path] } ] ) // targetParentBlock.children!.splice(targetIndex, 0, sourceBlock.id) } else if (direction === 'bottom') { operations.push( ...[ { cmd: 'listAfter', id: targetBlock.parentId, args: { id: leadingSourceBlockId, after: targetBlockId }, table: 'block', path: [path] } ] ) // targetParentBlock.children!.splice(targetIndex + 1, 0, sourceBlock.id) } newSourceBlockParentId = targetBlock.parentId // sourceBlock.parentId = targetParentBlock.id } else if (direction === 'left' || direction === 'right') { if (targetBlock.type === Editor.BlockType.Column) { deleteSourceBlock && operations.push( ...[ { cmd: 'listRemove', id: leadingSourceBlock.parentId, path: [path], args: { id: leadingSourceBlockId }, table: 'block' } ] ) const newColumnBlock = createEmptyBlock({ type: Editor.BlockType.Column, storyId, parentId: targetBlock.parentId, permissions: targetBlock.permissions }) // newColumnBlock.children = [sourceBlock.id] operations.push( ...[ { cmd: 'set', id: newColumnBlock.id, args: newColumnBlock, table: 'block', path: [] } ] ) operations.push( ...[ { cmd: 'listBefore', id: newColumnBlock.id, args: { id: leadingSourceBlockId }, table: 'block', path: [path] } ] ) if (direction === 'left') { operations.push( ...[ { cmd: 'listBefore', id: targetBlock.parentId, args: { id: newColumnBlock.id, before: targetBlockId }, table: 'block', path: [path] } ] ) // targetParentBlock.children?.splice(targetIndex, 0, newColumnBlock.id) } else if (direction === 'right') { operations.push( ...[ { cmd: 'listAfter', id: targetBlock.parentId, args: { id: newColumnBlock.id, after: targetBlockId }, table: 'block', path: [path] } ] ) // targetParentBlock.children?.splice(targetIndex + 1, 0, newColumnBlock.id) } newSourceBlockParentId = newColumnBlock.id // draft.blocksMap[newColumnBlock.id] = newColumnBlock } else { invariant(targetBlock.parentId === targetBlock.storyId, 'target block is not first class') invariant(targetBlock.type !== Editor.BlockType.Row, "row block can't be splited") const rowBlock = createEmptyBlock({ type: Editor.BlockType.Row, storyId, parentId: targetBlock.parentId, permissions: targetBlock.permissions }) const columnBlockA = createEmptyBlock({ type: Editor.BlockType.Column, storyId, parentId: rowBlock.id, permissions: targetBlock.permissions }) const columnBlockB = createEmptyBlock({ type: Editor.BlockType.Column, storyId, parentId: rowBlock.id, permissions: targetBlock.permissions }) operations.push( ...[ { cmd: 'set', id: rowBlock.id, args: cloneDeep(rowBlock), table: 'block', path: [] } ] ) operations.push( ...[ { cmd: 'listAfter', id: targetBlock.parentId, args: { id: rowBlock.id, after: targetBlockId }, table: 'block', path: [path] } ] ) deleteSourceBlock && operations.push( ...[ { cmd: 'listRemove', id: leadingSourceBlock.parentId, path: [path], args: { id: leadingSourceBlockId }, table: 'block' } ] ) operations.push( ...[ { cmd: 'listRemove', id: targetBlock.parentId, path: [path], args: { id: targetBlock.id }, table: 'block' } ] ) operations.push( ...[ { cmd: 'set', id: columnBlockA.id, args: cloneDeep(columnBlockA), table: 'block', path: [] } ] ) operations.push( ...[ { cmd: 'set', id: columnBlockB.id, args: cloneDeep(columnBlockB), table: 'block', path: [] } ] ) operations.push( ...[ { cmd: 'listBefore', id: rowBlock.id, args: { id: columnBlockA.id }, table: 'block', path: [path] } ] ) operations.push( ...[ { cmd: 'listAfter', id: rowBlock.id, args: { id: columnBlockB.id, after: columnBlockA.id }, table: 'block', path: [path] } ] ) if (direction === 'left') { operations.push( ...[ { cmd: 'listBefore', id: columnBlockA.id, args: { id: leadingSourceBlockId }, table: 'block', path: [path] } ] ) operations.push( ...[ { cmd: 'listBefore', id: columnBlockB.id, args: { id: targetBlock.id }, table: 'block', path: [path] } ] ) newSourceBlockParentId = columnBlockA.id } else if (direction === 'right') { operations.push( ...[ { cmd: 'listBefore', id: columnBlockA.id, args: { id: targetBlock.id }, table: 'block', path: [path] } ] ) operations.push( ...[ { cmd: 'listBefore', id: columnBlockB.id, args: { id: leadingSourceBlockId }, table: 'block', path: [path] } ] ) newSourceBlockParentId = columnBlockB.id } } } else if (direction === 'child') { deleteSourceBlock && operations.push( ...[ { cmd: 'listRemove', id: leadingSourceBlock.parentId, path: [path], args: { id: leadingSourceBlockId }, table: 'block' } ] ) operations.push( ...[ { cmd: 'listBefore', id: targetBlockId, args: { id: leadingSourceBlockId }, table: 'block', path: [path] } ] ) newSourceBlockParentId = targetBlockId } Object.values(sourceBlockFragment.data).forEach((block) => { if (block.storyId !== storyId) { operations.push({ cmd: 'update', id: block.id, path: ['storyId'], args: storyId, table: 'block' }) } operations.push({ cmd: 'setPermissions', id: block.id, path: ['permissions'], args: targetBlock.permissions, table: 'block' }) }) // ...and just place other blocks next to the first block const parentId = newSourceBlockParentId let afterId = leadingSourceBlockId sourceBlockFragment.children.slice(1).forEach((blockId) => { invariant(parentId, 'parent id is null') const block = sourceBlockFragment.data[blockId] if (deleteSourceBlock) { operations.push({ cmd: 'listRemove', id: block.parentId, path: [path], args: { id: block.id }, table: 'block' }) } operations.push( ...[ { cmd: 'listAfter', id: parentId, args: { id: block.id, after: afterId }, table: 'block', path: [path] } ] ) afterId = block.id }) return createTranscation({ operations }) } export const insertBlocksTranscation = ({ blocks, after }: { blocks: Editor.BaseBlock[]; after: string }) => { const operations: Operation[] = [] let afterId = after for (let i = 0; i < blocks.length; i++) { const block = blocks[i] operations.push({ cmd: 'set', id: block.id, path: [], args: block, table: 'block' }) operations.push({ cmd: 'listAfter', id: block.parentId, path: ['children'], table: 'block', args: { id: block.id, after: afterId } }) afterId = block.id } return createTranscation({ operations }) } export const setBlockTitleTranscation = ({ oldBlock, newBlock }: { oldBlock: Editor.BaseBlock newBlock: Editor.BaseBlock }) => { const operations: Operation[] = [] const id = oldBlock.id if (dequal(oldBlock.content?.title, newBlock.content?.title) === false) { operations.push({ cmd: 'update', path: ['content', 'title'], args: newBlock.content?.title, table: 'block', id: id }) } return createTranscation({ operations }) } export const setBlockOperations = <T extends Editor.BaseBlock>({ oldBlock, newBlock }: { oldBlock: T newBlock: T }) => { const operations: Operation[] = [] const id = oldBlock.id if (dequal(oldBlock.content, newBlock.content) === false) { operations.push({ cmd: 'set', path: ['content'], args: newBlock.content, table: 'block', id: id }) } if (dequal(oldBlock.format, newBlock.format) === false) { operations.push({ cmd: 'set', path: ['format'], args: newBlock.format, table: 'block', id: id }) } if (dequal(oldBlock.type, newBlock.type) === false) { operations.push({ cmd: 'update', path: ['type'], args: newBlock.type, table: 'block', id: id }) } return operations } export const setBlockTranscation = <T extends Editor.BaseBlock>({ oldBlock, newBlock }: { oldBlock: T newBlock: T }) => { return createTranscation({ operations: setBlockOperations({ oldBlock, newBlock }) }) }
the_stack
import { Node } from 'slate'; import { toSlateDoc } from '../src'; import { TestEditor, TransformFunc } from './testEditor'; import { createNode, createTestEditor, createValue, wait } from './utils'; const tests = [ [ 'Insert text into a paragraph node', [createNode('paragraph', '')], [ TestEditor.makeInsertText('Hello ', { path: [0, 0], offset: 0 }), TestEditor.makeInsertText('collaborator', { path: [0, 0], offset: 6 }), TestEditor.makeInsertText('!', { path: [0, 0], offset: 18 }), ], [createNode('paragraph', 'Hello collaborator!')], ], [ 'Delete characters from a paragraph node', [createNode('paragraph', 'Hello collaborator!')], [ TestEditor.makeRemoveCharacters(7, { path: [0, 0], offset: 11 }), TestEditor.makeRemoveCharacters(6, { path: [0, 0], offset: 5 }), ], [createNode('paragraph', 'Hello!')], ], [ 'Insert new nodes (both paragraph and text)', [createNode()], [ TestEditor.makeInsertNodes({ type: 'paragraph', children: [] }, [1]), TestEditor.makeInsertNodes({ text: 'Hello collaborator!' }, [1, 0]), ], [createNode(), createNode('paragraph', 'Hello collaborator!')], ], [ 'Insert new nodes (two paragraphs)', [ createNode('paragraph', 'alfa'), createNode('paragraph', 'bravo'), createNode('paragraph', 'charlie'), createNode('paragraph', 'delta'), ], [ TestEditor.makeInsertNodes(createNode('paragraph', 'echo'), [1]), TestEditor.makeInsertNodes(createNode('paragraph', 'foxtrot'), [4]), ], [ createNode('paragraph', 'alfa'), createNode('paragraph', 'echo'), createNode('paragraph', 'bravo'), createNode('paragraph', 'charlie'), createNode('paragraph', 'foxtrot'), createNode('paragraph', 'delta'), ], ], [ 'Insert new nodes (three paragraphs)', [ createNode('paragraph', 'one'), createNode('paragraph', 'two'), createNode('paragraph', 'three'), createNode('paragraph', 'four'), ], [ TestEditor.makeInsertNodes(createNode('paragraph', 'five'), [1]), TestEditor.makeInsertNodes(createNode('paragraph', 'six'), [3]), TestEditor.makeInsertNodes(createNode('paragraph', 'seven'), [5]), ], [ createNode('paragraph', 'one'), createNode('paragraph', 'five'), createNode('paragraph', 'two'), createNode('paragraph', 'six'), createNode('paragraph', 'three'), createNode('paragraph', 'seven'), createNode('paragraph', 'four'), ], ], [ 'Merge two paragraph nodes', [ createNode('paragraph', 'Hello '), createNode('paragraph', 'collaborator!'), ], [TestEditor.makeMergeNodes([1])], [createNode('paragraph', 'Hello collaborator!')], ], [ 'Move a paragraph node to an existing position', [ createNode('paragraph', 'first'), createNode('paragraph', 'second'), createNode('paragraph', 'third'), ], [TestEditor.makeMoveNodes([1], [0])], [ createNode('paragraph', 'second'), createNode('paragraph', 'first'), createNode('paragraph', 'third'), ], ], [ 'Move a paragraph node to the end', [ createNode('paragraph', 'first'), createNode('paragraph', 'second'), createNode('paragraph', 'third'), ], [TestEditor.makeMoveNodes([0], [3])], [ createNode('paragraph', 'second'), createNode('paragraph', 'third'), createNode('paragraph', 'first'), ], ], [ 'Move a paragraph node far past the end', [ createNode('paragraph', 'first'), createNode('paragraph', 'second'), createNode('paragraph', 'third'), ], [TestEditor.makeMoveNodes([0], [1000])], [ createNode('paragraph', 'second'), createNode('paragraph', 'third'), createNode('paragraph', 'first'), ], ], [ 'Move a text node', [ createNode('paragraph', 'first'), createNode('paragraph', 'second'), createNode('paragraph', 'third'), ], [TestEditor.makeMoveNodes([1, 0], [2, 0])], [ createNode('paragraph', 'first'), createNode('paragraph', ''), createNode('paragraph', 'secondthird'), ], ], [ 'Remove a paragraph node', [ createNode('paragraph', 'first'), createNode('paragraph', 'second'), createNode('paragraph', 'third'), ], [TestEditor.makeRemoveNodes([0])], [createNode('paragraph', 'second'), createNode('paragraph', 'third')], ], [ 'Remove two non-consecutive paragraph nodes', [ createNode('paragraph', 'first'), createNode('paragraph', 'second'), createNode('paragraph', 'third'), createNode('paragraph', 'fourth'), ], [TestEditor.makeRemoveNodes([0]), TestEditor.makeRemoveNodes([1])], [createNode('paragraph', 'second'), createNode('paragraph', 'fourth')], ], [ 'Remove two consecutive paragraph nodes', [ createNode('paragraph', 'first'), createNode('paragraph', 'second'), createNode('paragraph', 'third'), createNode('paragraph', 'fourth'), ], [TestEditor.makeRemoveNodes([1]), TestEditor.makeRemoveNodes([1])], [createNode('paragraph', 'first'), createNode('paragraph', 'fourth')], ], [ 'Remove a text node', [ createNode('paragraph', 'first'), createNode('paragraph', 'second'), createNode('paragraph', 'third'), ], [TestEditor.makeRemoveNodes([1, 0])], [ createNode('paragraph', 'first'), createNode('paragraph', ''), createNode('paragraph', 'third'), ], ], [ 'Set properties of a paragraph node', [ createNode('paragraph', 'first', { test: '1234' }), createNode('paragraph', 'second'), ], [TestEditor.makeSetNodes([0], { test: '4567' })], [ createNode('paragraph', 'first', { test: '4567' }), createNode('paragraph', 'second'), ], ], [ 'Set properties of a text node', [ createNode('paragraph', 'first', { test: '1234' }), createNode('paragraph', 'second'), ], [TestEditor.makeSetNodes([1, 0], { data: '4567' })], [ createNode('paragraph', 'first', { test: '1234' }), { type: 'paragraph', children: [ { data: '4567', text: 'second', }, ], }, ], ], [ 'Split an existing paragraph', [createNode('paragraph', 'Hello collaborator!')], [TestEditor.makeSplitNodes({ path: [0, 0], offset: 6 })], [ createNode('paragraph', 'Hello '), createNode('paragraph', 'collaborator!'), ], ], [ 'Insert and remove text in the same paragraph', [createNode('paragraph', 'abc def')], [ TestEditor.makeInsertText('ghi ', { path: [0, 0], offset: 4 }), TestEditor.makeRemoveCharacters(2, { path: [0, 0], offset: 1 }), TestEditor.makeInsertText('jkl ', { path: [0, 0], offset: 6 }), TestEditor.makeRemoveCharacters(1, { path: [0, 0], offset: 11 }), TestEditor.makeInsertText(' mno', { path: [0, 0], offset: 12 }), ], [createNode('paragraph', 'a ghi jkl df mno')], ], [ 'Remove first paragraph, insert text into second paragraph', [createNode('paragraph', 'abcd'), createNode('paragraph', 'efgh')], [ TestEditor.makeRemoveNodes([0]), TestEditor.makeInsertText(' ijkl ', { path: [0, 0], offset: 2 }), ], [createNode('paragraph', 'ef ijkl gh')], ], [ 'More complex case: insert text, both insert and remove nodes', [ createNode('paragraph', 'abcd'), createNode('paragraph', 'efgh'), createNode('paragraph', 'ijkl'), ], [ TestEditor.makeInsertText(' mnop ', { path: [0, 0], offset: 2 }), TestEditor.makeRemoveNodes([1]), TestEditor.makeInsertText(' qrst ', { path: [1, 0], offset: 2 }), TestEditor.makeInsertNodes(createNode('paragraph', 'uvxw'), [1]), ], [ createNode('paragraph', 'ab mnop cd'), createNode('paragraph', 'uvxw'), createNode('paragraph', 'ij qrst kl'), ], ], [ 'Insert text, then insert node that affects the path to the affected text', [createNode('paragraph', 'abcd')], [ TestEditor.makeInsertText(' efgh ', { path: [0, 0], offset: 2 }), TestEditor.makeInsertNodes(createNode('paragraph', 'ijkl'), [0]), ], [createNode('paragraph', 'ijkl'), createNode('paragraph', 'ab efgh cd')], ], [ 'Set properties, then insert node that affects path to the affected node', [createNode('paragraph', 'abcd')], [ TestEditor.makeSetNodes([0], { test: '1234' }), TestEditor.makeInsertNodes(createNode('paragraph', 'ijkl'), [0]), ], [ createNode('paragraph', 'ijkl'), createNode('paragraph', 'abcd', { test: '1234' }), ], ], [ 'Insert node, then insert second node that affects path to the first node', [ createValue([ createNode('paragraph', 'abc'), createNode('paragraph', 'def'), ]), ], [ TestEditor.makeInsertNodes(createNode('paragraph', 'jkl'), [0, 1]), TestEditor.makeInsertNodes(createNode('paragraph', 'ghi'), [0]), ], [ createNode('paragraph', 'ghi'), createValue([ createNode('paragraph', 'abc'), createNode('paragraph', 'jkl'), createNode('paragraph', 'def'), ]), ], ], [ 'remove_text op spans location of previous remove_text op', [createNode('paragraph', 'abc defg ijklm')], [TestEditor.makeRemoveCharacters(5, { path: [0, 0], offset: 4 })], [createNode('paragraph', 'abc ijklm')], [TestEditor.makeRemoveCharacters(6, { path: [0, 0], offset: 1 })], [createNode('paragraph', 'alm')], ], [ 'remove_text op spans locations of two previous remove_text ops', [createNode('paragraph', 'abcdefghijklmnopqrst')], [TestEditor.makeRemoveCharacters(3, { path: [0, 0], offset: 2 })], [createNode('paragraph', 'abfghijklmnopqrst')], [TestEditor.makeRemoveCharacters(8, { path: [0, 0], offset: 5 })], [createNode('paragraph', 'abfghqrst')], [TestEditor.makeRemoveCharacters(7, { path: [0, 0], offset: 1 })], [createNode('paragraph', 'at')], ], [ 'set_selection op is a null op', [createNode('paragraph', 'abcdefghijklmnopqrst')], [ TestEditor.makeSetSelection( { path: [0, 0], offset: 2 }, { path: [0, 0], offset: 4 } ), ], [createNode('paragraph', 'abcdefghijklmnopqrst')], ], ]; describe('slate operations propagate between editors', () => { tests.forEach(([testName, input, ...cases]) => { it(`${testName}`, async () => { // Create two editors. const src = await createTestEditor(); const dst = await createTestEditor(); // Set initial state for src editor, propagate changes to dst editor. TestEditor.applyTransform( src, TestEditor.makeInsertNodes(input as Node[], [0]) ); await wait(); let updates = TestEditor.getCapturedYjsUpdates(src); TestEditor.applyYjsUpdatesToYjs(dst, updates); await wait(); // Verify initial states. expect(src.children).toEqual(input); expect(toSlateDoc(src.sharedType)).toEqual(input); expect(toSlateDoc(dst.sharedType)).toEqual(input); expect(dst.children).toEqual(input); // Allow for multiple rounds of applying transforms and verifying state. const toTest = cases.slice(); while (toTest.length > 0) { const [transforms, output] = toTest.splice(0, 2); // Apply transforms to src editor, propagate changes to dst editor. TestEditor.applyTransforms(src, transforms as TransformFunc[]); // eslint-disable-next-line no-await-in-loop await wait(); updates = TestEditor.getCapturedYjsUpdates(src); TestEditor.applyYjsUpdatesToYjs(dst, updates); // eslint-disable-next-line no-await-in-loop await wait(); // Verify final states. expect(src.children).toEqual(output); expect(toSlateDoc(src.sharedType)).toEqual(output); expect(toSlateDoc(dst.sharedType)).toEqual(output); expect(dst.children).toEqual(output); } }); }); });
the_stack
import * as assert from 'assert'; import {beforeEach, describe, it} from 'mocha'; // eslint-disable-next-line @typescript-eslint/no-var-requires const {Query} = require('../src/query'); // eslint-disable-next-line @typescript-eslint/no-var-requires import {Datastore} from '../src'; describe('Query', () => { const SCOPE = {} as Datastore; const NAMESPACE = 'Namespace'; const KINDS = ['Kind']; // eslint-disable-next-line @typescript-eslint/no-explicit-any let query: any; beforeEach(() => { query = new Query(SCOPE, NAMESPACE, KINDS); }); describe('instantiation', () => { it('should localize the scope', () => { assert.strictEqual(query.scope, SCOPE); }); it('should localize the namespace', () => { assert.strictEqual(query.namespace, NAMESPACE); }); it('should localize the kind', () => { assert.strictEqual(query.kinds, KINDS); }); it('should use null for all falsy namespace values', () => { [ new Query(SCOPE, '', KINDS), new Query(SCOPE, null, KINDS), new Query(SCOPE, undefined, KINDS), new Query(SCOPE, 0 as {} as string, KINDS), new Query(SCOPE, KINDS), ].forEach(query => { assert.strictEqual(query.namespace, null); }); }); }); describe('filter', () => { it('should support filtering', () => { const now = new Date(); const query = new Query(['kind1']).filter('date', '<=', now); const filter = query.filters[0]; assert.strictEqual(filter.name, 'date'); assert.strictEqual(filter.op, '<='); assert.strictEqual(filter.val, now); }); it('should recognize all the different operators', () => { const now = new Date(); const query = new Query(['kind1']) .filter('date', '<=', now) .filter('name', '=', 'Title') .filter('count', '>', 20) .filter('size', '<', 10) .filter('something', '>=', 11); assert.strictEqual(query.filters[0].name, 'date'); assert.strictEqual(query.filters[0].op, '<='); assert.strictEqual(query.filters[0].val, now); assert.strictEqual(query.filters[1].name, 'name'); assert.strictEqual(query.filters[1].op, '='); assert.strictEqual(query.filters[1].val, 'Title'); assert.strictEqual(query.filters[2].name, 'count'); assert.strictEqual(query.filters[2].op, '>'); assert.strictEqual(query.filters[2].val, 20); assert.strictEqual(query.filters[3].name, 'size'); assert.strictEqual(query.filters[3].op, '<'); assert.strictEqual(query.filters[3].val, 10); assert.strictEqual(query.filters[4].name, 'something'); assert.strictEqual(query.filters[4].op, '>='); assert.strictEqual(query.filters[4].val, 11); }); it('should remove any whitespace surrounding the filter name', () => { const query = new Query(['kind1']).filter(' count ', '>', 123); assert.strictEqual(query.filters[0].name, 'count'); }); it('should remove any whitespace surrounding the operator', () => { const query = new Query(['kind1']).filter( 'count', ' < ', 123 ); assert.strictEqual(query.filters[0].op, '<'); }); it('should return the query instance', () => { const query = new Query(['kind1']); const nextQuery = query.filter('count', '<', 5); assert.strictEqual(query, nextQuery); }); it('should default the operator to "="', () => { const query = new Query(['kind1']).filter('name', 'Stephen'); const filter = query.filters[0]; assert.strictEqual(filter.name, 'name'); assert.strictEqual(filter.op, '='); assert.strictEqual(filter.val, 'Stephen'); }); }); describe('hasAncestor', () => { it('should support ancestor filtering', () => { const query = new Query(['kind1']).hasAncestor(['kind2', 123]); assert.strictEqual(query.filters[0].name, '__key__'); assert.strictEqual(query.filters[0].op, 'HAS_ANCESTOR'); assert.deepStrictEqual(query.filters[0].val, ['kind2', 123]); }); it('should return the query instance', () => { const query = new Query(['kind1']); const nextQuery = query.hasAncestor(['kind2', 123]); assert.strictEqual(query, nextQuery); }); }); describe('order', () => { it('should default ordering to ascending', () => { const query = new Query(['kind1']).order('name'); assert.strictEqual(query.orders[0].name, 'name'); assert.strictEqual(query.orders[0].sign, '+'); }); it('should support ascending order', () => { const query = new Query(['kind1']).order('name'); assert.strictEqual(query.orders[0].name, 'name'); assert.strictEqual(query.orders[0].sign, '+'); }); it('should support descending order', () => { const query = new Query(['kind1']).order('count', {descending: true}); assert.strictEqual(query.orders[0].name, 'count'); assert.strictEqual(query.orders[0].sign, '-'); }); it('should support both ascending and descending', () => { const query = new Query(['kind1']) .order('name') .order('count', {descending: true}); assert.strictEqual(query.orders[0].name, 'name'); assert.strictEqual(query.orders[0].sign, '+'); assert.strictEqual(query.orders[1].name, 'count'); assert.strictEqual(query.orders[1].sign, '-'); }); it('should return the query instance', () => { const query = new Query(['kind1']); const nextQuery = query.order('name'); assert.strictEqual(query, nextQuery); }); }); describe('groupBy', () => { it('should store an array of properties to group by', () => { const query = new Query(['kind1']).groupBy(['name', 'size']); assert.deepStrictEqual(query.groupByVal, ['name', 'size']); }); it('should convert a single property into an array', () => { const query = new Query(['kind1']).groupBy('name'); assert.deepStrictEqual(query.groupByVal, ['name']); }); it('should return the query instance', () => { const query = new Query(['kind1']); const nextQuery = query.groupBy(['name', 'size']); assert.strictEqual(query, nextQuery); }); }); describe('select', () => { it('should store an array of properties to select', () => { const query = new Query(['kind1']).select(['name', 'size']); assert.deepStrictEqual(query.selectVal, ['name', 'size']); }); it('should convert a single property into an array', () => { const query = new Query(['kind1']).select('name'); assert.deepStrictEqual(query.selectVal, ['name']); }); it('should return the query instance', () => { const query = new Query(['kind1']); const nextQuery = query.select(['name', 'size']); assert.strictEqual(query, nextQuery); }); }); describe('start', () => { it('should capture the starting cursor value', () => { const query = new Query(['kind1']).start('X'); assert.strictEqual(query.startVal, 'X'); }); it('should return the query instance', () => { const query = new Query(['kind1']); const nextQuery = query.start('X'); assert.strictEqual(query, nextQuery); }); }); describe('end', () => { it('should capture the ending cursor value', () => { const query = new Query(['kind1']).end('Z'); assert.strictEqual(query.endVal, 'Z'); }); it('should return the query instance', () => { const query = new Query(['kind1']); const nextQuery = query.end('Z'); assert.strictEqual(query, nextQuery); }); }); describe('limit', () => { it('should capture the number of results to limit to', () => { const query = new Query(['kind1']).limit(20); assert.strictEqual(query.limitVal, 20); }); it('should return the query instance', () => { const query = new Query(['kind1']); const nextQuery = query.limit(20); assert.strictEqual(query, nextQuery); }); }); describe('offset', () => { it('should capture the number of results to offset by', () => { const query = new Query(['kind1']).offset(100); assert.strictEqual(query.offsetVal, 100); }); it('should return the query instance', () => { const query = new Query(['kind1']); const nextQuery = query.offset(100); assert.strictEqual(query, nextQuery); }); }); describe('run', () => { it('should call the parent instance runQuery correctly', done => { const args = [{}, () => {}]; // eslint-disable-next-line @typescript-eslint/no-explicit-any query.scope.runQuery = function (...thisArgs: any[]) { assert.strictEqual(this, query.scope); assert.strictEqual(thisArgs[0], query); assert.strictEqual(thisArgs[1], args[0]); done(); }; query.run(...args); }); }); describe('runStream', () => { it('should not require options', () => { const runQueryReturnValue = {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any query.scope.runQueryStream = function (...args: any[]) { assert.strictEqual(this, query.scope); assert.strictEqual(args[0], query); return runQueryReturnValue; }; const results = query.runStream(); assert.strictEqual(results, runQueryReturnValue); }); it('should call the parent instance runQueryStream correctly', () => { const options = { consistency: 'string', gaxOptions: {}, wrapNumbers: true, }; const runQueryReturnValue = {}; // eslint-disable-next-line @typescript-eslint/no-explicit-any query.scope.runQueryStream = function (...args: any[]) { assert.strictEqual(this, query.scope); assert.strictEqual(args[0], query); assert.strictEqual(args[1], options); return runQueryReturnValue; }; const results = query.runStream(options); assert.strictEqual(results, runQueryReturnValue); }); }); });
the_stack
import { config, expect } from "chai"; import sinon from "sinon"; import { PropertyRecord } from "@itwin/appui-abstract"; import { IMutableGridItemFactory, MutableGridItemFactory } from "../../../../components-react/propertygrid/internal/flat-items/MutableGridItemFactory"; import { MutablePropertyGridModel } from "../../../../components-react/propertygrid/internal/PropertyGridModel"; import TestUtils from "../../../TestUtils"; import { FlattenedProperty, GridModelLastItemData, FlatGridTestUtils as GridUtils, PropertyGridModelTestData } from "./flat-items/FlatGridTestUtils"; config.truncateThreshold = 0; describe("MutablePropertyGridModel", () => { const testCases: Array<PropertyGridModelTestData & { unexistingItemKey: string }> = [ { testName: "Single category", propertyData: { label: TestUtils.createPrimitiveStringProperty("Label", "Value"), categories: [ { name: "Cat1", label: "Cat 1", expand: true }, ], records: { Cat1: [], }, }, expectedLastItemData: { Cat1: { isLastInRootCategory: true, lastInNumberOfCategories: 0 }, }, unexistingItemKey: "does not exist", }, { testName: "Multiple categories", propertyData: { label: TestUtils.createPrimitiveStringProperty("Label", "Value"), categories: [ { name: "Cat1", label: "Cat 1", expand: true }, { name: "Cat2", label: "Cat 2", expand: true }, { name: "Cat3", label: "Cat 3", expand: true }, ], records: { Cat1: [], Cat2: [], Cat3: [], }, }, expectedLastItemData: { Cat1: { isLastInRootCategory: true, lastInNumberOfCategories: 0 }, Cat2: { isLastInRootCategory: true, lastInNumberOfCategories: 0 }, Cat3: { isLastInRootCategory: true, lastInNumberOfCategories: 0 }, }, unexistingItemKey: "does not exist", }, { testName: "Nested categories", propertyData: { label: TestUtils.createPrimitiveStringProperty("Label", "Value"), categories: [ { name: "Cat1", label: "Cat 1", expand: true, childCategories: [ { name: "Cat1-1", label: "Cat 1-1", expand: true, childCategories: [ { name: "Cat1-1-1", label: "Cat 1-1-1", expand: true }, ], }, ], }, ], records: { Cat1: [], Cat2: [], Cat3: [], }, }, expectedLastItemData: { "Cat1_Cat1-1_Cat1-1-1": { isLastInRootCategory: true, lastInNumberOfCategories: 2 }, }, unexistingItemKey: "does not exist", }, { testName: "Single category with property records", propertyData: { label: TestUtils.createPrimitiveStringProperty("Label", "Value"), categories: [ { name: "Cat1", label: "Cat 1", expand: true }, ], records: { Cat1: [ TestUtils.createPrimitiveStringProperty("Prop", "V1", undefined, undefined, true), TestUtils.createArrayProperty("Array", [], true), TestUtils.createStructProperty("Struct", {}, true), ], }, }, expectedLastItemData: { Cat1_Struct: { isLastInRootCategory: true, lastInNumberOfCategories: 1 }, }, unexistingItemKey: "does not exist", }, { testName: "Multiple categories with property records", propertyData: { label: TestUtils.createPrimitiveStringProperty("Label", "Value"), categories: [ { name: "Cat1", label: "Cat 1", expand: true }, { name: "Cat2", label: "Cat 2", expand: true }, { name: "Cat3", label: "Cat 3", expand: true }, ], records: { Cat1: [ TestUtils.createPrimitiveStringProperty("Prop", "V1", undefined, undefined, true), TestUtils.createArrayProperty("Array", [], true), TestUtils.createStructProperty("Struct", {}, true), ], Cat2: [ TestUtils.createPrimitiveStringProperty("Prop", "V1", undefined, undefined, true), TestUtils.createStructProperty("Struct", {}, true), TestUtils.createArrayProperty("Array", [], true), ], Cat3: [ TestUtils.createStructProperty("Struct", {}, true), TestUtils.createArrayProperty("Array", [], true), TestUtils.createPrimitiveStringProperty("Prop", "V1", undefined, undefined, true), ], }, }, expectedLastItemData: { Cat1_Struct: { isLastInRootCategory: true, lastInNumberOfCategories: 1 }, Cat2_Array: { isLastInRootCategory: true, lastInNumberOfCategories: 1 }, Cat3_Prop: { isLastInRootCategory: true, lastInNumberOfCategories: 1 }, }, unexistingItemKey: "does not exist", }, { testName: "Nested categories with property records", propertyData: { label: TestUtils.createPrimitiveStringProperty("Label", "Value"), categories: [ { name: "Cat1", label: "Cat 1", expand: true, childCategories: [ { name: "Cat1-1", label: "Cat 1-1", expand: true, childCategories: [ { name: "Cat1-1-1", label: "Cat 1-1-1", expand: true }, ], }, ], }, ], records: { "Cat1": [ TestUtils.createPrimitiveStringProperty("Prop", "V1", undefined, undefined, true), TestUtils.createArrayProperty("Array", [], true), TestUtils.createStructProperty("Struct", {}, true), ], "Cat1-1": [ TestUtils.createPrimitiveStringProperty("Prop", "V1", undefined, undefined, true), TestUtils.createStructProperty("Struct", {}, true), TestUtils.createArrayProperty("Array", [], true), ], "Cat1-1-1": [ TestUtils.createStructProperty("Struct", {}, true), TestUtils.createArrayProperty("Array", [], true), TestUtils.createPrimitiveStringProperty("Prop", "V1", undefined, undefined, true), ], }, }, expectedLastItemData: { "Cat1_Cat1-1_Cat1-1-1_Prop": { isLastInRootCategory: true, lastInNumberOfCategories: 3 }, }, unexistingItemKey: "does not exist", }, { testName: "Nested categories with nested property records", propertyData: { label: TestUtils.createPrimitiveStringProperty("Label", "Value"), categories: [ { name: "Cat1", label: "Category 1", expand: true, childCategories: [ { name: "Cat1-1", label: "Category 1-1", expand: true }, ], }, { name: "Cat2", label: "Category 2", expand: true, childCategories: [ { name: "Cat2-1", label: "Category 2-1", expand: true, childCategories: [ { name: "Cat2-1-1", label: "Category 2-1-1", expand: false }, ], }, ], }, ], records: { "Cat1": [], "Cat1-1": [ TestUtils.createArrayProperty("Array1-1-1", [ TestUtils.createPrimitiveStringProperty("Property1-1-1-1", "V1", undefined, undefined, true), TestUtils.createStructProperty("Struct1-1-1-2", { "Array1-1-1-2-1": TestUtils.createArrayProperty("Array1-1-1-2-1", [], true), }, false), ], true), ], "Cat2": [ TestUtils.createStructProperty("Struct2-1", { "Property2-1-1": TestUtils.createPrimitiveStringProperty("Property2-1-1", "V1"), "Property2-1-2": TestUtils.createPrimitiveStringProperty("Property2-1-2", "V1"), "Property2-1-3": TestUtils.createPrimitiveStringProperty("Property2-1-3", "V1"), }, true), ], "Cat2-1": [], "Cat2-1-1": [ TestUtils.createPrimitiveStringProperty("Prop", "V1"), TestUtils.createArrayProperty("Array", [], true), TestUtils.createStructProperty("Struct", {}, true), ], }, }, expectedLastItemData: { "Cat1_Cat1-1_Array1-1-1_Struct1-1-1-2_1": { isLastInRootCategory: true, lastInNumberOfCategories: 2 }, "Cat2_Cat2-1_Cat2-1-1": { isLastInRootCategory: true, lastInNumberOfCategories: 2 }, }, unexistingItemKey: "Cat2_Struct2-1_does not exist", }, { testName: "Big nested categories with nested property records", propertyData: { label: TestUtils.createPrimitiveStringProperty("Label", "Value"), categories: [ { name: "Cat1", label: "Category 1", expand: true, childCategories: [ { name: "Cat1-1", label: "Category 1-1", expand: true }, { name: "Cat1-2", label: "Category 1-2", expand: true }, { name: "Cat1-3", label: "Category 1-3", expand: true }, ], }, { name: "Cat2", label: "Category 2", expand: true, childCategories: [ { name: "Cat2-1", label: "Category 2-1", expand: true, childCategories: [ { name: "Cat2-1-1", label: "Category 2-1-1", expand: false }, { name: "Cat2-1-2", label: "Category 2-1-2", expand: true }, { name: "Cat2-1-3", label: "Category 2-1-3", expand: false }, ], }, { name: "Cat2-2", label: "Category 2-2", expand: false, childCategories: [ { name: "Cat2-2-1", label: "Category 2-2-1", expand: true }, { name: "Cat2-2-2", label: "Category 2-2-2", expand: true }, { name: "Cat2-2-3", label: "Category 2-2-3", expand: true }, ], }, ], }, ], records: { "Cat1": [], "Cat1-1": [ TestUtils.createArrayProperty("Array1-1-1", [ TestUtils.createPrimitiveStringProperty("Property1-1-1-1", "V1"), TestUtils.createStructProperty("Struct1-1-1-2", { "Array1-1-1-2-1": TestUtils.createArrayProperty("Array1-1-1-2-1", [ TestUtils.createPrimitiveStringProperty("Property1-1-1-2-1-1", "V1"), TestUtils.createPrimitiveStringProperty("Property1-1-1-2-1-2", "V1"), TestUtils.createPrimitiveStringProperty("Property1-1-1-2-1-3", "V1"), ], false), }, true), TestUtils.createPrimitiveStringProperty("Property1-1-1-3", "V1"), TestUtils.createPrimitiveStringProperty("Property1-1-1-4", "V1"), TestUtils.createPrimitiveStringProperty("Property1-1-1-5", "V1"), ], true), ], "Cat1-2": [ TestUtils.createArrayProperty("Array1-2-1", [ TestUtils.createPrimitiveStringProperty("Property1-2-1-1", "V1"), TestUtils.createStructProperty("Struct1-2-1-2", { "Array1-2-1-2-1": TestUtils.createArrayProperty("Array1-2-1-2-1", [ TestUtils.createPrimitiveStringProperty("Property1-2-1-2-1-1", "V1"), TestUtils.createPrimitiveStringProperty("Property1-2-1-2-1-2", "V1"), TestUtils.createPrimitiveStringProperty("Property1-2-1-2-1-3", "V1"), ], true), }, false), TestUtils.createPrimitiveStringProperty("Property1-2-1-3", "V1"), TestUtils.createPrimitiveStringProperty("Property1-2-1-4", "V1"), TestUtils.createPrimitiveStringProperty("Property1-2-1-5", "V1"), ], true), ], "Cat1-3": [ TestUtils.createArrayProperty("Array1-3-1", [ TestUtils.createPrimitiveStringProperty("Property1-3-1-1", "V1"), TestUtils.createStructProperty("Struct1-3-1-2", { "Array1-3-1-2-1": TestUtils.createArrayProperty("Array1-3-1-2-1", [ TestUtils.createPrimitiveStringProperty("Property1-3-1-2-1-1", "V1"), TestUtils.createPrimitiveStringProperty("Property1-3-1-2-1-2", "V1"), TestUtils.createPrimitiveStringProperty("Property1-3-1-2-1-3", "V1"), ], false), }, true), TestUtils.createPrimitiveStringProperty("Property1-3-1-3", "V1"), TestUtils.createPrimitiveStringProperty("Property1-3-1-4", "V1"), TestUtils.createPrimitiveStringProperty("Property1-3-1-5", "V1"), ], false), ], "Cat2": [ TestUtils.createStructProperty("Struct2", { "Property2-1": TestUtils.createPrimitiveStringProperty("Property2-1", "V1"), "Property2-2": TestUtils.createPrimitiveStringProperty("Property2-2", "V1"), "Property2-3": TestUtils.createPrimitiveStringProperty("Property2-3", "V1"), }, true), ], "Cat2-1": [], "Cat2-1-1": [ TestUtils.createPrimitiveStringProperty("Prop", "V1"), TestUtils.createArrayProperty("Array", [], true), TestUtils.createStructProperty("Struct", {}, true), ], "Cat2-1-2": [ TestUtils.createPrimitiveStringProperty("Prop", "V1"), TestUtils.createArrayProperty("Array", [], true), TestUtils.createStructProperty("Struct", {}, true), ], "Cat2-1-3": [ TestUtils.createPrimitiveStringProperty("Prop", "V1"), TestUtils.createArrayProperty("Array", [], true), TestUtils.createStructProperty("Struct", {}, true), ], "Cat2-2": [], "Cat2-2-1": [ TestUtils.createPrimitiveStringProperty("Prop", "V1"), TestUtils.createArrayProperty("Array", [], true), TestUtils.createStructProperty("Struct", {}, true), ], "Cat2-2-2": [ TestUtils.createPrimitiveStringProperty("Prop", "V1"), TestUtils.createArrayProperty("Array", [], true), TestUtils.createStructProperty("Struct", {}, true), ], "Cat2-2-3": [ TestUtils.createPrimitiveStringProperty("Prop", "V1"), TestUtils.createArrayProperty("Array", [], true), TestUtils.createStructProperty("Struct", {}, true), ], }, }, expectedLastItemData: { "Cat1_Cat1-1_Array1-1-1_Property1-1-1-5_4": { isLastInRootCategory: false, lastInNumberOfCategories: 1 }, "Cat1_Cat1-2_Array1-2-1_Property1-2-1-5_4": { isLastInRootCategory: false, lastInNumberOfCategories: 1 }, "Cat1_Cat1-3_Array1-3-1": { isLastInRootCategory: true, lastInNumberOfCategories: 2 }, "Cat2_Cat2-1_Cat2-1-1": { isLastInRootCategory: false, lastInNumberOfCategories: 0 }, "Cat2_Cat2-1_Cat2-1-2_Struct": { isLastInRootCategory: false, lastInNumberOfCategories: 1 }, "Cat2_Cat2-1_Cat2-1-3": { isLastInRootCategory: false, lastInNumberOfCategories: 1 }, "Cat2_Cat2-2": { isLastInRootCategory: true, lastInNumberOfCategories: 1 }, }, unexistingItemKey: "Cat2_Struct2_does not exist", }, ]; let factory: IMutableGridItemFactory; beforeEach(() => { factory = new MutableGridItemFactory(); }); describe("Initialize MutablePropertyGridModel correctly", () => { let createCategorySpy: sinon.SinonSpy<any, any>; let createPropertySpy: sinon.SinonSpy<any, any>; beforeEach(() => { createCategorySpy = sinon.spy(factory, "createGridCategory"); createPropertySpy = sinon.spy(factory, "createCategorizedProperty"); }); for (const testCase of testCases) { it(testCase.testName, () => { new MutablePropertyGridModel(testCase.propertyData, factory); const expectedFlatProperties = GridUtils.getFlattenedPropertyData(testCase.propertyData); const expectedCategories = expectedFlatProperties.filter((property) => !(property.item instanceof PropertyRecord)); const expectedRecords = expectedFlatProperties.filter((property) => property.item instanceof PropertyRecord); expect(createCategorySpy.callCount).to.be.equal(expectedCategories.length); expectedCategories.forEach((category) => expect(createCategorySpy.calledWith(category, testCase.propertyData.records, factory))); expect(createPropertySpy.callCount).to.be.equal(expectedRecords.length); }); } }); describe("getFlatGrid", () => { for (const testCase of testCases) { it(testCase.testName, () => { const gridModel = new MutablePropertyGridModel(testCase.propertyData, factory); const visibleGrid = gridModel.getFlatGrid(); const expectedFlatGrid = GridUtils.getFlattenedPropertyData(testCase.propertyData, false); visibleGrid.forEach((gridItem, index) => { const expectedProperty = expectedFlatGrid[index]; GridUtils.assertGridItem(gridItem, expectedProperty); }); }); } }); describe("getVisibleFlatGrid", () => { for (const testCase of testCases) { it(testCase.testName, () => { const gridModel = new MutablePropertyGridModel(testCase.propertyData, factory); const visibleGrid = gridModel.getVisibleFlatGrid(); const expectedFlatGrid = GridUtils.getFlattenedPropertyData(testCase.propertyData, true); visibleGrid.forEach((gridItem, index) => { const expectedProperty = expectedFlatGrid[index]; GridUtils.assertGridItem(gridItem, expectedProperty); }); }); } }); function assertGridModel(gridModel: MutablePropertyGridModel, expectedFlatGrid: FlattenedProperty[], lastItemData?: GridModelLastItemData) { expectedFlatGrid.forEach((expectedProperty) => { const gridItem = gridModel.getItem(expectedProperty.selectionKey); GridUtils.assertGridItem(gridItem, expectedProperty); if (lastItemData) { const expectedLastItemData = lastItemData[gridItem.selectionKey] ?? { isLastInRootCategory: false, lastInNumberOfCategories: 0 }; expect(gridItem.lastInNumberOfCategories).to.be.equal(expectedLastItemData.lastInNumberOfCategories, `lastInNumberOfCategories does not match: ${gridItem.selectionKey}`); expect(gridItem.isLastInRootCategory).to.be.equal(expectedLastItemData.isLastInRootCategory, `isLastInRootCategory does not match: ${gridItem.selectionKey}`); } }); } describe("getItem", () => { for (const testCase of testCases) { it(`Throws when getting item that does not exist: ${testCase.testName}`, () => { const gridModel = new MutablePropertyGridModel(testCase.propertyData, factory); expect(() => gridModel.getItem(testCase.unexistingItemKey)).to.throw(Error, `Grid item at provided key not found: ${testCase.unexistingItemKey}`); }); it(`Gets visible items: ${testCase.testName}`, () => { const gridModel = new MutablePropertyGridModel(testCase.propertyData, factory); const expectedFlatGrid = GridUtils.getFlattenedPropertyData(testCase.propertyData, true); assertGridModel(gridModel, expectedFlatGrid, testCase.expectedLastItemData); }); it(`Gets all items: ${testCase.testName}`, () => { const gridModel = new MutablePropertyGridModel(testCase.propertyData, factory); const expectedFlatGrid = GridUtils.getFlattenedPropertyData(testCase.propertyData, false); assertGridModel(gridModel, expectedFlatGrid); }); } }); describe("getRootCategories", () => { for (const testCase of testCases) { it(`${testCase.testName}`, () => { const gridModel = new MutablePropertyGridModel(testCase.propertyData, factory); const rootCategories = gridModel.getRootCategories(); rootCategories.forEach((category, index) => GridUtils.assertCategoryEquals(category, testCase.propertyData.categories[index])); }); } }); });
the_stack
"use strict"; import "aurelia-polyfills"; import { TemplatingBindingLanguage, InterpolationBindingExpression } from "aurelia-templating-binding"; import { ViewResources, BindingLanguage, BehaviorInstruction } from "aurelia-templating"; import { AccessMember, AccessScope, AccessKeyed, Expression, NameExpression, ValueConverter, ListenerExpression } from "aurelia-binding"; import { Container } from "aurelia-dependency-injection"; import * as ts from "typescript"; import * as Path from "path"; import { Rule, Parser, ParserState, Issue, IssueSeverity } from "template-lint"; import { Reflection } from "../reflection"; import { AureliaReflection } from '../aurelia-reflection'; import { ASTBuilder, ASTElementNode, ASTTextNode, ASTNode, ASTAttribute, ASTContext, FileLoc } from "../ast"; import Node = ts.Node; import NodeArray = ts.NodeArray; import Decorator = ts.Decorator; import Identifier = ts.Identifier; /** * Rule to ensure static type usage is valid */ export class BindingRule extends ASTBuilder { public reportBindingAccess = true; public reportExceptions = false; public reportUnresolvedViewModel = false; public localProvidors = ["ref", "repeat.for", "if.bind", "with.bind"]; public restrictedAccess = ["private", "protected"]; public localOverride?= new Map<string, Array<{ name: string, value: any }>>(); constructor( private reflection: Reflection, auReflection: AureliaReflection, opt?: { reportBindingSyntax?: boolean, reportBindingAccess?: boolean, reportUnresolvedViewModel?: boolean, reportExceptions?: boolean, localProvidors?: string[], localOverride?: Map<string, Array<{ name: string, typeValue: any }>> restrictedAccess?: string[] }) { super(auReflection); if (opt) Object.assign(this, opt); } init(parser: Parser, path?: string) { super.init(parser); this.root.context = this.resolveViewModel(path); } finalise(): Issue[] { if (this.reportBindingAccess) { try { if (this.root.context != null) this.examineNode(this.root); } catch (error) { if (this.reportExceptions) this.reportIssue(new Issue({ message: error, line: -1, column: -1 })); } } return super.finalise(); } private examineNode(node: ASTNode) { if (node instanceof ASTElementNode) { this.examineElementNode(node); //triage #77 if (node.attrs.find(x => x.name == "slot" || x.name == "replace-part")) return; } else if (node instanceof ASTTextNode) { this.examineTextNode(node); } if (node.children == null) return; node.children.forEach(child => { this.examineNode(child); }); } private examineElementNode(node: ASTElementNode) { let attrs = node.attrs.sort((a, b) => { var ai = this.localProvidors.indexOf(a.name); var bi = this.localProvidors.indexOf(b.name); if (ai == -1 && bi == -1) return 0; if (ai == -1) return 1; if (bi == -1) return -1; return ai < bi ? -1 : 1; }); if (this.localOverride.has(node.tag)) { node.locals.push(...this.localOverride.get(node.tag).map(x => new ASTContext(x))); } for (let i = 0, ii = attrs.length; i < ii; ++i) { let attr = attrs[i]; this.examineAttribute(node, attr); } } private examineTextNode(node: ASTTextNode) { let exp = <any>node.expression; if (!exp) return; if (exp.constructor.name == "InterpolationBindingExpression") this.examineInterpolationExpression(node, exp); } private examineAttribute(node: ASTElementNode, attr: ASTAttribute) { let instruction = attr.instruction; if (instruction == null) return; let instructionName = instruction.constructor.name; switch (instructionName) { case "BehaviorInstruction": { this.examineBehaviorInstruction(node, <BehaviorInstruction>instruction); break; } case "ListenerExpression": { this.examineListenerExpression(node, <ListenerExpression>instruction); break; } case "NameExpression": { if (attr.name == "ref") { var name = instruction.sourceExpression.name; var root = this.resolveRoot(node); root.locals.push(new ASTContext({ name: name, type: <ts.TypeNode>ts.createNode(ts.SyntaxKind.AnyKeyword) })); } this.examineNameExpression(node, <NameExpression>instruction); break; } default: { if (this.reportExceptions) this.reportIssue(new Issue({ message: `Unknown instruction type: ${instructionName}`, line: attr.location.line })); } } } private examineBehaviorInstruction(node: ASTElementNode, instruction: BehaviorInstruction) { let attrName = instruction.attrName; let attrLoc = node.location; switch (attrName) { case "repeat": { let varKey = <string>instruction.attributes["key"]; let varValue = <string>instruction.attributes["value"]; let varLocal = <string>instruction.attributes["local"]; let source = instruction.attributes["items"]; let chain = this.flattenAccessChain(source.sourceExpression); let resolved = this.resolveAccessScopeToType(node, chain, new FileLoc(attrLoc.line, attrLoc.column)); let type = resolved ? resolved.type : null; let typeDecl = resolved ? resolved.typeDecl : null; if (varKey && varValue) { node.locals.push(new ASTContext({ name: varKey, type: <ts.TypeNode>ts.createNode(ts.SyntaxKind.StringKeyword) })); node.locals.push(new ASTContext({ name: varValue, type: type, typeDecl: typeDecl })); } else { node.locals.push(new ASTContext({ name: varLocal, type: type, typeDecl: typeDecl })); } node.locals.push(new ASTContext({ name: "$index", type: <ts.TypeNode>ts.createNode(ts.SyntaxKind.NumberKeyword) })); node.locals.push(new ASTContext({ name: "$first", type: <ts.TypeNode>ts.createNode(ts.SyntaxKind.BooleanKeyword) })); node.locals.push(new ASTContext({ name: "$last", type: <ts.TypeNode>ts.createNode(ts.SyntaxKind.BooleanKeyword) })); node.locals.push(new ASTContext({ name: "$odd", type: <ts.TypeNode>ts.createNode(ts.SyntaxKind.BooleanKeyword) })); node.locals.push(new ASTContext({ name: "$even", type: <ts.TypeNode>ts.createNode(ts.SyntaxKind.BooleanKeyword) })); break; } case "with": { let source = instruction.attributes["with"]; let chain = this.flattenAccessChain(source.sourceExpression); let resolved = this.resolveAccessScopeToType(node, chain, new FileLoc(attrLoc.line, attrLoc.column)); if (resolved != null) node.context = resolved; break; } default: let attrExp = instruction.attributes[attrName]; let access = instruction.attributes[attrName].sourceExpression; if (attrExp.constructor.name == "InterpolationBindingExpression") this.examineInterpolationExpression(node, attrExp); else { let chain = this.flattenAccessChain(access); let resolved = this.resolveAccessScopeToType(node, chain, new FileLoc(attrLoc.line, attrLoc.column)); } }; } private examineListenerExpression(node: ASTElementNode, exp: any /*ListenerExpression*/) { let target: string = exp.targetEvent; let access = exp.sourceExpression; let chain = this.flattenAccessChain(access); let resolved = this.resolveAccessScopeToType(node, chain, node.location); node.locals.push(new ASTContext({ name: "$event" })); for (var arg of access.args) { let access = arg; let chain = this.flattenAccessChain(access); let resolved = this.resolveAccessScopeToType(node, chain, node.location); } node.locals.pop(); } private examineNameExpression(node: ASTElementNode, exp: any /*NamedExpression*/) { let access = exp.sourceExpression; let chain = this.flattenAccessChain(access); let resolved = this.resolveAccessScopeToType(node, chain, node.location); } private examineInterpolationExpression(node: ASTNode, exp: any) { if (!exp || !node) return; let lineOffset = 0; let column = node.location.column; exp.parts.forEach(part => { if (part.name !== undefined) { let chain = this.flattenAccessChain(part); if (chain.length > 0) this.resolveAccessScopeToType(node, chain, new FileLoc(node.location.line + lineOffset, column)); } else if ((<string>part).match !== undefined) { let lines = (<string>part).split(/\n|\r/); if (lines && lines.length > 1) { lineOffset += lines.length; column = lines[lines.length - 1].length + 1; } } }); } private resolveRoot(node: ASTNode): ASTNode { while (node.parent) node = node.parent; return node; } private resolveViewModel(path: string): ASTContext { if (!path || path.trim() == "") return null; let viewFileInfo = Path.parse(path); let viewModelFile = Path.join(viewFileInfo.dir, `${viewFileInfo.name}`); let viewName = this.toSymbol(viewFileInfo.name); let viewModelSource = this.reflection.pathToSource[viewModelFile]; if (!viewModelSource) { if (this.reportUnresolvedViewModel) { this.reportIssue( new Issue({ message: `no view-model source-file found`, detail: viewModelFile, line: -1, column: -1, severity: IssueSeverity.Warning })); } return null; } let classes = <ts.ClassDeclaration[]>viewModelSource.statements.filter(x => x.kind == ts.SyntaxKind.ClassDeclaration); if (classes == null || classes.length == 0) { if (this.reportUnresolvedViewModel) { this.reportIssue( new Issue({ message: `no classes found in view-model source-file`, detail: viewModelFile, line: -1, column: -1, severity: IssueSeverity.Warning })); } return null; } let first = classes[0]; let context = new ASTContext(); context.name = first.name.getText(); context.typeDecl = first; return context; } private resolveAccessScopeToType(node: ASTNode, chain: any[], loc: FileLoc): ASTContext { let access = chain[0]; let ancestor = <number>access.ancestor; let context = ASTNode.inheritContext(node, ancestor); let locals = ASTNode.inheritLocals(node, ancestor); return this.resolveAccessChainToType(node, context, locals, chain, loc); } private resolveAccessChainToType(node: ASTNode, context: ASTContext, locals: ASTContext[], chain: any[], loc: FileLoc): ASTContext { if (chain == null || chain.length == 0) return; let decl = context.typeDecl; let access = chain[0]; let resolved: ASTContext = null; if (access.constructor.name == "AccessMember" || access.constructor.name == "AccessScope" || access.constructor.name == "CallMember" || access.constructor.name == "CallScope") { let name = access.name; if (context.typeValue) { resolved = this.resolveValueContext(context.typeValue, name, loc); } else { if (!resolved) resolved = this.resolveLocalType(locals, name); if (!resolved) resolved = this.resolveStaticType(node, context, name, loc); }; } else if (access.constructor.name == "AccessKeyed") { let keyAccess = access.key; let keyChain = this.flattenAccessChain(keyAccess); let keyTypeDecl = this.resolveAccessScopeToType(node, keyChain, loc); resolved = new ASTContext({ name: context.name, type: context.type, typeDecl: context.typeDecl }); } if (!resolved) { return null; } if (chain.length == 1) { return resolved; } if (resolved.typeDecl == null) { return null; } return this.resolveAccessChainToType(node, resolved, null, chain.slice(1), loc); } private resolveValueContext(value: any, memberName: string, loc: FileLoc): ASTContext { if (!value) return null; let resolved = value[memberName]; if (resolved === undefined) { this.reportUnresolvedAccessObjectIssue(memberName, value.constructor.name, loc); return null; } return new ASTContext({ name: memberName /*,typeValue: resolved*/ }); } private resolveLocalType(locals: ASTContext[], memberName: string): ASTContext { if (!locals) return null; let localVar = locals.find(x => x.name == memberName); return localVar; } private resolveStaticType(node: ASTNode, context: ASTContext, memberName: string, loc: FileLoc): ASTContext { if (context == null || context.typeDecl == null) return null; let decl = context.typeDecl; let memberType: ts.TypeNode; let member = null; switch (decl.kind) { case ts.SyntaxKind.ClassDeclaration: { const classDecl = <ts.ClassDeclaration>decl; let members = this.resolveClassMembers(classDecl); member = members .filter(x => x.kind == ts.SyntaxKind.PropertyDeclaration || x.kind == ts.SyntaxKind.MethodDeclaration || x.kind == ts.SyntaxKind.GetAccessor) .sort((a, b) => { let sa = (a.flags & ts.NodeFlags.Static); let sb = (b.flags & ts.NodeFlags.Static); return sa - sb; }) .find(x => (<any>x.name).text == memberName); if (member) { /* //#140 - doesn't support if (member.kind === ts.SyntaxKind.GetAccessor) { this.checkDecorators(node, member, context, loc); } */ memberType = this.reflection.resolveClassElementType(member); } else { [member, memberType] = this.findMemberInCtorDecls(classDecl, memberName); } if (!member) { // "dynamic" members could be defined using index signature: `[x: string]: number;` member = members.filter(x => x.kind == ts.SyntaxKind.IndexSignature).pop(); } if (!member) break; } break; case ts.SyntaxKind.InterfaceDeclaration: { let members = this.resolveInterfaceMembers(<ts.InterfaceDeclaration>decl); member = members .filter(x => x.kind == ts.SyntaxKind.PropertySignature || x.kind == ts.SyntaxKind.MethodSignature || x.kind == ts.SyntaxKind.GetAccessor) .find(x => x.name.getText() === memberName); if (!member) { // "dynamic" members could be defined using index signature: `[x: string]: number;` member = members.filter(x => x.kind == ts.SyntaxKind.IndexSignature).pop(); } if (!member) break; memberType = this.reflection.resolveTypeElementType(member); } break; default: //console.log("Unhandled Kind"); } if (!member) { this.reportUnresolvedAccessMemberIssue(memberName, decl, loc); return null; } if (!memberType) return null; if (this.restrictedAccess.length > 0) { const isPrivate = member.flags & ts.NodeFlags.Private; const isProtected = member.flags & ts.NodeFlags.Protected; const restrictPrivate = this.restrictedAccess.indexOf("private") != -1; const restrictProtected = this.restrictedAccess.indexOf("protected") != -1; if (isPrivate && restrictPrivate || isProtected && restrictProtected) { const accessModifier = isPrivate ? "private" : "protected"; this.reportPrivateAccessMemberIssue(memberName, decl, loc, accessModifier); return null; } } let memberTypeName = this.reflection.resolveTypeName(memberType); let memberTypeDecl: ts.Declaration = this.reflection.getDeclForType((<ts.SourceFile>decl.parent), memberTypeName); let memberIsArray = member.type.kind == ts.SyntaxKind.ArrayType || memberType.getText().startsWith("Array"); //TODO: //let typeArgs = <args:ts.TypeReference[]> member.type.typeArguments; //The simpler solution here might be to create a copy of the generic type declaration and //replace the generic references with the arguments. return new ASTContext({ type: memberType, typeDecl: memberTypeDecl, typeValue: memberIsArray ? [] : null }); } private findMemberInCtorDecls(classDecl: ts.ClassDeclaration, memberName: string): [ts.ParameterDeclaration, ts.TypeNode] { do { let members = classDecl.members; const constr = <ts.ConstructorDeclaration>members.find(ce => ce.kind == ts.SyntaxKind.Constructor); if (constr) { const param: ts.ParameterDeclaration = constr.parameters.find(parameter => parameter.name.getText() === memberName); if (param && param.flags) { return [param, param.type]; } } let currentClass = classDecl; classDecl = null; if (currentClass.heritageClauses != null && currentClass.heritageClauses.length > 0) { let extend = currentClass.heritageClauses.find(x => x.token == ts.SyntaxKind.ExtendsKeyword); if (extend) { let extendType = extend.types[0]; let memberTypeDecl: ts.Declaration = this.reflection.getDeclForType((<ts.SourceFile>currentClass.parent), extendType.getText()); if (memberTypeDecl != null && memberTypeDecl.kind == ts.SyntaxKind.ClassDeclaration) { classDecl = <ts.ClassDeclaration>memberTypeDecl; } } } } while (classDecl != null); return [null, null]; } private checkDecorators(node: ASTNode, member, context: ASTContext, loc: FileLoc) { if (member.decorators) { const memberNode = <Node>member; const decorators: NodeArray<Decorator> = member.decorators; decorators.forEach((decorator) => { const decoratorExprNode = <any>decorator.expression; const expr = <Identifier>decoratorExprNode.expression; if (expr.text === "computedFrom") { var decoratorArguments = decoratorExprNode.arguments; const decoratorArgumentsAsText: string[] = decoratorArguments.map((decoratorArg) => decoratorArg.text); decoratorArgumentsAsText.forEach((computedDependencyText) => { var exp = this.auReflection.createTextExpression(`\$\{${computedDependencyText}\}`); if (exp) { this.examineInterpolationExpression(node, exp); } }); } }); } } private resolveClassMembers(classDecl: ts.ClassDeclaration): ts.NodeArray<ts.ClassElement> { var members = classDecl.members; if (!classDecl.heritageClauses) return members; for (let base of classDecl.heritageClauses) { for (let type of base.types) { let typeDecl = this.reflection.getDeclForType((<ts.SourceFile>classDecl.parent), type.getText()); if (typeDecl != null) { let baseMembers = this.resolveClassMembers(<ts.ClassDeclaration>typeDecl); members = <ts.NodeArray<ts.ClassElement>>members.concat(baseMembers); } } } return members; } private resolveInterfaceMembers(interfaceDecl: ts.InterfaceDeclaration): ts.NodeArray<ts.TypeElement> { var members = interfaceDecl.members; if (!interfaceDecl.heritageClauses) return members; for (let base of interfaceDecl.heritageClauses) { for (let type of base.types) { let typeDecl = this.reflection.getDeclForType((<ts.SourceFile>interfaceDecl.parent), type.getText()); if (typeDecl != null) { let baseMembers = this.resolveInterfaceMembers(<ts.InterfaceDeclaration>typeDecl); members = <ts.NodeArray<ts.TypeElement>>members.concat(baseMembers); } } } return members; } private flattenAccessChain(access) { let chain = []; while (access !== undefined) { if (access.constructor.name == "PrefixNot") access = access.expression; else { chain.push(access); access = access.object; } } return chain.reverse(); } private toSymbol(path: string): string { path = this.toCamelCase(path.trim()); return path.charAt(0).toUpperCase() + path.slice(1); } private toFile(symbol: string) { return this.toDashCase(symbol.trim()); } private toCamelCase(value: string) { return value.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); }); } private toDashCase(value: string) { return value.replace(/([a-z][A-Z])/g, function (g) { return g[0] + "-" + g[1].toLowerCase(); }); } private reportUnresolvedAccessObjectIssue(member: string, objectName: string, loc: FileLoc) { let msg = `cannot find '${member}' in object '${objectName}'`; let issue = new Issue({ message: msg, line: loc.line, column: loc.column, severity: IssueSeverity.Error }); this.reportIssue(issue); } private reportUnresolvedAccessMemberIssue(member: string, decl: ts.Declaration, loc: FileLoc) { let msg = `cannot find '${member}' in type '${decl.name.getText()}'`; let issue = new Issue({ message: msg, line: loc.line, column: loc.column, severity: IssueSeverity.Error }); this.reportIssue(issue); } private reportPrivateAccessMemberIssue(member: string, decl: ts.Declaration, loc: FileLoc, accessModifier: string) { let msg = `field '${member}' in type '${decl.name.getText()}' has ${accessModifier} access modifier`; let issue = new Issue({ message: msg, line: loc.line, column: loc.column, severity: IssueSeverity.Warning }); this.reportIssue(issue); } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages an Azure App Configuration Feature. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const rg = new azure.core.ResourceGroup("rg", {location: "West Europe"}); * const appconf = new azure.appconfiguration.ConfigurationStore("appconf", { * resourceGroupName: rg.name, * location: rg.location, * }); * const test = new azure.appconfiguration.ConfigurationFeature("test", { * configurationStoreId: appconf.id, * description: "test description", * label: `acctest-ackeylabel-%d`, * enabled: true, * }); * ``` * * ## Import * * App Configuration Features can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:appconfiguration/configurationFeature:ConfigurationFeature test /subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/resourceGroup1/providers/Microsoft.AppConfiguration/configurationStores/appConf1/AppConfigurationFeature/appConfFeature1/Label/label1 * ``` * * If you wish to import a key with an empty label then sustitute the label's name with `%00`, like this * * ```sh * $ pulumi import azure:appconfiguration/configurationFeature:ConfigurationFeature test /subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/resourceGroup1/providers/Microsoft.AppConfiguration/configurationStores/appConf1/AppConfigurationFeature/appConfFeature1/Label/%00 * ``` */ export class ConfigurationFeature extends pulumi.CustomResource { /** * Get an existing ConfigurationFeature resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ConfigurationFeatureState, opts?: pulumi.CustomResourceOptions): ConfigurationFeature { return new ConfigurationFeature(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:appconfiguration/configurationFeature:ConfigurationFeature'; /** * Returns true if the given object is an instance of ConfigurationFeature. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is ConfigurationFeature { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === ConfigurationFeature.__pulumiType; } /** * Specifies the id of the App Configuration. Changing this forces a new resource to be created. */ public readonly configurationStoreId!: pulumi.Output<string>; /** * The description of the App Configuration Feature. */ public readonly description!: pulumi.Output<string | undefined>; /** * The status of the App Configuration Feature. By default, this is set to false. */ public readonly enabled!: pulumi.Output<boolean | undefined>; public readonly etag!: pulumi.Output<string>; /** * The label of the App Configuration Feature. Changing this forces a new resource to be created. */ public readonly label!: pulumi.Output<string | undefined>; /** * Should this App Configuration Feature be Locked to prevent changes? */ public readonly locked!: pulumi.Output<boolean | undefined>; /** * The name of the App Configuration Feature. Changing this foces a new resource to be crearted. */ public readonly name!: pulumi.Output<string>; /** * A list of one or more numbers representing the value of the percentage required to enable this feature. */ public readonly percentageFilterValue!: pulumi.Output<number | undefined>; /** * A mapping of tags to assign to the resource. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * A `targetingFilter` block as defined below. */ public readonly targetingFilters!: pulumi.Output<outputs.appconfiguration.ConfigurationFeatureTargetingFilter[] | undefined>; /** * A `targetingFilter` block `timewindowFilter` as defined below. */ public readonly timewindowFilters!: pulumi.Output<outputs.appconfiguration.ConfigurationFeatureTimewindowFilter[] | undefined>; /** * Create a ConfigurationFeature resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: ConfigurationFeatureArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ConfigurationFeatureArgs | ConfigurationFeatureState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ConfigurationFeatureState | undefined; inputs["configurationStoreId"] = state ? state.configurationStoreId : undefined; inputs["description"] = state ? state.description : undefined; inputs["enabled"] = state ? state.enabled : undefined; inputs["etag"] = state ? state.etag : undefined; inputs["label"] = state ? state.label : undefined; inputs["locked"] = state ? state.locked : undefined; inputs["name"] = state ? state.name : undefined; inputs["percentageFilterValue"] = state ? state.percentageFilterValue : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["targetingFilters"] = state ? state.targetingFilters : undefined; inputs["timewindowFilters"] = state ? state.timewindowFilters : undefined; } else { const args = argsOrState as ConfigurationFeatureArgs | undefined; if ((!args || args.configurationStoreId === undefined) && !opts.urn) { throw new Error("Missing required property 'configurationStoreId'"); } inputs["configurationStoreId"] = args ? args.configurationStoreId : undefined; inputs["description"] = args ? args.description : undefined; inputs["enabled"] = args ? args.enabled : undefined; inputs["etag"] = args ? args.etag : undefined; inputs["label"] = args ? args.label : undefined; inputs["locked"] = args ? args.locked : undefined; inputs["name"] = args ? args.name : undefined; inputs["percentageFilterValue"] = args ? args.percentageFilterValue : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["targetingFilters"] = args ? args.targetingFilters : undefined; inputs["timewindowFilters"] = args ? args.timewindowFilters : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(ConfigurationFeature.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering ConfigurationFeature resources. */ export interface ConfigurationFeatureState { /** * Specifies the id of the App Configuration. Changing this forces a new resource to be created. */ configurationStoreId?: pulumi.Input<string>; /** * The description of the App Configuration Feature. */ description?: pulumi.Input<string>; /** * The status of the App Configuration Feature. By default, this is set to false. */ enabled?: pulumi.Input<boolean>; etag?: pulumi.Input<string>; /** * The label of the App Configuration Feature. Changing this forces a new resource to be created. */ label?: pulumi.Input<string>; /** * Should this App Configuration Feature be Locked to prevent changes? */ locked?: pulumi.Input<boolean>; /** * The name of the App Configuration Feature. Changing this foces a new resource to be crearted. */ name?: pulumi.Input<string>; /** * A list of one or more numbers representing the value of the percentage required to enable this feature. */ percentageFilterValue?: pulumi.Input<number>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A `targetingFilter` block as defined below. */ targetingFilters?: pulumi.Input<pulumi.Input<inputs.appconfiguration.ConfigurationFeatureTargetingFilter>[]>; /** * A `targetingFilter` block `timewindowFilter` as defined below. */ timewindowFilters?: pulumi.Input<pulumi.Input<inputs.appconfiguration.ConfigurationFeatureTimewindowFilter>[]>; } /** * The set of arguments for constructing a ConfigurationFeature resource. */ export interface ConfigurationFeatureArgs { /** * Specifies the id of the App Configuration. Changing this forces a new resource to be created. */ configurationStoreId: pulumi.Input<string>; /** * The description of the App Configuration Feature. */ description?: pulumi.Input<string>; /** * The status of the App Configuration Feature. By default, this is set to false. */ enabled?: pulumi.Input<boolean>; etag?: pulumi.Input<string>; /** * The label of the App Configuration Feature. Changing this forces a new resource to be created. */ label?: pulumi.Input<string>; /** * Should this App Configuration Feature be Locked to prevent changes? */ locked?: pulumi.Input<boolean>; /** * The name of the App Configuration Feature. Changing this foces a new resource to be crearted. */ name?: pulumi.Input<string>; /** * A list of one or more numbers representing the value of the percentage required to enable this feature. */ percentageFilterValue?: pulumi.Input<number>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A `targetingFilter` block as defined below. */ targetingFilters?: pulumi.Input<pulumi.Input<inputs.appconfiguration.ConfigurationFeatureTargetingFilter>[]>; /** * A `targetingFilter` block `timewindowFilter` as defined below. */ timewindowFilters?: pulumi.Input<pulumi.Input<inputs.appconfiguration.ConfigurationFeatureTimewindowFilter>[]>; }
the_stack
import {setdifference} from '../common/base_util'; import {EngineConst} from '../common/engine'; import {AuditoryDescription} from './auditory_description'; import {Span} from './span'; export interface Tags { open?: EngineConst.personalityProps[]; close?: EngineConst.personalityProps[]; [personality: string]: any; } export type PauseValue = number | string; export interface Pause { pause: PauseValue; [personality: string]: any; } export type Markup = Pause | Tags; // TODO: Refactor into dedicated personality/markup data structure. /** * Merges pause personality annotations. * @param oldPause Previous pause annotation. * @param newPause New pause annotation. * @param opt_merge Function to combine pauses. By default we add them. * @return A personality annotation with the merged * pause values. */ export function mergePause( oldPause: Pause|null, newPause: Pause, opt_merge?: (p1: PauseValue, p2: PauseValue) => PauseValue): Pause { if (!oldPause) { return newPause; } return {pause: mergePause_(oldPause.pause, newPause.pause, opt_merge)}; } /** * Merges pause personality annotations. * @param oldPause Previous pause annotation. * @param newPause New pause annotation. * @param opt_merge Function to combine pauses. By default we add them. * @return A personality annotation with the merged pause * values. */ function mergePause_( oldPause: PauseValue, newPause: PauseValue, opt_merge?: (p1: PauseValue, p2: PauseValue) => PauseValue): PauseValue { let merge = opt_merge || function(x, y) { // TODO (TS): Changes this from || to &&. if (typeof x === 'number' && typeof y === 'number') { return x + y; } if (typeof x === 'number') { return y; } if (typeof y === 'number') { return x; } return [oldPause, newPause].sort()[0]; }; return merge.call(null, oldPause, newPause); } /** * Merges new personality into the old personality markup. * @param oldPers Old personality markup. * @param newPers New personality markup. */ export function mergeMarkup(oldPers: Tags, newPers: Tags) { delete oldPers.open; newPers.close.forEach(x => delete oldPers[x]); newPers.open.forEach(x => oldPers[x] = newPers[x]); let keys = Object.keys(oldPers); oldPers.open = keys as EngineConst.personalityProps[]; } /** * Sorts a list of opening tags by order of which is closed last. * If more than two elements are opened at the same, we need to look ahead in * which order they will be closed. * @param open The list of opening tags. * @param descrs The rest descriptions. * @return The sorted array. */ export function sortClose( open: EngineConst.personalityProps[], descrs: Tags[]): EngineConst.personalityProps[] { if (open.length <= 1) { return open; } let result: EngineConst.personalityProps[] = []; for (let i = 0, descr; descr = descrs[i], open.length; i++) { if (!descr.close || !descr.close.length) { continue; } descr.close.forEach(function(x) { let index = open.indexOf(x); if (index !== -1) { result.unshift(x); open.splice(index, 1); } }); } return result; } // The procedure transforms lists of descriptions into the internal format of // markup elements. /** * The range of personality annotations in the current list of descriptions. */ let PersonalityRanges_: {[key: string]: number[]} = {}; /** * The range of personality annotations. */ let LastOpen_: EngineConst.personalityProps[][] = []; /** * Computes a markup list. Careful this is destructive on the description list. * @param descrs The list of descriptions. * @return Markup list. */ export function personalityMarkup(descrs: AuditoryDescription[]): Markup[] { PersonalityRanges_ = {}; LastOpen_ = []; let result: Markup[] = []; let currentPers = {}; for (let i = 0, descr; descr = descrs[i]; i++) { let pause: Pause = null; let span = descr.descriptionSpan(); let pers: Markup = descr.personality; let join = pers[EngineConst.personalityProps.JOIN]; delete pers[EngineConst.personalityProps.JOIN]; if (typeof pers[EngineConst.personalityProps.PAUSE] !== 'undefined') { pause = {[EngineConst.personalityProps.PAUSE]: pers[EngineConst.personalityProps.PAUSE]}; // TODO (TS): Look at that once more! delete pers[EngineConst.personalityProps.PAUSE]; } let diff = personalityDiff_(pers, currentPers); // TODO: Replace last parameter by global parameter, depending on format. appendMarkup_(result, span, diff, join, pause, true); } result = result.concat(finaliseMarkup_()); result = simplifyMarkup_(result); return result; } /** * Appends an element to the partial markup list. If the last markup entry and * the new element are either both span or pause elements it joins * them. Otherwise the new element is appended. * @param markup The markup list. * @param element A single markup element. */ function appendElement_(markup: Markup[], element: Markup) { let last = markup[markup.length - 1]; if (!last) { markup.push(element); return; } if (isSpanElement(element) && isSpanElement(last)) { if (typeof last.join === 'undefined') { last.span = last.span.concat(element.span); return; } let lstr = last['span'].pop(); let fstr = element['span'].shift(); last['span'].push(lstr + last.join + fstr); last['span'] = last['span'].concat(element.span); last.join = element.join; return; } if (isPauseElement(element) && isPauseElement(last)) { last.pause = mergePause_(last.pause, element.pause); return; } markup.push(element); } /** * Simplification of markup sequence. Currently uses one technique only. * @param markup Markup list. * @return Simplified markup list. */ function simplifyMarkup_(markup: Markup[]): Markup[] { let lastPers: Markup = {}; let result = []; for (let i = 0, element; element = markup[i]; i++) { if (!isMarkupElement(element)) { appendElement_(result, element); continue; } if (!element.close || element.close.length !== 1 || element.open.length) { copyValues_(element, lastPers); result.push(element); continue; } let nextElement = markup[i + 1]; if (!nextElement || isSpanElement(nextElement)) { copyValues_(element, lastPers); result.push(element); continue; } let pauseElement = isPauseElement(nextElement) ? nextElement : null; if (pauseElement) { nextElement = markup[i + 2]; } if (nextElement && isMarkupElement(nextElement) && nextElement.open[0] === element.close[0] && !nextElement.close.length && nextElement[nextElement.open[0]] === lastPers[nextElement.open[0]]) { if (pauseElement) { appendElement_(result, pauseElement); i = i + 2; } else { i = i + 1; } } else { copyValues_(element, lastPers); result.push(element); } } return result; } /** * Copies values from one markup object to the other. * @param from Source element. * @param to Target element. */ function copyValues_(from: Markup, to: Markup) { if (from['rate']) { to['rate'] = from['rate']; } if (from['pitch']) { to['pitch'] = from['pitch']; } if (from['volume']) { to['volume'] = from['volume']; } } /** * Computes the final markup elements, if necessary. * @return Markup list. */ function finaliseMarkup_(): Markup[] { let final = []; for (let i = LastOpen_.length - 1; i >= 0; i--) { let pers = LastOpen_[i]; if (pers.length) { let markup: Markup = {open: [], close: []}; for (let j = 0; j < pers.length; j++) { let per = pers[j]; markup.close.push(per); markup[per] = 0; } final.push(markup); } } return final; } /** * Predicate to check if the markup element is a pause. * @param element An element of the markup list. * @return True if this is a pause element. */ export function isMarkupElement(element: Markup): boolean { return typeof element === 'object' && element.open; } /** * Predicate to check if the markup element is a pause. * @param element An element of the markup list. * @return True if this is a pause element. */ export function isPauseElement(element: Markup): boolean { return typeof element === 'object' && Object.keys(element).length === 1 && Object.keys(element)[0] === EngineConst.personalityProps.PAUSE; } /** * Predicate to check if the markup element is a span. * @param element An element of the markup list. * @return True if this is a span element. */ export function isSpanElement(element: Markup): boolean { let keys = Object.keys(element); return typeof element === 'object' && (keys.length === 1 && keys[0] === 'span' || keys.length === 2 && (keys[0] === 'span' && keys[1] === 'join' || keys[1] === 'span' && keys[0] === 'join')); } /** * Appends content to the current markup list. * @param markup The markup list. * @param span A content span. * @param pers A personality annotation. * @param join An optional joiner string. * @param pause A pause annotation. * @param opt_merge Flag that specifies subsequent pauses are to be * merged. */ function appendMarkup_( markup: Markup[], span: Span, pers: {[key: string]: number}, join: string, pause: Pause, merge: boolean = false) { if (merge) { let last = markup[markup.length - 1]; let oldJoin; if (last) { oldJoin = last[EngineConst.personalityProps.JOIN]; } if (last && !span.speech && pause && isPauseElement(last)) { let pauseProp = EngineConst.personalityProps.PAUSE; // Merging could be done using max or min or plus. last[pauseProp] = mergePause_(last[pauseProp], pause[pauseProp]); pause = null; } if (last && span.speech && Object.keys(pers).length === 0 && isSpanElement(last)) { // TODO: Check that out if this works with spans. if (typeof oldJoin !== 'undefined') { let lastSpan = last['span'].pop(); span = new Span( lastSpan.speech + oldJoin + span.speech, lastSpan.attributes); } last['span'].push(span); span = new Span('', {}); last[EngineConst.personalityProps.JOIN] = join; } } if (Object.keys(pers).length !== 0) { markup.push(pers); } if (span.speech) { markup.push({span: [span], join: join}); } if (pause) { markup.push(pause); } } /** * Compute the difference of two personality annotations. * @param current The current personality annotation. * @param old The previous personality annotation. * @return The difference between the two annotations. */ function personalityDiff_( current: {[key: string]: number}, old: {[key: string]: number}): {[key: string]: number} { if (!old) { return current; } let result: Markup = {}; for (let prop of EngineConst.personalityPropList) { let currentValue = current[prop]; let oldValue = old[prop]; if (!currentValue && !oldValue || currentValue && oldValue && currentValue === oldValue) { continue; } let value = currentValue || 0; // TODO: Simplify if (!isMarkupElement(result)) { result.open = []; result.close = []; } if (!currentValue) { result.close.push(prop); } if (!oldValue) { result.open.push(prop); } if (oldValue && currentValue) { result.close.push(prop); result.open.push(prop); } old[prop] = value; result[prop] = value; PersonalityRanges_[prop] ? PersonalityRanges_[prop].push(value) : PersonalityRanges_[prop] = [value]; } if (isMarkupElement(result)) { // Cases: // Deal first with close: // Let C = close set, LO = last open, // LO' = LO \ C; // C = C \ LO; // LO = LO'; // if LO = {} remove LO; // if C = {} done; // LO = LO u LO-1; // if LO != {} // close elements in LO; // open elements in LO with values from oldValue; // remove LO; // repeat; let c = result.close.slice(); while (c.length > 0) { let lo = LastOpen_.pop(); let loNew = setdifference(lo, c); c = setdifference(c, lo); lo = loNew; if (c.length === 0) { if (lo.length !== 0) { LastOpen_.push(lo); } continue; } if (lo.length === 0) { continue; } result.close = result.close.concat(lo); result.open = result.open.concat(lo); for (let i = 0, open; open = lo[i]; i++) { result[open] = old[open]; } } LastOpen_.push(result.open); } return result; }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * A `CryptoKey` represents a logical key that can be used for cryptographic operations. * * > **Note:** CryptoKeys cannot be deleted from Google Cloud Platform. * Destroying a provider-managed CryptoKey will remove it from state * and delete all CryptoKeyVersions, rendering the key unusable, but *will * not delete the resource from the project.* When the provider destroys these keys, * any data previously encrypted with these keys will be irrecoverable. * For this reason, it is strongly recommended that you add lifecycle hooks * to the resource to prevent accidental destruction. * * To get more information about CryptoKey, see: * * * [API documentation](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys) * * How-to Guides * * [Creating a key](https://cloud.google.com/kms/docs/creating-keys#create_a_key) * * ## Example Usage * ### Kms Crypto Key Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const keyring = new gcp.kms.KeyRing("keyring", {location: "global"}); * const example_key = new gcp.kms.CryptoKey("example-key", { * keyRing: keyring.id, * rotationPeriod: "100000s", * }); * ``` * ### Kms Crypto Key Asymmetric Sign * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const keyring = new gcp.kms.KeyRing("keyring", {location: "global"}); * const example_asymmetric_sign_key = new gcp.kms.CryptoKey("example-asymmetric-sign-key", { * keyRing: keyring.id, * purpose: "ASYMMETRIC_SIGN", * versionTemplate: { * algorithm: "EC_SIGN_P384_SHA384", * }, * }); * ``` * * ## Import * * CryptoKey can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:kms/cryptoKey:CryptoKey default {{key_ring}}/cryptoKeys/{{name}} * ``` * * ```sh * $ pulumi import gcp:kms/cryptoKey:CryptoKey default {{key_ring}}/{{name}} * ``` */ export class CryptoKey extends pulumi.CustomResource { /** * Get an existing CryptoKey resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: CryptoKeyState, opts?: pulumi.CustomResourceOptions): CryptoKey { return new CryptoKey(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:kms/cryptoKey:CryptoKey'; /** * Returns true if the given object is an instance of CryptoKey. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is CryptoKey { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === CryptoKey.__pulumiType; } /** * The period of time that versions of this key spend in the DESTROY_SCHEDULED state before transitioning to DESTROYED. * If not specified at creation time, the default duration is 24 hours. */ public readonly destroyScheduledDuration!: pulumi.Output<string>; /** * Whether this key may contain imported versions only. */ public readonly importOnly!: pulumi.Output<boolean>; /** * The KeyRing that this key belongs to. * Format: `'projects/{{project}}/locations/{{location}}/keyRings/{{keyRing}}'`. */ public readonly keyRing!: pulumi.Output<string>; /** * Labels with user-defined metadata to apply to this resource. */ public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>; /** * The resource name for the CryptoKey. */ public readonly name!: pulumi.Output<string>; /** * The immutable purpose of this CryptoKey. See the * [purpose reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys#CryptoKeyPurpose) * for possible inputs. * Default value is `ENCRYPT_DECRYPT`. * Possible values are `ENCRYPT_DECRYPT`, `ASYMMETRIC_SIGN`, and `ASYMMETRIC_DECRYPT`. */ public readonly purpose!: pulumi.Output<string | undefined>; /** * Every time this period passes, generate a new CryptoKeyVersion and set it as the primary. * The first rotation will take place after the specified period. The rotation period has * the format of a decimal number with up to 9 fractional digits, followed by the * letter `s` (seconds). It must be greater than a day (ie, 86400). */ public readonly rotationPeriod!: pulumi.Output<string | undefined>; /** * If set to true, the request will create a CryptoKey without any CryptoKeyVersions. * You must use the `gcp.kms.KeyRingImportJob` resource to import the CryptoKeyVersion. */ public readonly skipInitialVersionCreation!: pulumi.Output<boolean | undefined>; /** * A template describing settings for new crypto key versions. * Structure is documented below. */ public readonly versionTemplate!: pulumi.Output<outputs.kms.CryptoKeyVersionTemplate>; /** * Create a CryptoKey resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: CryptoKeyArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: CryptoKeyArgs | CryptoKeyState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as CryptoKeyState | undefined; inputs["destroyScheduledDuration"] = state ? state.destroyScheduledDuration : undefined; inputs["importOnly"] = state ? state.importOnly : undefined; inputs["keyRing"] = state ? state.keyRing : undefined; inputs["labels"] = state ? state.labels : undefined; inputs["name"] = state ? state.name : undefined; inputs["purpose"] = state ? state.purpose : undefined; inputs["rotationPeriod"] = state ? state.rotationPeriod : undefined; inputs["skipInitialVersionCreation"] = state ? state.skipInitialVersionCreation : undefined; inputs["versionTemplate"] = state ? state.versionTemplate : undefined; } else { const args = argsOrState as CryptoKeyArgs | undefined; if ((!args || args.keyRing === undefined) && !opts.urn) { throw new Error("Missing required property 'keyRing'"); } inputs["destroyScheduledDuration"] = args ? args.destroyScheduledDuration : undefined; inputs["importOnly"] = args ? args.importOnly : undefined; inputs["keyRing"] = args ? args.keyRing : undefined; inputs["labels"] = args ? args.labels : undefined; inputs["name"] = args ? args.name : undefined; inputs["purpose"] = args ? args.purpose : undefined; inputs["rotationPeriod"] = args ? args.rotationPeriod : undefined; inputs["skipInitialVersionCreation"] = args ? args.skipInitialVersionCreation : undefined; inputs["versionTemplate"] = args ? args.versionTemplate : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(CryptoKey.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering CryptoKey resources. */ export interface CryptoKeyState { /** * The period of time that versions of this key spend in the DESTROY_SCHEDULED state before transitioning to DESTROYED. * If not specified at creation time, the default duration is 24 hours. */ destroyScheduledDuration?: pulumi.Input<string>; /** * Whether this key may contain imported versions only. */ importOnly?: pulumi.Input<boolean>; /** * The KeyRing that this key belongs to. * Format: `'projects/{{project}}/locations/{{location}}/keyRings/{{keyRing}}'`. */ keyRing?: pulumi.Input<string>; /** * Labels with user-defined metadata to apply to this resource. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The resource name for the CryptoKey. */ name?: pulumi.Input<string>; /** * The immutable purpose of this CryptoKey. See the * [purpose reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys#CryptoKeyPurpose) * for possible inputs. * Default value is `ENCRYPT_DECRYPT`. * Possible values are `ENCRYPT_DECRYPT`, `ASYMMETRIC_SIGN`, and `ASYMMETRIC_DECRYPT`. */ purpose?: pulumi.Input<string>; /** * Every time this period passes, generate a new CryptoKeyVersion and set it as the primary. * The first rotation will take place after the specified period. The rotation period has * the format of a decimal number with up to 9 fractional digits, followed by the * letter `s` (seconds). It must be greater than a day (ie, 86400). */ rotationPeriod?: pulumi.Input<string>; /** * If set to true, the request will create a CryptoKey without any CryptoKeyVersions. * You must use the `gcp.kms.KeyRingImportJob` resource to import the CryptoKeyVersion. */ skipInitialVersionCreation?: pulumi.Input<boolean>; /** * A template describing settings for new crypto key versions. * Structure is documented below. */ versionTemplate?: pulumi.Input<inputs.kms.CryptoKeyVersionTemplate>; } /** * The set of arguments for constructing a CryptoKey resource. */ export interface CryptoKeyArgs { /** * The period of time that versions of this key spend in the DESTROY_SCHEDULED state before transitioning to DESTROYED. * If not specified at creation time, the default duration is 24 hours. */ destroyScheduledDuration?: pulumi.Input<string>; /** * Whether this key may contain imported versions only. */ importOnly?: pulumi.Input<boolean>; /** * The KeyRing that this key belongs to. * Format: `'projects/{{project}}/locations/{{location}}/keyRings/{{keyRing}}'`. */ keyRing: pulumi.Input<string>; /** * Labels with user-defined metadata to apply to this resource. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The resource name for the CryptoKey. */ name?: pulumi.Input<string>; /** * The immutable purpose of this CryptoKey. See the * [purpose reference](https://cloud.google.com/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys#CryptoKeyPurpose) * for possible inputs. * Default value is `ENCRYPT_DECRYPT`. * Possible values are `ENCRYPT_DECRYPT`, `ASYMMETRIC_SIGN`, and `ASYMMETRIC_DECRYPT`. */ purpose?: pulumi.Input<string>; /** * Every time this period passes, generate a new CryptoKeyVersion and set it as the primary. * The first rotation will take place after the specified period. The rotation period has * the format of a decimal number with up to 9 fractional digits, followed by the * letter `s` (seconds). It must be greater than a day (ie, 86400). */ rotationPeriod?: pulumi.Input<string>; /** * If set to true, the request will create a CryptoKey without any CryptoKeyVersions. * You must use the `gcp.kms.KeyRingImportJob` resource to import the CryptoKeyVersion. */ skipInitialVersionCreation?: pulumi.Input<boolean>; /** * A template describing settings for new crypto key versions. * Structure is documented below. */ versionTemplate?: pulumi.Input<inputs.kms.CryptoKeyVersionTemplate>; }
the_stack
import { EventEmitter } from 'eventemitter3'; // own modules import { ITaskOptions, ITaskTimerEvent, ITaskTimerOptions, ITimeInfo, Task as TTask, TaskCallback } from '.'; import { utils } from './utils'; /** * @private */ const DEFAULT_TIMER_OPTIONS: ITaskTimerOptions = Object.freeze({ interval: 1000, precision: true, stopOnCompleted: false }); /** * TaskTimer • https://github.com/onury/tasktimer * @license MIT * @copyright 2019, Onur Yıldırım <onur@cutepilot.com> */ // --------------------------- // EventEmitter Docs // --------------------------- /** * Calls each of the listeners registered for a given event name. * @name TaskTimer#emit * @function * * @param {TaskTimer.Event} eventName - The name of the event to be emitted. * @param {any} [data] - Data to be passed to event listeners. * * @returns {Boolean} - `true` if the event had listeners, else `false`. */ /** * Return an array listing the events for which the emitter has registered * listeners. * @name TaskTimer#eventNames * @function * * @returns {Array} - List of event names. */ /** * Adds the listener function to the end of the listeners array for the event * named `eventName`. No checks are made to see if the listener has already * been added. Multiple calls passing the same combination of `eventName` and * `listener` will result in the listener being added, and called, multiple * times. * @name TaskTimer#on * @function * @alias TaskTimer#addListener * @chainable * * @param {TaskTimer.Event} eventName - The name of the event to be added. * @param {Function} listener - The callback function to be invoked per event. * @param {*} [context=this] - The context to invoke the listener with. * * @returns {TaskTimer} - `{@link #TaskTimer|TaskTimer}` instance. * * @example * const timer = new TaskTimer(1000); * // add a listener to be invoked when timer has stopped. * timer.on(TaskTimer.Event.STOPPED, () => { * console.log('Timer has stopped!'); * }); * timer.start(); */ /** * Adds a one time listener function for the event named `eventName`. The next * time `eventName` is triggered, this `listener` is removed and then invoked. * @name TaskTimer#once * @function * @chainable * * @param {TaskTimer.Event} eventName - The name of the event to be added. * @param {Function} listener - The callback function to be invoked per event. * @param {*} [context=this] - The context to invoke the listener with. * * @returns {TaskTimer} - `{@link #TaskTimer|TaskTimer}` instance. */ /** * Removes the specified `listener` from the listener array for the event * named `eventName`. * @name TaskTimer#off * @function * @alias TaskTimer#removeListener * @chainable * * @param {TaskTimer.Event} eventName - The name of the event to be removed. * @param {Function} listener - The callback function to be invoked per event. * @param {*} [context=this] - Only remove the listeners that have this context. * @param {Boolean} [once=false] - Only remove one-time listeners. * * @returns {TaskTimer} - `{@link #TaskTimer|TaskTimer}` instance. */ /** * Gets the number of listeners listening to a given event. * @name TaskTimer#listenerCount * @function * * @param {TaskTimer.Event} eventName - The name of the event. * * @returns {Number} - The number of listeners. */ /** * Gets the listeners registered for a given event. * @name TaskTimer#listeners * @function * * @param {TaskTimer.Event} eventName - The name of the event. * * @returns {Array} - The registered listeners. */ /** * Removes all listeners, or those of the specified `eventName`. * @name TaskTimer#removeAllListeners * @function * @chainable * * @param {TaskTimer.Event} [eventName] - The name of the event to be removed. * * @returns {TaskTimer} - `{@link #TaskTimer|TaskTimer}` instance. */ /** * A timer utility for running periodic tasks on the given interval ticks. This * is useful when you want to run or schedule multiple tasks on a single timer * instance. * * This class extends `EventEmitter3` which is an `EventEmitter` implementation * for both Node and browser. For detailed information, refer to Node.js * documentation. * @class * @global * * @extends EventEmitter * * @see * {@link https://nodejs.org/api/events.html#events_class_eventemitter|EventEmitter} */ class TaskTimer extends EventEmitter { /** * Inner storage for Tasktimer. * @private */ private _: { opts: ITaskTimerOptions; state: TaskTimer.State; tasks: { [k: string]: TTask }; tickCount: number; taskRunCount: number; startTime: number; stopTime: number; completedTaskCount: number; // below are needed for precise interval. we need to inspect ticks and // elapsed time difference within the latest "continuous" session. in // other words, paused time should be ignored in these calculations. so // we need varibales saved after timer is resumed. resumeTime: number; hrResumeTime: [number, number]; tickCountAfterResume: number; }; /** * setTimeout reference used by the timmer. * @private */ private _timeoutRef: any; /** * setImmediate reference used by the timer. * @private */ private _immediateRef: any; /** * Timer run count storage. * @private */ private _runCount: number; // --------------------------- // CONSTRUCTOR // --------------------------- /** * Constructs a new `TaskTimer` instance with the given time interval (in * milliseconds). * @constructor * * @param {ITaskTimerOptions|number} [options] - Either TaskTimer options * or a base interval (in milliseconds). Since the tasks run on ticks * instead of millisecond intervals; this value operates as the base * resolution for all tasks. If you are running heavy tasks, lower interval * requires higher CPU power. This value can be updated any time by setting * the `interval` property on the instance. * * @example * const timer = new TaskTimer(1000); // milliseconds * // Execute some code on each tick... * timer.on('tick', () => { * console.log('tick count: ' + timer.tickCount); * console.log('elapsed time: ' + timer.time.elapsed + ' ms.'); * }); * // add a task named 'heartbeat' that runs every 5 ticks and a total of 10 times. * const task1 = { * id: 'heartbeat', * tickDelay: 20, // ticks (to wait before first run) * tickInterval: 5, // ticks (interval) * totalRuns: 10, // times to run * callback(task) { // can also be an async function, returning a promise * console.log(task.id + ' task has run ' + task.currentRuns + ' times.'); * } * }; * timer.add(task1).start(); */ constructor(options?: ITaskTimerOptions | number) { super(); this._timeoutRef = null; this._immediateRef = null; this._runCount = 0; this._reset(); this._.opts = {}; const opts = typeof options === 'number' ? { interval: options } : options || {} as any; this.interval = opts.interval; this.precision = opts.precision; this.stopOnCompleted = opts.stopOnCompleted; } // --------------------------- // PUBLIC (INSTANCE) PROPERTIES // --------------------------- /** * Gets or sets the base timer interval in milliseconds. * * Since the tasks run on ticks instead of millisecond intervals; this * value operates as the base resolution for all tasks. If you are running * heavy tasks, lower interval requires higher CPU power. This value can be * updated any time. * * @name TaskTimer#interval * @type {number} */ get interval(): number { return this._.opts.interval; } set interval(value: number) { this._.opts.interval = utils.getNumber(value, 20, DEFAULT_TIMER_OPTIONS.interval); } /** * Gets or sets whether timer precision enabled. * * Because of the single-threaded, asynchronous nature of JavaScript, each * execution takes a piece of CPU time, and the time they have to wait will * vary, depending on the load. This creates a latency and cumulative * difference in asynchronous timers; that gradually increase the * inacuraccy. `TaskTimer` overcomes this problem as much as possible: * * <li>The delay between each tick is auto-adjusted when it's off * due to task/CPU loads or clock drifts.</li> * <li>In Node.js, `TaskTimer` also makes use of `process.hrtime()` * high-resolution real-time. The time is relative to an arbitrary * time in the past (not related to the time of day) and therefore not * subject to clock drifts.</li> * <li>The timer may hit a synchronous / blocking task; or detect significant * time drift (longer than the base interval) due to JS event queue, which * cannot be recovered by simply adjusting the next delay. In this case, right * from the next tick onward; it will auto-recover as much as possible by * running "immediate" tasks until it reaches the proper time vs tick/run * balance.</li> * * <blockquote><i>Note that precision will be as high as possible but it still * can be off by a few milliseconds; depending on the CPU or the load.</i> * </blockquote> * @name TaskTimer#precision * @type {boolean} */ get precision(): boolean { return this._.opts.precision; } set precision(value: boolean) { this._.opts.precision = utils.getBool(value, DEFAULT_TIMER_OPTIONS.precision); } /** * Gets or sets whether the timer should automatically stop when all tasks * are completed. For this to take affect, all added tasks should have * `totalRuns` and/or `stopDate` configured. This option can be set/changed * at any time. * @name TaskTimer#stopOnCompleted * @type {boolean} */ get stopOnCompleted(): boolean { return this._.opts.stopOnCompleted; } set stopOnCompleted(value: boolean) { this._.opts.stopOnCompleted = utils.getBool(value, DEFAULT_TIMER_OPTIONS.stopOnCompleted); } /** * Gets the current state of the timer. * For possible values, see `TaskTimer.State` enumeration. * @name TaskTimer#state * @type {TaskTimer.State} * @readonly */ get state(): TaskTimer.State { return this._.state; } /** * Gets time information for the latest run of the timer. * `#time.started` indicates the start time of the timer. * `#time.stopped` indicates the stop time of the timer. (`0` if still running.) * `#time.elapsed` indicates the elapsed time of the timer. * @name TaskTimer#time * @type {ITimeInfo} * @readonly */ get time(): ITimeInfo { const { startTime, stopTime } = this._; const t: ITimeInfo = { started: startTime, stopped: stopTime, elapsed: 0 }; if (startTime) { const current = this.state !== TaskTimer.State.STOPPED ? Date.now() : stopTime; t.elapsed = current - startTime; } return Object.freeze(t); } /** * Gets the current tick count for the latest run of the timer. * This value will be reset to `0` when the timer is stopped or reset. * @name TaskTimer#tickCount * @type {Number} * @readonly */ get tickCount(): number { return this._.tickCount; } /** * Gets the current task count. Tasks remain even after the timer is * stopped. But they will be removed if the timer is reset. * @name TaskTimer#taskCount * @type {Number} * @readonly */ get taskCount(): number { return Object.keys(this._.tasks).length; } /** * Gets the total number of all task executions (runs). * @name TaskTimer#taskRunCount * @type {Number} * @readonly */ get taskRunCount(): number { return this._.taskRunCount; } /** * Gets the total number of timer runs, including resumed runs. * @name TaskTimer#runCount * @type {Number} * @readonly */ get runCount(): number { return this._runCount; } // --------------------------- // PUBLIC (INSTANCE) METHODS // --------------------------- /** * Gets the task with the given ID. * @memberof TaskTimer * * @param {String} id - ID of the task. * * @returns {Task} */ get(id: string): TTask { return this._.tasks[id] || null; } /** * Adds a collection of new tasks for the timer. * @memberof TaskTimer * @chainable * * @param {Task|ITaskOptions|TaskCallback|Array} task - Either a * single task, task options object or the callback function; or a mixture * of these as an array. * * @returns {TaskTimer} * * @throws {Error} - If a task callback is not set or a task with the given * name already exists. */ add(task: TTask | ITaskOptions | TaskCallback | Array<TTask | ITaskOptions | TaskCallback>): TaskTimer { if (!utils.isset(task)) { throw new Error('Either a task, task options or a callback is required.'); } utils.ensureArray(task).forEach((item: any) => this._add(item)); return this; } /** * Removes the task by the given name. * @memberof TaskTimer * @chainable * * @param {string|Task} task - Task to be removed. Either pass the * name or the task itself. * * @returns {TaskTimer} * * @throws {Error} - If a task with the given name does not exist. */ remove(task: string | TTask): TaskTimer { const id: string = typeof task === 'string' ? task : task.id; task = this.get(id); if (!id || !task) { throw new Error(`No tasks exist with ID: '${id}'.`); } // first decrement completed tasks count if this is a completed task. if (task.completed && this._.completedTaskCount > 0) this._.completedTaskCount--; this._.tasks[id] = null; delete this._.tasks[id]; this._emit(TaskTimer.Event.TASK_REMOVED, task); return this; } /** * Starts the timer and puts the timer in `RUNNING` state. If it's already * running, this will reset the start/stop time and tick count, but will not * reset (or remove) existing tasks. * @memberof TaskTimer * @chainable * * @returns {TaskTimer} */ start(): TaskTimer { this._stop(); this._.state = TaskTimer.State.RUNNING; this._runCount++; this._.tickCount = 0; this._.taskRunCount = 0; this._.stopTime = 0; this._markTime(); this._.startTime = Date.now(); this._emit(TaskTimer.Event.STARTED); this._run(); return this; } /** * Pauses the timer, puts the timer in `PAUSED` state and all tasks on hold. * @memberof TaskTimer * @chainable * * @returns {TaskTimer} */ pause(): TaskTimer { if (this.state !== TaskTimer.State.RUNNING) return this; this._stop(); this._.state = TaskTimer.State.PAUSED; this._emit(TaskTimer.Event.PAUSED); return this; } /** * Resumes the timer and puts the timer in `RUNNING` state; if previuosly * paused. In this state, all existing tasks are resumed. * @memberof TaskTimer * @chainable * * @returns {TaskTimer} */ resume(): TaskTimer { if (this.state === TaskTimer.State.IDLE) { this.start(); return this; } if (this.state !== TaskTimer.State.PAUSED) return this; this._runCount++; this._markTime(); this._.state = TaskTimer.State.RUNNING; this._emit(TaskTimer.Event.RESUMED); this._run(); return this; } /** * Stops the timer and puts the timer in `STOPPED` state. In this state, all * existing tasks are stopped and no values or tasks are reset until * re-started or explicitly calling reset. * @memberof TaskTimer * @chainable * * @returns {TaskTimer} */ stop(): TaskTimer { if (this.state !== TaskTimer.State.RUNNING) return this; this._stop(); this._.stopTime = Date.now(); this._.state = TaskTimer.State.STOPPED; this._emit(TaskTimer.Event.STOPPED); return this; } /** * Stops the timer and puts the timer in `IDLE` state. * This will reset the ticks and removes all tasks silently; meaning no * other events will be emitted such as `"taskRemoved"`. * @memberof TaskTimer * @chainable * * @returns {TaskTimer} */ reset(): TaskTimer { this._reset(); this._emit(TaskTimer.Event.RESET); return this; } // --------------------------- // PRIVATE (INSTANCE) METHODS // --------------------------- /** * @private */ private _emit(type: TaskTimer.Event, data?: any): boolean { const event: ITaskTimerEvent = { name: type, source: this, data }; return this.emit(type, event); } /** * Adds a new task for the timer. * @private * * @param {Task|ITaskOptions|TaskCallback} options - Either a task instance, * task options object or the callback function to be executed on tick * intervals. * * @returns {TaskTimer} * * @throws {Error} - If the task callback is not set or a task with the * given name already exists. */ private _add(options: TTask | ITaskOptions | TaskCallback): TaskTimer { if (typeof options === 'function') { options = { callback: options }; } if (utils.type(options) === 'object' && !options.id) { (options as ITaskOptions).id = this._getUniqueTaskID(); } if (this.get(options.id)) { throw new Error(`A task with id '${options.id}' already exists.`); } const task = options instanceof TTask ? options : new TTask(options); (task as any)._setTimer(this); this._.tasks[task.id] = task; this._emit(TaskTimer.Event.TASK_ADDED, task); return this; } /** * Stops the timer. * @private */ private _stop(): void { this._.tickCountAfterResume = 0; if (this._timeoutRef) { clearTimeout(this._timeoutRef); this._timeoutRef = null; } if (this._immediateRef) { utils.clearImmediate(this._immediateRef); this._immediateRef = null; } } /** * Resets the timer. * @private */ private _reset(): void { this._ = { opts: (this._ || {} as any).opts, state: TaskTimer.State.IDLE, tasks: {}, tickCount: 0, taskRunCount: 0, startTime: 0, stopTime: 0, completedTaskCount: 0, resumeTime: 0, hrResumeTime: null, tickCountAfterResume: 0 }; this._stop(); } /** * Called (by Task instance) when it has completed all of its runs. * @private */ // @ts-ignore: TS6133: declared but never read. private _taskCompleted(task: TTask): void { this._.completedTaskCount++; this._emit(TaskTimer.Event.TASK_COMPLETED, task); if (this._.completedTaskCount === this.taskCount) { this._emit(TaskTimer.Event.COMPLETED); if (this.stopOnCompleted) this.stop(); } if (task.removeOnCompleted) this.remove(task); } /** * Handler to be executed on each tick. * @private */ private _tick(): void { this._.state = TaskTimer.State.RUNNING; let id: string; let task: TTask; const tasks = this._.tasks; this._.tickCount++; this._.tickCountAfterResume++; this._emit(TaskTimer.Event.TICK); // tslint:disable:forin for (id in tasks) { task = tasks[id]; if (!task || !task.canRunOnTick) continue; // below will not execute if task is disabled or already // completed. (task as any)._run(() => { this._.taskRunCount++; this._emit(TaskTimer.Event.TASK, task); }); } this._run(); } /** * Marks the resume (or start) time in milliseconds or high-resolution time * if available. * @private */ private _markTime(): void { /* istanbul ignore if */ if (utils.BROWSER) { // tested separately this._.resumeTime = Date.now(); } else { this._.hrResumeTime = process.hrtime(); } } /** * Gets the time difference in milliseconds sinct the last resume or start * time. * @private */ private _getTimeDiff(): number { // Date.now() is ~2x faster than Date#getTime() /* istanbul ignore if */ if (utils.BROWSER) return Date.now() - this._.resumeTime; // tested separately const hrDiff = process.hrtime(this._.hrResumeTime); return Math.ceil((hrDiff[0] * 1000) + (hrDiff[1] / 1e6)); } /** * Runs the timer. * @private */ private _run(): void { if (this.state !== TaskTimer.State.RUNNING) return; let interval = this.interval; // we'll get a precise interval by checking if our clock is already // drifted. if (this.precision) { const diff = this._getTimeDiff(); // did we reach this expected tick count for the given time period? // calculated count should not be greater than tickCountAfterResume if (Math.floor(diff / interval) > this._.tickCountAfterResume) { // if we're really late, run immediately! this._immediateRef = utils.setImmediate(() => this._tick()); return; } // if we still have time but a bit off, update next interval. interval = interval - (diff % interval); } this._timeoutRef = setTimeout(() => this._tick(), interval); } /** * Gets a unique task ID. * @private */ private _getUniqueTaskID(): string { let num: number = this.taskCount; let id: string; while (!id || this.get(id)) { num++; id = 'task' + num; } return id; } } // --------------------------- // NAMESPACE // --------------------------- // tslint:disable:no-namespace /* istanbul ignore next */ /** @private */ namespace TaskTimer { /** * Represents the class that holds the configurations and the callback function * required to run a task. See {@link api/#Task|class information}. * @name TaskTimer.Task * @class */ export const Task = TTask; /** * Enumerates `TaskTimer` states. * @memberof TaskTimer * @enum {String} * @readonly */ export enum State { /** * Indicates that the timer is in `idle` state. * This is the initial state when the `TaskTimer` instance is first created. * Also when an existing timer is reset, it will be `idle`. * @type {String} */ IDLE = 'idle', /** * Indicates that the timer is in `running` state; such as when the timer is * started or resumed. * @type {String} */ RUNNING = 'running', /** * Indicates that the timer is in `paused` state. * @type {String} */ PAUSED = 'paused', /** * Indicates that the timer is in `stopped` state. * @type {String} */ STOPPED = 'stopped' } /** * Enumerates the `TaskTimer` event types. * @memberof TaskTimer * @enum {String} * @readonly */ export enum Event { /** * Emitted on each tick (interval) of `TaskTimer`. * @type {String} */ TICK = 'tick', /** * Emitted when the timer is put in `RUNNING` state; such as when the timer is * started. * @type {String} */ STARTED = 'started', /** * Emitted when the timer is put in `RUNNING` state; such as when the timer is * resumed. * @type {String} */ RESUMED = 'resumed', /** * Emitted when the timer is put in `PAUSED` state. * @type {String} */ PAUSED = 'paused', /** * Emitted when the timer is put in `STOPPED` state. * @type {String} */ STOPPED = 'stopped', /** * Emitted when the timer is reset. * @type {String} */ RESET = 'reset', /** * Emitted when a task is executed. * @type {String} */ TASK = 'task', /** * Emitted when a task is added to `TaskTimer` instance. * @type {String} */ TASK_ADDED = 'taskAdded', /** * Emitted when a task is removed from `TaskTimer` instance. * Note that this will not be emitted when `.reset()` is called; which * removes all tasks silently. * @type {String} */ TASK_REMOVED = 'taskRemoved', /** * Emitted when a task has completed all of its executions (runs) * or reached its stopping date/time (if set). Note that this event * will only be fired if the tasks has a `totalRuns` limit or a * `stopDate` value set. * @type {String} */ TASK_COMPLETED = 'taskCompleted', /** * Emitted when a task produces an error on its execution. * @type {String} */ TASK_ERROR = 'taskError', /** * Emitted when all tasks have completed all of their executions (runs) * or reached their stopping date/time (if set). Note that this event * will only be fired if all tasks have a `totalRuns` limit or a * `stopDate` value set. * @type {String} */ COMPLETED = 'completed' } } // --------------------------- // EXPORT // --------------------------- export { TaskTimer };
the_stack
import React, { useState, useCallback, useEffect } from "react"; import { css } from "emotion"; import get from "lodash/get"; import { useRouter } from "@webiny/react-router"; import { Form } from "@webiny/form"; import { Input } from "@webiny/ui/Input"; import { Select } from "@webiny/ui/Select"; import { useSnackbar } from "@webiny/app-admin/hooks/useSnackbar"; import { CircularProgress } from "@webiny/ui/Progress"; import { validation } from "@webiny/validation"; import { useMutation, useQueryLocale } from "../../hooks"; import { i18n } from "@webiny/app/i18n"; import { ButtonDefault } from "@webiny/ui/Button"; import * as UID from "@webiny/ui/Dialog"; import { Grid, Cell } from "@webiny/ui/Grid"; import { addModelToGroupCache, addModelToListCache } from "./cache"; import { CmsEditorContentModel, CmsModel } from "~/types"; import { useI18N } from "@webiny/app-i18n/hooks/useI18N"; import { CREATE_CONTENT_MODEL_FROM, LIST_MENU_CONTENT_GROUPS_MODELS, CreateCmsModelFromMutationResponse, CreateCmsModelFromMutationVariables, ListMenuCmsGroupsQueryResponse } from "../../viewsGraphql"; import { CmsGroup } from "~/admin/views/contentModelGroups/graphql"; import { CmsGroupOption } from "~/admin/views/contentModels/types"; const t = i18n.ns("app-headless-cms/admin/views/content-models/clone-content-model-dialog"); const narrowDialog = css({ ".mdc-dialog__surface": { width: 600, minWidth: 600 } }); const noPadding = css({ padding: "5px !important" }); export interface Props { open: boolean; onClose: UID.DialogOnClose; contentModel: CmsEditorContentModel; closeModal: () => void; } /** * This list is to disallow creating models that might interfere with GraphQL schema creation. * Add more if required. */ const disallowedModelIdEndingList: string[] = ["Response", "List", "Meta", "Input", "Sorter"]; const getSelectedGroup = ( groups: CmsGroupOption[] | null, model: CmsEditorContentModel ): string | null => { if (!groups || groups.length === 0 || !model) { return ""; } const current = model.group.id; const group = groups.find(g => g.value === current); if (group) { return group.value; } const defaultSelected = groups.find(() => true); return defaultSelected ? defaultSelected.value : null; }; const CloneContentModelDialog: React.FC<Props> = ({ open, onClose, contentModel, closeModal }) => { const [loading, setLoading] = useState<boolean>(false); const { showSnackbar } = useSnackbar(); const { history } = useRouter(); const { getLocales, getCurrentLocale, setCurrentLocale } = useI18N(); const currentLocale = getCurrentLocale("content"); const [locale, setLocale] = useState<string>(currentLocale || ""); const [groups, setGroups] = useState<CmsGroupOption[] | null>(null); const [createContentModelFrom] = useMutation< CreateCmsModelFromMutationResponse, CreateCmsModelFromMutationVariables >(CREATE_CONTENT_MODEL_FROM, { onError(error) { setLoading(false); showSnackbar(error.message); }, update(cache, response) { if (!response.data) { showSnackbar(`Missing data on Create Content Model From Mutation Response.`); return; } const { data: model, error } = response.data.createContentModelFrom; if (error) { setLoading(false); showSnackbar(error.message); return; } if (currentLocale !== locale) { setCurrentLocale(locale, "content"); window.location.reload(); return; } addModelToListCache(cache, model); addModelToGroupCache(cache, model); history.push("/cms/content-models/"); closeModal(); } }); const locales = getLocales().map(({ code }) => { return { value: code, label: code === currentLocale ? "Current locale" : code }; }); const { data, loading: groupsLoading } = useQueryLocale<ListMenuCmsGroupsQueryResponse>( LIST_MENU_CONTENT_GROUPS_MODELS, locale, { skip: !open || !!groups } ); useEffect(() => { if (!data || groupsLoading) { return; } const contentModelGroups: CmsGroupOption[] = get( data, "listContentModelGroups.data", [] ).map((item: CmsGroup): CmsGroupOption => { return { value: item.id, label: item.name }; }); setGroups(contentModelGroups); }, [data, groupsLoading]); const selectedGroup = getSelectedGroup(groups, contentModel); const nameValidator = useCallback((name: string) => { const target = (name || "").trim(); if (!target.charAt(0).match(/[a-zA-Z]/)) { throw new Error("Value is not valid - must not start with a number."); } if (target.toLowerCase() === "id") { throw new Error('Value is not valid - "id" is an auto-generated field.'); } for (const ending of disallowedModelIdEndingList) { const re = new RegExp(`${ending}$`, "i"); const matched = target.match(re); if (matched === null) { continue; } throw new Error(`Model name that ends with "${ending}" is not allowed.`); } return true; }, []); return ( <UID.Dialog open={open} onClose={onClose} className={narrowDialog} data-testid="cms-clone-content-model-modal" > {(!groups || groupsLoading) && ( <CircularProgress label={"Please wait while we load required information."} /> )} {open && ( <Form data={{ group: selectedGroup, locale, name: contentModel.name }} onSubmit={data => { setLoading(true); createContentModelFrom({ variables: { modelId: contentModel.modelId, /** * We know that data is CmsModel */ data: data as unknown as CmsModel } }); }} > {({ Bind, submit }) => ( <> {loading && <CircularProgress />} <UID.DialogTitle>{t`Clone Content Model`}</UID.DialogTitle> <UID.DialogContent> <Grid className={noPadding}> <Cell span={12}> <Bind name={"name"} validators={[ validation.create("required,maxLength:100"), nameValidator ]} > <Input label={t`Name`} description={t`The name of the content model`} /> </Bind> </Cell> <Cell span={12}> <Bind name={"locale"} validators={validation.create("required")} afterChange={(value?: string) => { if (!value) { return; } setLocale(value); setGroups(null); }} > <Select description={t`Choose a locale into which you wish to clone the model`} label={t`Content model locale`} options={locales} /> </Bind> </Cell> <Cell span={12}> <Bind name={"group"} validators={validation.create("required")} > <Select description={t`Choose a content model group`} label={t`Content model group`} options={groups || []} /> </Bind> </Cell> <Cell span={12}> <Bind name="description"> {props => ( <Input {...props} rows={4} maxLength={200} characterCount label={t`Description`} value={contentModel.description} /> )} </Bind> </Cell> </Grid> </UID.DialogContent> <UID.DialogActions> <ButtonDefault onClick={ev => { submit(ev); }} > + {t`Clone`} </ButtonDefault> </UID.DialogActions> </> )} </Form> )} </UID.Dialog> ); }; export default CloneContentModelDialog;
the_stack
import { Physics, Plugins, Scene, Events, Scenes } from "phaser"; import { getRootBody, warnInvalidObject } from "./utils"; import logger from "./logger"; import { CollidingObject as CO, isCollidingObject } from "./valid-collision-object"; import { ListenerMap, CollideABConfig as ABConfig, Unsubscribe, CollideCallback, CollideContext, ExtendedMatterCollisionData, EventData, CollideAConfig as AConfig, InternalCollideConfig, RemoveCollideConfigA as RemoveAConfig, RemoveCollideConfigAB as RemoveABConfig, InternalCollideRemoveConfig, } from "./collision-types"; import Matter = Physics.Matter; import MatterEvents = Matter.Events; const { START, DESTROY, SHUTDOWN } = Scenes.Events; const { COLLISION_START, COLLISION_ACTIVE, COLLISION_END } = Matter.Events; type MatterCollisionEvent = | MatterEvents.CollisionActiveEvent | MatterEvents.CollisionEndEvent | MatterEvents.CollisionActiveEvent; /** * @export */ export default class MatterCollisionPlugin extends Plugins.ScenePlugin { public events = new Events.EventEmitter(); private collisionStartListeners: ListenerMap = new Map(); private collisionEndListeners: ListenerMap = new Map(); private collisionActiveListeners: ListenerMap = new Map(); constructor( protected scene: Scene, protected pluginManager: Plugins.PluginManager, pluginKey: string ) { super(scene, pluginManager, pluginKey); this.scene = scene; this.scene.events.once(START, this.start, this); this.scene.events.once(DESTROY, this.destroy, this); } /** * Add a listener for collidestart events between objectA and objectB. The collidestart event is * fired by Matter when two bodies start colliding within a tick of the engine. If objectB is * omitted, any collisions with objectA will be passed along to the listener. See * {@link paircollisionstart} for information on callback parameters. */ public addOnCollideStart<T extends CO, K extends CO>(config: ABConfig<T, K>): Unsubscribe; public addOnCollideStart<T extends CO>(config: AConfig<T>): Unsubscribe; public addOnCollideStart(config: InternalCollideConfig): Unsubscribe { // Note: the order of overloads is important! TS matches the first one it can, so this needs // the most specific/constrained signature first. this.addOnCollide(this.collisionStartListeners, config); return () => this.removeOnCollide(this.collisionStartListeners, config); } /** This method mirrors {@link MatterCollisionPlugin#addOnCollideStart} */ public addOnCollideEnd<T extends CO, K extends CO>(config: ABConfig<T, K>): Unsubscribe; public addOnCollideEnd<T extends CO>(config: AConfig<T>): Unsubscribe; public addOnCollideEnd(config: InternalCollideConfig): Unsubscribe { this.addOnCollide(this.collisionEndListeners, config); return () => this.removeOnCollide(this.collisionEndListeners, config); } /** This method mirrors {@link MatterCollisionPlugin#addOnCollideStart} */ public addOnCollideActive<T extends CO, K extends CO>(config: ABConfig<T, K>): Unsubscribe; public addOnCollideActive<T extends CO>(config: AConfig<T>): Unsubscribe; public addOnCollideActive(config: InternalCollideConfig): Unsubscribe { this.addOnCollide(this.collisionActiveListeners, config); return () => this.removeOnCollide(this.collisionActiveListeners, config); } /** * Remove any listeners that were added with addOnCollideStart. If objectB, callback or context * parameters are omitted, any listener matching the remaining parameters will be removed. E.g. if * you only specify objectA and objectB, all listeners with objectA & objectB will be removed * regardless of the callback or context. */ public removeOnCollideStart<T extends CO, K extends CO>(config: RemoveABConfig<T, K>): void; public removeOnCollideStart<T extends CO>(config: RemoveAConfig<T>): void; public removeOnCollideStart(config: InternalCollideRemoveConfig) { this.removeOnCollide(this.collisionStartListeners, config); } /** This method mirrors {@link MatterCollisionPlugin#removeOnCollideStart} */ public removeOnCollideEnd<T extends CO, K extends CO>(config: RemoveABConfig<T, K>): void; public removeOnCollideEnd<T extends CO>(config: RemoveAConfig<T>): void; public removeOnCollideEnd(config: InternalCollideRemoveConfig) { this.removeOnCollide(this.collisionEndListeners, config); } /** This method mirrors {@link MatterCollisionPlugin#removeOnCollideStart} */ public removeOnCollideActive<T extends CO, K extends CO>(config: RemoveABConfig<T, K>): void; public removeOnCollideActive<T extends CO>(config: RemoveAConfig<T>): void; public removeOnCollideActive(config: InternalCollideRemoveConfig) { this.removeOnCollide(this.collisionActiveListeners, config); } /** Remove any listeners that were added with addOnCollideStart. */ public removeAllCollideStartListeners() { this.collisionStartListeners.clear(); } /** Remove any listeners that were added with addOnCollideActive. */ public removeAllCollideActiveListeners() { this.collisionActiveListeners.clear(); } /** Remove any listeners that were added with addOnCollideEnd. */ public removeAllCollideEndListeners() { this.collisionEndListeners.clear(); } /** * Remove any listeners that were added with addOnCollideStart, addOnCollideActive or * addOnCollideEnd. */ public removeAllCollideListeners() { this.removeAllCollideStartListeners(); this.removeAllCollideActiveListeners(); this.removeAllCollideEndListeners(); } private addOnCollide(map: ListenerMap, config: InternalCollideConfig): void { const { context, callback, objectA, objectB } = config; if (!callback || typeof callback !== "function") { logger.warn(`No valid callback specified. Received: ${callback}`); return; } const objectsA = Array.isArray(objectA) ? objectA : [objectA]; const objectsB = Array.isArray(objectB) ? objectB : [objectB]; objectsA.forEach((a) => { objectsB.forEach((b) => { this.addOnCollideObjectVsObject(map, a, b, callback, context); }); }); } private removeOnCollide(map: ListenerMap, config: InternalCollideRemoveConfig) { const { context, callback, objectA, objectB } = config; const objectsA = Array.isArray(objectA) ? objectA : [objectA]; const objectsB = Array.isArray(objectB) ? objectB : [objectB]; objectsA.forEach((a) => { const callbacks = map.get(a) || []; const remainingCallbacks = callbacks.filter((cb) => { // If anything doesn't match a provided config value (i.e. anything other than undefined), // we can bail and keep listener. if (context !== undefined && cb.context !== context) return true; if (callback !== undefined && cb.callback !== callback) return true; if (objectB !== undefined && !objectsB.includes(cb.target)) return true; return false; }); if (remainingCallbacks.length > 0) map.set(a, remainingCallbacks); else map.delete(a); }); } private addOnCollideObjectVsObject( map: ListenerMap, objectA: CO, objectB: CO | undefined, callback: CollideCallback<CO, CO>, context: CollideContext | undefined ) { // Can't do anything if the first object is not defined or invalid. if (!objectA || !isCollidingObject(objectA)) { warnInvalidObject(objectA); return; } // The second object can be undefined or a valid body. if (objectB && !isCollidingObject(objectB)) { warnInvalidObject(objectA); return; } const callbacks = map.get(objectA) || []; callbacks.push({ target: objectB, callback, context }); map.set(objectA, callbacks); } private onCollisionStart(event: MatterEvents.CollisionActiveEvent) { this.onCollisionEvent(this.collisionStartListeners, COLLISION_START, event); } private onCollisionEnd(event: MatterEvents.CollisionEndEvent) { this.onCollisionEvent(this.collisionEndListeners, COLLISION_END, event); } private onCollisionActive(event: MatterEvents.CollisionActiveEvent) { this.onCollisionEvent(this.collisionActiveListeners, COLLISION_ACTIVE, event); } /** * Reusable handler for collisionstart, collisionend, collisionactive. * */ private onCollisionEvent( listenerMap: ListenerMap, eventName: string, event: MatterCollisionEvent ) { const pairs = event.pairs as ExtendedMatterCollisionData[]; const pairEventName = "pair" + eventName; const eventData: Partial<EventData<CO, CO>> = { isReversed: false }; const eventDataReversed: Partial<EventData<CO, CO>> = { isReversed: true }; pairs.map((pair, i) => { const { bodyA, bodyB } = pair; const rootBodyA = getRootBody(bodyA); const rootBodyB = getRootBody(bodyB); let gameObjectA: CO | undefined = rootBodyA.gameObject ?? undefined; let gameObjectB: CO | undefined = rootBodyB.gameObject ?? undefined; // Special case for tiles, where it's more useful to have a reference to the Tile object not // the TileBody. This is hot code, so use a property check instead of instanceof. if (gameObjectA && gameObjectA instanceof Matter.TileBody) { gameObjectA = gameObjectA.tile; } if (gameObjectB && gameObjectB instanceof Matter.TileBody) { gameObjectB = gameObjectB.tile; } pairs[i].gameObjectA = gameObjectA ?? undefined; pairs[i].gameObjectB = gameObjectB ?? undefined; eventData.bodyA = bodyA; eventData.bodyB = bodyB; eventData.gameObjectA = gameObjectA ?? undefined; eventData.gameObjectB = gameObjectB ?? undefined; eventData.pair = pair; this.events.emit(pairEventName, eventData); if (listenerMap.size > 0) { eventDataReversed.bodyB = bodyA; eventDataReversed.bodyA = bodyB; eventDataReversed.gameObjectB = gameObjectA; eventDataReversed.gameObjectA = gameObjectB; eventDataReversed.pair = pair; const data = eventData as EventData<CO, CO>; const dataReversed = eventDataReversed as EventData<CO, CO>; this.checkPairAndEmit(listenerMap, bodyA, bodyB, gameObjectB, data); this.checkPairAndEmit(listenerMap, bodyB, bodyA, gameObjectA, dataReversed); if (gameObjectA) { this.checkPairAndEmit(listenerMap, gameObjectA, bodyB, gameObjectB, data); } if (gameObjectB) { this.checkPairAndEmit(listenerMap, gameObjectB, bodyA, gameObjectA, dataReversed); } } }); this.events.emit(eventName, event); } private checkPairAndEmit( map: ListenerMap, objectA: CO, bodyB: MatterJS.Body, gameObjectB: CO | undefined, eventData: EventData<CO, CO> ) { const callbacks = map.get(objectA); if (callbacks) { callbacks.forEach(({ target, callback, context }) => { if (!target || target === bodyB || target === gameObjectB) { callback.call(context, eventData); } }); } } subscribeMatterEvents() { const matter = this.scene.matter; if (!matter || !matter.world) { logger.warn("Plugin requires matter!"); return; } matter.world.on(COLLISION_START, this.onCollisionStart, this); matter.world.on(COLLISION_ACTIVE, this.onCollisionActive, this); matter.world.on(COLLISION_END, this.onCollisionEnd, this); } unsubscribeMatterEvents() { // Don't unsub if matter next existing or if the game is destroyed (since the matter world will // be already gone) const matter = this.scene.matter; if (!matter || !matter.world) return; matter.world.off(COLLISION_START, this.onCollisionStart, this); matter.world.off(COLLISION_ACTIVE, this.onCollisionActive, this); matter.world.off(COLLISION_END, this.onCollisionEnd, this); } start() { // If restarting, unsubscribe before resubscribing to ensure only one listener is added this.scene.events.off(SHUTDOWN, this.shutdown, this); this.scene.events.on(SHUTDOWN, this.shutdown, this); this.subscribeMatterEvents(); } shutdown() { this.removeAllCollideListeners(); this.unsubscribeMatterEvents(); // Resubscribe to start so that the plugin is started again after Matter this.scene.events.once(START, this.start, this); } destroy() { this.scene.events.off(DESTROY, this.destroy, this); this.scene.events.off(START, this.start, this); this.scene.events.off(SHUTDOWN, this.shutdown, this); this.removeAllCollideListeners(); this.unsubscribeMatterEvents(); } }
the_stack
import { INestApplication } from '@nestjs/common' import { Test } from '@nestjs/testing' import * as request from 'supertest' import { AppModule } from '../../../../app/app.module' import { DeploymentEntityV2 } from '../../../../app/v2/api/deployments/entity/deployment.entity' import { Execution } from '../../../../app/v2/api/deployments/entity/execution.entity' import { GitProvidersEnum } from '../../../../app/v2/core/configuration/interfaces' import { FixtureUtilsService } from '../fixture-utils.service' import { UrlConstants } from '../test-constants' import { TestSetupUtils } from '../test-setup-utils' import { EntityManager } from 'typeorm' import { ComponentEntityV2 } from '../../../../app/v2/api/deployments/entity/component.entity' import { LogEntity } from '../../../../app/v2/api/deployments/entity/logs.entity' describe('DeploymentController v2', () => { let fixtureUtilsService: FixtureUtilsService let app: INestApplication let manager: EntityManager beforeAll(async() => { const module = Test.createTestingModule({ imports: [ await AppModule.forRootAsync() ], providers: [ FixtureUtilsService ] }) TestSetupUtils.seApplicationConstants() app = await TestSetupUtils.createApplication(module) fixtureUtilsService = app.get<FixtureUtilsService>(FixtureUtilsService) manager = fixtureUtilsService.manager }) afterAll(async() => { await fixtureUtilsService.clearDatabase() await app.close() }) beforeEach(async() => { await fixtureUtilsService.clearDatabase() }) it('returns error message for empty payload', async() => { const createDeploymentRequest = {} const errorResponse = { errors: [ { title: '"deploymentId" is required', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'deploymentId' }, status: 400 }, { title: '"namespace" is required', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'namespace' }, status: 400 }, { title: '"circle" is required', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'circle' }, status: 400 }, { title: '"git" is required', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'git' }, status: 400 }, { title: '"components" is required', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'components' }, status: 400 }, { title: '"authorId" is required', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'authorId' }, status: 400 }, { title: '"callbackUrl" is required', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'callbackUrl' }, status: 400 } ] } await request(app.getHttpServer()) .post('/v2/deployments') .send(createDeploymentRequest) .set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b') .expect(400) .expect(response => { expect(response.body).toEqual(errorResponse) }) }) it('create execution for the deployment', async() => { const encryptedToken = `-----BEGIN PGP MESSAGE----- ww0ECQMCcRYScW+NJZZy0kUBbjTidEUAU0cTcHycJ5Phx74jvSTZ7ZE7hxK9AejbNDe5jDRGbqSd BSAwlmwpOpK27k2yXj4g1x2VaF9GGl//Ere+xUY= =QGZf -----END PGP MESSAGE----- ` const base64Token = Buffer.from(encryptedToken).toString('base64') const createDeploymentRequest = { deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2', namespace: 'default', git: { token: base64Token, provider: GitProvidersEnum.GITHUB }, circle: { id: '333365f8-bb29-49f7-bf2b-3ec956a71583', default: false }, components: [ { helmRepository: UrlConstants.helmRepository, componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl.com', buildImageTag: 'tag1', componentName: 'component-name' } ], authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af', callbackUrl: UrlConstants.deploymentCallbackUrl, } const response = await request(app.getHttpServer()) .post('/v2/deployments') .send(createDeploymentRequest) .set('x-circle-id', 'ab1c7726-a274-4fc3-9ec1-44e3563d58af') .expect(response => { expect(response.body).toEqual({ id: expect.anything() }) }) const executionsCount = await manager.findAndCount(Execution) expect(executionsCount[1]).toEqual(1) const execution = await manager.findOneOrFail(Execution, { relations: ['deployment'] }) expect(execution.deployment.id).toEqual(response.body.id) }) it('returns bad request when tag not respect the dns label format ', async() => { const encryptedToken = `-----BEGIN PGP MESSAGE----- ww0ECQMCcRYScW+NJZZy0kUBbjTidEUAU0cTcHycJ5Phx74jvSTZ7ZE7hxK9AejbNDe5jDRGbqSd BSAwlmwpOpK27k2yXj4g1x2VaF9GGl//Ere+xUY= =QGZf -----END PGP MESSAGE----- ` const base64Token = Buffer.from(encryptedToken).toString('base64') const createDeploymentRequest = { deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2', namespace: 'default', git: { token: base64Token, provider: GitProvidersEnum.GITHUB }, circle: { id: '333365f8-bb29-49f7-bf2b-3ec956a71583', default: false }, components: [ { helmRepository: UrlConstants.helmRepository, componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl.com', buildImageTag: 'UPPER-tag', componentName: 'component-name' } ], authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af', callbackUrl: UrlConstants.deploymentCallbackUrl, } const expectedError = { errors: [ { title: 'tag must consist of lower case alphanumeric characters, "-" or ".", and must start and end with an alphanumeric character', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'components/0' }, status: 400 } ] } const response = await request(app.getHttpServer()) .post('/v2/deployments') .send(createDeploymentRequest) .set('x-circle-id', 'ab1c7726-a274-4fc3-9ec1-44e3563d58af') expect(response.body).toEqual(expectedError) }) it('returns a bad request error when the git token decryption fail', async() => { const createDeploymentRequest = { deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2', namespace: 'default', git: { token: Buffer.from('malformed token').toString('base64'), provider: GitProvidersEnum.GITHUB }, circle: { id: '333365f8-bb29-49f7-bf2b-3ec956a71583', default: false }, components: [ { helmRepository: UrlConstants.helmRepository, componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl.com', buildImageTag: 'tag1', componentName: 'component-name' } ], authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af', callbackUrl: UrlConstants.deploymentCallbackUrl, } const expectedError = { errors: [ { title: 'Unable to decrypt "token"', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'git.token' }, status: 400 } ] } await request(app.getHttpServer()) .post('/v2/deployments') .send(createDeploymentRequest) .set('x-circle-id', 'ab1c7726-a274-4fc3-9ec1-44e3563d58af') .expect(400) .expect(response => { expect(response.body).toEqual(expectedError) }) }) it('returns error for malformed payload', async() => { const createDeploymentRequest = { deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2', circle: { headerValue: '333365f8-bb29-49f7-bf2b-3ec956a71583' }, components: [ { componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl.com', buildImageTag: 'tag1', componentName: 'component-name', helmRepository: UrlConstants.helmRepository }, { componentId: '888865f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl.com', buildImageTag: 'tag1', componentName: 'component-name', helmRepository: UrlConstants.helmRepository }, { componentId: '888865f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl.com2 ', buildImageTag: 'tag1', componentName: 'component-name', helmRepository: UrlConstants.helmRepository }, { componentId: '888865f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl-ends-with-dash.com3-', buildImageTag: 'tag1', componentName: 'component-name', helmRepository: UrlConstants.helmRepository }, { componentId: '888865f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: `very-long-url${'4'.repeat(237)}.com`, // max is 253 because of kubernetes buildImageTag: 'tag1', componentName: 'component-name', helmRepository: UrlConstants.helmRepository }, { componentId: '888865f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'quiz-app-backend', buildImageTag: 'tag1', componentName: 'component-name', helmRepository: UrlConstants.helmRepository } ], authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af', callbackUrl: UrlConstants.deploymentCallbackUrl } const errorResponse = { errors: [ { title: '"namespace" is required', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'namespace' }, status: 400 }, { title: '"circle.id" is required', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'circle/id' }, status: 400 }, { title: '"circle.default" is required', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'circle/default' }, status: 400 }, { title: '"circle.headerValue" is not allowed', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'circle/headerValue' }, status: 400 }, { title: '"git" is required', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'git' }, status: 400 }, { title: expect.stringContaining('"buildImageUrl" with value "imageurl.com2 " fails to match the required pattern'), meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'components/2/buildImageUrl' }, status: 400 }, { title: expect.stringContaining('"buildImageUrl" with value "imageurl-ends-with-dash.com3-" fails to match the required pattern'), meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'components/3/buildImageUrl' }, status: 400 }, { title: '"buildImageUrl" length must be less than or equal to 253 characters long', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'components/4/buildImageUrl' }, status: 400 }, { title: '"components" contains a duplicate value', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'components/1' }, status: 400 } ] } await request(app.getHttpServer()) .post('/v2/deployments') .send(createDeploymentRequest) .set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b') .expect(400) .expect(response => { expect(response.body).toEqual(errorResponse) }) }) it('returns error for empty components', async() => { const createDeploymentRequest = { deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2', namespace: 'default', circle: { id: '333365f8-bb29-49f7-bf2b-3ec956a71583', default: false }, git: { token: Buffer.from('123123').toString('base64'), provider: 'GITHUB' }, components: [], authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af', callbackUrl: UrlConstants.deploymentCallbackUrl } const errorResponse = { errors: [ { title: '"components" must contain at least 1 items', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'components' }, status: 400 } ] } await request(app.getHttpServer()) .post('/v2/deployments') .send(createDeploymentRequest) .set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b') .expect(400) .expect(response => { expect(response.body).toEqual(errorResponse) }) }) it('saves optional parameters correctly', async() => { const encryptedToken = ` -----BEGIN PGP MESSAGE----- ww0ECQMCcRYScW+NJZZy0kUBbjTidEUAU0cTcHycJ5Phx74jvSTZ7ZE7hxK9AejbNDe5jDRGbqSd BSAwlmwpOpK27k2yXj4g1x2VaF9GGl//Ere+xUY= =QGZf -----END PGP MESSAGE----- ` const createDeploymentRequest = { deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2', namespace: 'default', circle: { id: '333365f8-bb29-49f7-bf2b-3ec956a71583', default: false }, git: { token: Buffer.from(encryptedToken).toString('base64'), provider: 'GITHUB' }, components: [ { componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl.com', buildImageTag: 'tag1', componentName: 'component-name', hostValue: 'host-value-1', gatewayName: 'gateway-name-1', helmRepository: UrlConstants.helmRepository, } ], authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af', callbackUrl: UrlConstants.deploymentCallbackUrl, timeoutInSeconds: 10 } const response = await request(app.getHttpServer()) .post('/v2/deployments') .send(createDeploymentRequest) .set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b') .expect(201) const deployment = await manager.findOneOrFail(DeploymentEntityV2, response.body.id, { relations: ['components'] }) expect(deployment.components.map(c => c.hostValue)).toEqual(['host-value-1']) expect(deployment.components.map(c => c.gatewayName)).toEqual(['gateway-name-1']) expect(deployment.timeoutInSeconds).toEqual(10) }) it('validates size of componentName + buildImageTag concatenation', async() => { const createDeploymentRequest = { deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2', namespace: 'default', circle: { id: '333365f8-bb29-49f7-bf2b-3ec956a71583', default: false }, git: { token: Buffer.from('123123').toString('base64'), provider: 'GITHUB' }, components: [ { helmRepository: UrlConstants.helmRepository, componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl.com', buildImageTag: '11111111111111111111111111111111', componentName: '22222222222222222222222222222222', hostValue: 'host-value-1', gatewayName: 'gateway-name-1' } ], authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af', callbackUrl: UrlConstants.deploymentCallbackUrl, } const errorResponse = { errors: [ { title: 'Sum of lengths of componentName and buildImageTag cant be greater than 63', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'components/0' }, status: 400 } ] } await request(app.getHttpServer()) .post('/v2/deployments') .send(createDeploymentRequest) .set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b') .expect(400) .expect(response => { expect(response.body).toEqual(errorResponse) }) }) it('validates imageTag is equal to suplied tag on imageUrl', async() => { const createDeploymentRequest = { deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2', namespace: 'default', circle: { id: '333365f8-bb29-49f7-bf2b-3ec956a71583', default: false }, git: { token: Buffer.from('123123').toString('base64'), provider: 'GITHUB' }, components: [ { helmRepository: UrlConstants.helmRepository, componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl.com:some-tag', buildImageTag: 'different-tag', componentName: 'my-component', hostValue: 'host-value-1', gatewayName: 'gateway-name-1' }, { helmRepository: UrlConstants.helmRepository, componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl2.com:another-tag', buildImageTag: 'another-tag', componentName: 'my-other-component' } ], authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af', callbackUrl: UrlConstants.deploymentCallbackUrl } const errorResponse = { errors: [ { title: 'The tag suplied on the buildImageUrl must match the buildImageTag', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'components/0' }, status: 400 } ] } await request(app.getHttpServer()) .post('/v2/deployments') .send(createDeploymentRequest) .set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b') .expect(400) .expect(response => { expect(response.body).toEqual(errorResponse) }) }) it('returns an error when there is one active default deployment on the same namespace with a different circle id', async() => { const createDeploymentRequest = { deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2', namespace: 'default', circle: { id: '333365f8-bb29-49f7-bf2b-3ec956a71583', default: true }, git: { token: Buffer.from('123123').toString('base64'), provider: 'GITHUB' }, components: [ { helmRepository: UrlConstants.helmRepository, componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl.com:some-tag', buildImageTag: 'some-tag', componentName: 'my-component', hostValue: 'host-value-1', gatewayName: 'gateway-name-1' }, { helmRepository: UrlConstants.helmRepository, componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl2.com:another-tag', buildImageTag: 'another-tag', componentName: 'my-other-component' } ], authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af', callbackUrl: UrlConstants.deploymentCallbackUrl } const sameNamespaceActiveDeployment = new DeploymentEntityV2( '6d1e1881-72d3-4fb5-84da-8bd61bb8e2d3', '580a7726-a274-4fc3-9ec1-44e3563d58af', 'ad03d665-f689-42aa-b1de-d19653e89b86', UrlConstants.deploymentCallbackUrl, [ new ComponentEntityV2( UrlConstants.helmRepository, 'currenttag', 'imageurl.com:currenttag', 'my-component', '777765f8-bb29-49f7-bf2b-3ec956a71583', 'host-value-1', 'gateway-name-1', [] ) ], true, 'default', 120, ) sameNamespaceActiveDeployment.current = true await manager.save(sameNamespaceActiveDeployment) const errorResponse = { errors: [ { title: 'Invalid circle id.', detail: 'Namespace already has an active default deployment.', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'circle/id' }, status: 409 } ] } await request(app.getHttpServer()) .post('/v2/deployments') .send(createDeploymentRequest) .set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b') .expect(409) .expect(response => { expect(response.body).toEqual(errorResponse) }) }) it('allows a default circle deployment when there is one active default deployment on a different namespace', async() => { const encryptedToken = ` -----BEGIN PGP MESSAGE----- ww0ECQMCcRYScW+NJZZy0kUBbjTidEUAU0cTcHycJ5Phx74jvSTZ7ZE7hxK9AejbNDe5jDRGbqSd BSAwlmwpOpK27k2yXj4g1x2VaF9GGl//Ere+xUY= =QGZf -----END PGP MESSAGE----- ` const createDeploymentRequest = { deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2', namespace: 'default', circle: { id: '333365f8-bb29-49f7-bf2b-3ec956a71583', default: true }, git: { token: Buffer.from(encryptedToken).toString('base64'), provider: 'GITHUB' }, components: [ { helmRepository: UrlConstants.helmRepository, componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl.com:some-tag', buildImageTag: 'some-tag', componentName: 'my-component', hostValue: 'host-value-1', gatewayName: 'gateway-name-1' }, { helmRepository: UrlConstants.helmRepository, componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl2.com:another-tag', buildImageTag: 'another-tag', componentName: 'my-other-component' } ], authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af', callbackUrl: UrlConstants.deploymentCallbackUrl } const differentNamespaceActiveDeployment = new DeploymentEntityV2( '6d1e1881-72d3-4fb5-84da-8bd61bb8e2d3', '580a7726-a274-4fc3-9ec1-44e3563d58af', 'ad03d665-f689-42aa-b1de-d19653e89b86', UrlConstants.deploymentCallbackUrl, [ new ComponentEntityV2( UrlConstants.helmRepository, 'current-tag', 'imageurl.com:current-tag', 'my-component', '777765f8-bb29-49f7-bf2b-3ec956a71583', 'host-value-1', 'gateway-name-1', [] ) ], true, 'test2', 120, ) differentNamespaceActiveDeployment.current = true await manager.save(differentNamespaceActiveDeployment) await request(app.getHttpServer()) .post('/v2/deployments') .send(createDeploymentRequest) .set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b') .expect(201) }) it('allows a circle deployment when there is one active circle deployment on the same namespace', async() => { const encryptedToken = ` -----BEGIN PGP MESSAGE----- ww0ECQMCcRYScW+NJZZy0kUBbjTidEUAU0cTcHycJ5Phx74jvSTZ7ZE7hxK9AejbNDe5jDRGbqSd BSAwlmwpOpK27k2yXj4g1x2VaF9GGl//Ere+xUY= =QGZf -----END PGP MESSAGE----- ` const createDeploymentRequest = { deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2', namespace: 'default', circle: { id: '333365f8-bb29-49f7-bf2b-3ec956a71583', default: false }, git: { token: Buffer.from(encryptedToken).toString('base64'), provider: 'GITHUB' }, components: [ { helmRepository: UrlConstants.helmRepository, componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl.com:some-tag', buildImageTag: 'some-tag', componentName: 'my-component', hostValue: 'host-value-1', gatewayName: 'gateway-name-1' }, { helmRepository: UrlConstants.helmRepository, componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl2.com:another-tag', buildImageTag: 'another-tag', componentName: 'my-other-component' } ], authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af', callbackUrl: UrlConstants.deploymentCallbackUrl } const differentNamespaceActiveDeployment = new DeploymentEntityV2( '6d1e1881-72d3-4fb5-84da-8bd61bb8e2d3', '580a7726-a274-4fc3-9ec1-44e3563d58af', 'ad03d665-f689-42aa-b1de-d19653e89b86', UrlConstants.deploymentCallbackUrl, [ new ComponentEntityV2( UrlConstants.helmRepository, 'currenttag', 'imageurl.com:currenttag', 'my-component', '777765f8-bb29-49f7-bf2b-3ec956a71583', 'host-value-1', 'gateway-name-1', [] ) ], false, 'default', 120, ) differentNamespaceActiveDeployment.current = true await manager.save(differentNamespaceActiveDeployment) await request(app.getHttpServer()) .post('/v2/deployments') .send(createDeploymentRequest) .set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b') .expect(201) }) it('returns correct error when git token is not valid', async() => { const encryptedToken = 'invalid-token' const createDeploymentRequest = { deploymentId: '28a3f957-3702-4c4e-8d92-015939f39cf2', namespace: 'default', circle: { id: '333365f8-bb29-49f7-bf2b-3ec956a71583', default: false }, git: { token: Buffer.from(encryptedToken).toString('base64'), provider: 'GITHUB' }, components: [ { helmRepository: UrlConstants.helmRepository, componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl.com:some-tag', buildImageTag: 'some-tag', componentName: 'my-component', hostValue: 'host-value-1', gatewayName: 'gateway-name-1' }, { helmRepository: UrlConstants.helmRepository, componentId: '777765f8-bb29-49f7-bf2b-3ec956a71583', buildImageUrl: 'imageurl2.com:another-tag', buildImageTag: 'another-tag', componentName: 'my-other-component' } ], authorId: '580a7726-a274-4fc3-9ec1-44e3563d58af', callbackUrl: UrlConstants.deploymentCallbackUrl } const errorResponse = { errors: [ { title: 'Unable to decrypt "token"', meta: { component: 'butler', timestamp: expect.anything() }, source: { pointer: 'git.token' }, status: 400 } ] } await request(app.getHttpServer()) .post('/v2/deployments') .send(createDeploymentRequest) .set('x-circle-id', 'a45fd548-0082-4021-ba80-a50703c44a3b') .expect(400) .expect(response => { expect(response.body).toEqual(errorResponse) }) }) it('returns logs from deployment id', async() => { const deploymentId = '6d1e1881-72d3-4fb5-84da-8bd61bb8e2d3' const deployment = new DeploymentEntityV2( deploymentId, '580a7726-a274-4fc3-9ec1-44e3563d58af', 'ad03d665-f689-42aa-b1de-d19653e89b86', UrlConstants.deploymentCallbackUrl, [ new ComponentEntityV2( UrlConstants.helmRepository, 'currenttag', 'imageurl.com:currenttag', 'my-component', '777765f8-bb29-49f7-bf2b-3ec956a71583', 'host-value-1', 'gateway-name-1', [] ) ], true, 'default', 120, ) await manager.save(deployment) const log = new LogEntity ( deploymentId, [ { type: 'INFO', title: 'Created', details: '{"message":"Container image "paulczar/gb-frontend:v5" already present on machine","object":"Pod/frontend-7cb5fb8b96-prqxv"}', timestamp: '2021-04-29T10:17:24-03:00' } ] ) await manager.save(log) await request(app.getHttpServer()) .get(`/v2/deployments/${deploymentId}/logs`) .expect(200) .expect(response => { expect(response.body).toEqual({ logs: [ { type: 'INFO', title: 'Created', details: '{"message":"Container image "paulczar/gb-frontend:v5" already present on machine","object":"Pod/frontend-7cb5fb8b96-prqxv"}', timestamp: '2021-04-29T10:17:24-03:00' } ] }) }) }) })
the_stack
import ts = require('typescript'); // A blacklist of node kinds that do NOT need to be searched for namespace usages. // // A blacklist is safer than trying to whitelist all the relevant items from SyntaxKind. // // ref: typescript.d.ts export const namespaceBlacklist: ReadonlyArray<ts.SyntaxKind> = [ ts.SyntaxKind.Unknown, ts.SyntaxKind.EndOfFileToken, ts.SyntaxKind.SingleLineCommentTrivia, ts.SyntaxKind.MultiLineCommentTrivia, ts.SyntaxKind.NewLineTrivia, ts.SyntaxKind.WhitespaceTrivia, ts.SyntaxKind.ShebangTrivia, ts.SyntaxKind.ConflictMarkerTrivia, ts.SyntaxKind.NumericLiteral, ts.SyntaxKind.BigIntLiteral, ts.SyntaxKind.StringLiteral, ts.SyntaxKind.JsxText, ts.SyntaxKind.JsxTextAllWhiteSpaces, ts.SyntaxKind.RegularExpressionLiteral, ts.SyntaxKind.NoSubstitutionTemplateLiteral, ts.SyntaxKind.TemplateHead, ts.SyntaxKind.TemplateMiddle, ts.SyntaxKind.TemplateTail, ts.SyntaxKind.OpenBraceToken, ts.SyntaxKind.CloseBraceToken, ts.SyntaxKind.OpenParenToken, ts.SyntaxKind.CloseParenToken, ts.SyntaxKind.OpenBracketToken, ts.SyntaxKind.CloseBracketToken, ts.SyntaxKind.DotToken, ts.SyntaxKind.DotDotDotToken, ts.SyntaxKind.SemicolonToken, ts.SyntaxKind.CommaToken, ts.SyntaxKind.QuestionDotToken, ts.SyntaxKind.LessThanToken, ts.SyntaxKind.LessThanSlashToken, ts.SyntaxKind.GreaterThanToken, ts.SyntaxKind.LessThanEqualsToken, ts.SyntaxKind.GreaterThanEqualsToken, ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsToken, ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken, ts.SyntaxKind.EqualsGreaterThanToken, ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken, ts.SyntaxKind.AsteriskToken, ts.SyntaxKind.AsteriskAsteriskToken, ts.SyntaxKind.SlashToken, ts.SyntaxKind.PercentToken, ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken, ts.SyntaxKind.LessThanLessThanToken, ts.SyntaxKind.GreaterThanGreaterThanToken, ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken, ts.SyntaxKind.AmpersandToken, ts.SyntaxKind.BarToken, ts.SyntaxKind.CaretToken, ts.SyntaxKind.ExclamationToken, ts.SyntaxKind.TildeToken, ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken, ts.SyntaxKind.QuestionToken, ts.SyntaxKind.ColonToken, ts.SyntaxKind.AtToken, ts.SyntaxKind.QuestionQuestionToken, /** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */ ts.SyntaxKind.BacktickToken, ts.SyntaxKind.EqualsToken, ts.SyntaxKind.PlusEqualsToken, ts.SyntaxKind.MinusEqualsToken, ts.SyntaxKind.AsteriskEqualsToken, ts.SyntaxKind.AsteriskAsteriskEqualsToken, ts.SyntaxKind.SlashEqualsToken, ts.SyntaxKind.PercentEqualsToken, ts.SyntaxKind.LessThanLessThanEqualsToken, ts.SyntaxKind.GreaterThanGreaterThanEqualsToken, ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken, ts.SyntaxKind.AmpersandEqualsToken, ts.SyntaxKind.BarEqualsToken, ts.SyntaxKind.CaretEqualsToken, ts.SyntaxKind.Identifier, ts.SyntaxKind.BreakKeyword, // ts.SyntaxKind.CaseKeyword, // ts.SyntaxKind.CatchKeyword, // ts.SyntaxKind.ClassKeyword, // ts.SyntaxKind.ConstKeyword, ts.SyntaxKind.ContinueKeyword, ts.SyntaxKind.DebuggerKeyword, ts.SyntaxKind.DefaultKeyword, ts.SyntaxKind.DeleteKeyword, ts.SyntaxKind.DoKeyword, ts.SyntaxKind.ElseKeyword, ts.SyntaxKind.EnumKeyword, ts.SyntaxKind.ExportKeyword, ts.SyntaxKind.ExtendsKeyword, ts.SyntaxKind.FalseKeyword, ts.SyntaxKind.FinallyKeyword, ts.SyntaxKind.ForKeyword, ts.SyntaxKind.FunctionKeyword, ts.SyntaxKind.IfKeyword, ts.SyntaxKind.ImportKeyword, ts.SyntaxKind.InKeyword, ts.SyntaxKind.InstanceOfKeyword, ts.SyntaxKind.NewKeyword, ts.SyntaxKind.NullKeyword, ts.SyntaxKind.ReturnKeyword, ts.SyntaxKind.SuperKeyword, ts.SyntaxKind.SwitchKeyword, ts.SyntaxKind.ThisKeyword, ts.SyntaxKind.ThrowKeyword, ts.SyntaxKind.TrueKeyword, ts.SyntaxKind.TryKeyword, ts.SyntaxKind.TypeOfKeyword, ts.SyntaxKind.VarKeyword, ts.SyntaxKind.VoidKeyword, ts.SyntaxKind.WhileKeyword, ts.SyntaxKind.WithKeyword, ts.SyntaxKind.ImplementsKeyword, ts.SyntaxKind.InterfaceKeyword, ts.SyntaxKind.LetKeyword, ts.SyntaxKind.PackageKeyword, ts.SyntaxKind.PrivateKeyword, ts.SyntaxKind.ProtectedKeyword, ts.SyntaxKind.PublicKeyword, ts.SyntaxKind.StaticKeyword, ts.SyntaxKind.YieldKeyword, ts.SyntaxKind.AbstractKeyword, ts.SyntaxKind.AsKeyword, ts.SyntaxKind.AssertsKeyword, ts.SyntaxKind.AnyKeyword, ts.SyntaxKind.AsyncKeyword, ts.SyntaxKind.AwaitKeyword, ts.SyntaxKind.BooleanKeyword, ts.SyntaxKind.ConstructorKeyword, ts.SyntaxKind.DeclareKeyword, ts.SyntaxKind.GetKeyword, ts.SyntaxKind.InferKeyword, ts.SyntaxKind.IsKeyword, ts.SyntaxKind.KeyOfKeyword, ts.SyntaxKind.ModuleKeyword, ts.SyntaxKind.NamespaceKeyword, ts.SyntaxKind.NeverKeyword, ts.SyntaxKind.ReadonlyKeyword, ts.SyntaxKind.RequireKeyword, ts.SyntaxKind.NumberKeyword, ts.SyntaxKind.ObjectKeyword, ts.SyntaxKind.SetKeyword, ts.SyntaxKind.StringKeyword, ts.SyntaxKind.SymbolKeyword, ts.SyntaxKind.TypeKeyword, ts.SyntaxKind.UndefinedKeyword, ts.SyntaxKind.UniqueKeyword, ts.SyntaxKind.UnknownKeyword, ts.SyntaxKind.FromKeyword, ts.SyntaxKind.GlobalKeyword, ts.SyntaxKind.BigIntKeyword, ts.SyntaxKind.OfKeyword, // ts.SyntaxKind.QualifiedName, // same value as FirstNode (there are other such duplicates) - this seems to be intentional - see https://github.com/microsoft/TypeScript/blob/master/src/compiler/types.ts ts.SyntaxKind.ComputedPropertyName, ts.SyntaxKind.TypeParameter, ts.SyntaxKind.Parameter, ts.SyntaxKind.Decorator, ts.SyntaxKind.PropertySignature, ts.SyntaxKind.PropertyDeclaration, ts.SyntaxKind.MethodSignature, ts.SyntaxKind.MethodDeclaration, ts.SyntaxKind.Constructor, ts.SyntaxKind.GetAccessor, ts.SyntaxKind.SetAccessor, ts.SyntaxKind.CallSignature, ts.SyntaxKind.ConstructSignature, ts.SyntaxKind.IndexSignature, ts.SyntaxKind.TypePredicate, // ts.SyntaxKind.TypeReference, ts.SyntaxKind.FunctionType, ts.SyntaxKind.ConstructorType, ts.SyntaxKind.TypeQuery, ts.SyntaxKind.TypeLiteral, ts.SyntaxKind.ArrayType, ts.SyntaxKind.TupleType, ts.SyntaxKind.OptionalType, ts.SyntaxKind.RestType, ts.SyntaxKind.UnionType, ts.SyntaxKind.IntersectionType, ts.SyntaxKind.ConditionalType, ts.SyntaxKind.InferType, ts.SyntaxKind.ParenthesizedType, ts.SyntaxKind.ThisType, ts.SyntaxKind.TypeOperator, ts.SyntaxKind.IndexedAccessType, ts.SyntaxKind.MappedType, ts.SyntaxKind.LiteralType, ts.SyntaxKind.ImportType, ts.SyntaxKind.ObjectBindingPattern, ts.SyntaxKind.ArrayBindingPattern, ts.SyntaxKind.BindingElement, // ts.SyntaxKind.ArrayLiteralExpression, // ts.SyntaxKind.ObjectLiteralExpression, // ts.SyntaxKind.PropertyAccessExpression, // ts.SyntaxKind.ElementAccessExpression, // ts.SyntaxKind.CallExpression, // ts.SyntaxKind.NewExpression, // ts.SyntaxKind.TaggedTemplateExpression, // ts.SyntaxKind.TypeAssertionExpression, // ts.SyntaxKind.ParenthesizedExpression, // ts.SyntaxKind.FunctionExpression, // ts.SyntaxKind.ArrowFunction, // ts.SyntaxKind.DeleteExpression, // ts.SyntaxKind.TypeOfExpression, // ts.SyntaxKind.VoidExpression, // ts.SyntaxKind.AwaitExpression, // ts.SyntaxKind.PrefixUnaryExpression, // ts.SyntaxKind.PostfixUnaryExpression, // ts.SyntaxKind.BinaryExpression, // ts.SyntaxKind.ConditionalExpression, // ts.SyntaxKind.TemplateExpression, // ts.SyntaxKind.YieldExpression, // ts.SyntaxKind.SpreadElement, // ts.SyntaxKind.ClassExpression, // ts.SyntaxKind.OmittedExpression, // ts.SyntaxKind.ExpressionWithTypeArguments, // ts.SyntaxKind.AsExpression, // ts.SyntaxKind.NonNullExpression, ts.SyntaxKind.MetaProperty, // ts.SyntaxKind.SyntheticExpression, ts.SyntaxKind.TemplateSpan, ts.SyntaxKind.SemicolonClassElement, // ts.SyntaxKind.Block, ts.SyntaxKind.EmptyStatement, // ts.SyntaxKind.VariableStatement, // ts.SyntaxKind.ExpressionStatement, // ts.SyntaxKind.IfStatement, // ts.SyntaxKind.DoStatement, // ts.SyntaxKind.WhileStatement, // ts.SyntaxKind.ForStatement, // ts.SyntaxKind.ForInStatement, // ts.SyntaxKind.ForOfStatement, // ts.SyntaxKind.ContinueStatement, // ts.SyntaxKind.BreakStatement, // ts.SyntaxKind.ReturnStatement, // ts.SyntaxKind.WithStatement, // ts.SyntaxKind.SwitchStatement, // ts.SyntaxKind.LabeledStatement, // ts.SyntaxKind.ThrowStatement, // ts.SyntaxKind.TryStatement, // ts.SyntaxKind.DebuggerStatement, // ts.SyntaxKind.VariableDeclaration, // ts.SyntaxKind.VariableDeclarationList, // ts.SyntaxKind.FunctionDeclaration, // ts.SyntaxKind.ClassDeclaration, // ts.SyntaxKind.InterfaceDeclaration, // ts.SyntaxKind.TypeAliasDeclaration, // ts.SyntaxKind.EnumDeclaration, // ts.SyntaxKind.ModuleDeclaration, // ts.SyntaxKind.ModuleBlock, // ts.SyntaxKind.CaseBlock, ts.SyntaxKind.NamespaceExportDeclaration, ts.SyntaxKind.ImportEqualsDeclaration, ts.SyntaxKind.ImportDeclaration, ts.SyntaxKind.ImportClause, ts.SyntaxKind.NamespaceImport, ts.SyntaxKind.NamedImports, ts.SyntaxKind.ImportSpecifier, ts.SyntaxKind.ExportAssignment, ts.SyntaxKind.ExportDeclaration, ts.SyntaxKind.NamedExports, ts.SyntaxKind.ExportSpecifier, ts.SyntaxKind.MissingDeclaration, ts.SyntaxKind.ExternalModuleReference, ts.SyntaxKind.JsxElement, ts.SyntaxKind.JsxSelfClosingElement, ts.SyntaxKind.JsxOpeningElement, ts.SyntaxKind.JsxClosingElement, ts.SyntaxKind.JsxFragment, ts.SyntaxKind.JsxOpeningFragment, ts.SyntaxKind.JsxClosingFragment, ts.SyntaxKind.JsxAttribute, ts.SyntaxKind.JsxAttributes, ts.SyntaxKind.JsxSpreadAttribute, // ts.SyntaxKind.JsxExpression, // ts.SyntaxKind.CaseClause, // ts.SyntaxKind.DefaultClause, // ts.SyntaxKind.HeritageClause, // ts.SyntaxKind.CatchClause, ts.SyntaxKind.PropertyAssignment, ts.SyntaxKind.ShorthandPropertyAssignment, ts.SyntaxKind.SpreadAssignment, ts.SyntaxKind.EnumMember, ts.SyntaxKind.UnparsedPrologue, ts.SyntaxKind.UnparsedPrepend, ts.SyntaxKind.UnparsedText, ts.SyntaxKind.UnparsedInternalText, ts.SyntaxKind.UnparsedSyntheticReference, ts.SyntaxKind.SourceFile, ts.SyntaxKind.Bundle, ts.SyntaxKind.UnparsedSource, ts.SyntaxKind.InputFiles, ts.SyntaxKind.JSDocTypeExpression, ts.SyntaxKind.JSDocAllType, ts.SyntaxKind.JSDocUnknownType, ts.SyntaxKind.JSDocNullableType, ts.SyntaxKind.JSDocNonNullableType, ts.SyntaxKind.JSDocOptionalType, ts.SyntaxKind.JSDocFunctionType, ts.SyntaxKind.JSDocVariadicType, ts.SyntaxKind.JSDocNamepathType, ts.SyntaxKind.JSDocComment, ts.SyntaxKind.JSDocTypeLiteral, ts.SyntaxKind.JSDocSignature, ts.SyntaxKind.JSDocTag, ts.SyntaxKind.JSDocAugmentsTag, ts.SyntaxKind.JSDocAuthorTag, ts.SyntaxKind.JSDocClassTag, ts.SyntaxKind.JSDocCallbackTag, ts.SyntaxKind.JSDocEnumTag, ts.SyntaxKind.JSDocParameterTag, ts.SyntaxKind.JSDocReturnTag, ts.SyntaxKind.JSDocThisTag, ts.SyntaxKind.JSDocTypeTag, ts.SyntaxKind.JSDocTemplateTag, ts.SyntaxKind.JSDocTypedefTag, ts.SyntaxKind.JSDocPropertyTag, // ts.SyntaxKind.SyntaxList, ts.SyntaxKind.NotEmittedStatement, // ts.SyntaxKind.PartiallyEmittedExpression, // ts.SyntaxKind.CommaListExpression, ts.SyntaxKind.MergeDeclarationMarker, ts.SyntaxKind.EndOfDeclarationMarker, // ts.SyntaxKind.SyntheticReferenceExpression, // ts.SyntaxKind.Count, ts.SyntaxKind.FirstAssignment, ts.SyntaxKind.LastAssignment, ts.SyntaxKind.FirstCompoundAssignment, ts.SyntaxKind.LastCompoundAssignment, ts.SyntaxKind.FirstReservedWord, ts.SyntaxKind.LastReservedWord, ts.SyntaxKind.FirstKeyword, ts.SyntaxKind.LastKeyword, ts.SyntaxKind.FirstFutureReservedWord, ts.SyntaxKind.LastFutureReservedWord, // ts.SyntaxKind.FirstTypeNode, // ts.SyntaxKind.LastTypeNode, ts.SyntaxKind.FirstPunctuation, ts.SyntaxKind.LastPunctuation, ts.SyntaxKind.FirstToken, ts.SyntaxKind.LastToken, ts.SyntaxKind.FirstTriviaToken, ts.SyntaxKind.LastTriviaToken, ts.SyntaxKind.FirstLiteralToken, ts.SyntaxKind.LastLiteralToken, ts.SyntaxKind.FirstTemplateToken, ts.SyntaxKind.LastTemplateToken, ts.SyntaxKind.FirstBinaryOperator, ts.SyntaxKind.LastBinaryOperator, // ts.SyntaxKind.FirstStatement, // ts.SyntaxKind.LastStatement, // ts.SyntaxKind.FirstNode, ts.SyntaxKind.FirstJSDocNode, ts.SyntaxKind.LastJSDocNode, ts.SyntaxKind.FirstJSDocTagNode, ts.SyntaxKind.LastJSDocTagNode, ];
the_stack
import * as $protobuf from "protobufjs"; /** Namespace master. */ export namespace master { /** Properties of a Player. */ interface IPlayer { /** Player name */ name?: (string|null); /** Player identifiers */ identifiers?: (string[]|null); /** Player endpoint */ endpoint?: (string|null); /** Player ping */ ping?: (number|null); /** Player id */ id?: (number|null); } /** Represents a Player. */ class Player implements IPlayer { /** * Constructs a new Player. * @param [properties] Properties to set */ constructor(properties?: master.IPlayer); /** Player name. */ public name: string; /** Player identifiers. */ public identifiers: string[]; /** Player endpoint. */ public endpoint: string; /** Player ping. */ public ping: number; /** Player id. */ public id: number; /** * Creates a new Player instance using the specified properties. * @param [properties] Properties to set * @returns Player instance */ public static create(properties?: master.IPlayer): master.Player; /** * Encodes the specified Player message. Does not implicitly {@link master.Player.verify|verify} messages. * @param message Player message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: master.IPlayer, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Player message, length delimited. Does not implicitly {@link master.Player.verify|verify} messages. * @param message Player message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: master.IPlayer, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Player message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Player * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): master.Player; /** * Decodes a Player message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Player * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): master.Player; /** * Verifies a Player message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Player message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Player */ public static fromObject(object: { [k: string]: any }): master.Player; /** * Creates a plain object from a Player message. Also converts values to other types if specified. * @param message Player * @param [options] Conversion options * @returns Plain object */ public static toObject(message: master.Player, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Player to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ServerData. */ interface IServerData { /** ServerData svMaxclients */ svMaxclients?: (number|null); /** ServerData clients */ clients?: (number|null); /** ServerData protocol */ protocol?: (number|null); /** ServerData hostname */ hostname?: (string|null); /** ServerData gametype */ gametype?: (string|null); /** ServerData mapname */ mapname?: (string|null); /** ServerData resources */ resources?: (string[]|null); /** ServerData server */ server?: (string|null); /** ServerData players */ players?: (master.IPlayer[]|null); /** ServerData iconVersion */ iconVersion?: (number|null); /** ServerData vars */ vars?: ({ [k: string]: string }|null); /** ServerData enhancedHostSupport */ enhancedHostSupport?: (boolean|null); /** ServerData upvotePower */ upvotePower?: (number|null); /** ServerData burstPower */ burstPower?: (number|null); /** ServerData connectEndPoints */ connectEndPoints?: (string[]|null); } /** Represents a ServerData. */ class ServerData implements IServerData { /** * Constructs a new ServerData. * @param [properties] Properties to set */ constructor(properties?: master.IServerData); /** ServerData svMaxclients. */ public svMaxclients: number; /** ServerData clients. */ public clients: number; /** ServerData protocol. */ public protocol: number; /** ServerData hostname. */ public hostname: string; /** ServerData gametype. */ public gametype: string; /** ServerData mapname. */ public mapname: string; /** ServerData resources. */ public resources: string[]; /** ServerData server. */ public server: string; /** ServerData players. */ public players: master.IPlayer[]; /** ServerData iconVersion. */ public iconVersion: number; /** ServerData vars. */ public vars: { [k: string]: string }; /** ServerData enhancedHostSupport. */ public enhancedHostSupport: boolean; /** ServerData upvotePower. */ public upvotePower: number; /** ServerData burstPower. */ public burstPower: number; /** ServerData connectEndPoints. */ public connectEndPoints: string[]; /** * Creates a new ServerData instance using the specified properties. * @param [properties] Properties to set * @returns ServerData instance */ public static create(properties?: master.IServerData): master.ServerData; /** * Encodes the specified ServerData message. Does not implicitly {@link master.ServerData.verify|verify} messages. * @param message ServerData message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: master.IServerData, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ServerData message, length delimited. Does not implicitly {@link master.ServerData.verify|verify} messages. * @param message ServerData message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: master.IServerData, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ServerData message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ServerData * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): master.ServerData; /** * Decodes a ServerData message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ServerData * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): master.ServerData; /** * Verifies a ServerData message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ServerData message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ServerData */ public static fromObject(object: { [k: string]: any }): master.ServerData; /** * Creates a plain object from a ServerData message. Also converts values to other types if specified. * @param message ServerData * @param [options] Conversion options * @returns Plain object */ public static toObject(message: master.ServerData, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ServerData to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Server. */ interface IServer { /** Server EndPoint */ EndPoint?: (string|null); /** Server Data */ Data?: (master.IServerData|null); } /** Represents a Server. */ class Server implements IServer { /** * Constructs a new Server. * @param [properties] Properties to set */ constructor(properties?: master.IServer); /** Server EndPoint. */ public EndPoint: string; /** Server Data. */ public Data?: (master.IServerData|null); /** * Creates a new Server instance using the specified properties. * @param [properties] Properties to set * @returns Server instance */ public static create(properties?: master.IServer): master.Server; /** * Encodes the specified Server message. Does not implicitly {@link master.Server.verify|verify} messages. * @param message Server message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: master.IServer, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Server message, length delimited. Does not implicitly {@link master.Server.verify|verify} messages. * @param message Server message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: master.IServer, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Server message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Server * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): master.Server; /** * Decodes a Server message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Server * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): master.Server; /** * Verifies a Server message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Server message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Server */ public static fromObject(object: { [k: string]: any }): master.Server; /** * Creates a plain object from a Server message. Also converts values to other types if specified. * @param message Server * @param [options] Conversion options * @returns Plain object */ public static toObject(message: master.Server, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Server to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Servers. */ interface IServers { /** Servers servers */ servers?: (master.IServer[]|null); } /** Represents a Servers. */ class Servers implements IServers { /** * Constructs a new Servers. * @param [properties] Properties to set */ constructor(properties?: master.IServers); /** Servers servers. */ public servers: master.IServer[]; /** * Creates a new Servers instance using the specified properties. * @param [properties] Properties to set * @returns Servers instance */ public static create(properties?: master.IServers): master.Servers; /** * Encodes the specified Servers message. Does not implicitly {@link master.Servers.verify|verify} messages. * @param message Servers message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: master.IServers, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Servers message, length delimited. Does not implicitly {@link master.Servers.verify|verify} messages. * @param message Servers message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: master.IServers, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Servers message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Servers * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): master.Servers; /** * Decodes a Servers message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Servers * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): master.Servers; /** * Verifies a Servers message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Servers message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Servers */ public static fromObject(object: { [k: string]: any }): master.Servers; /** * Creates a plain object from a Servers message. Also converts values to other types if specified. * @param message Servers * @param [options] Conversion options * @returns Plain object */ public static toObject(message: master.Servers, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Servers to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ServerIcon. */ interface IServerIcon { /** ServerIcon endPoint */ endPoint?: (string|null); /** ServerIcon icon */ icon?: (Uint8Array|null); /** ServerIcon iconVersion */ iconVersion?: (number|null); } /** Represents a ServerIcon. */ class ServerIcon implements IServerIcon { /** * Constructs a new ServerIcon. * @param [properties] Properties to set */ constructor(properties?: master.IServerIcon); /** ServerIcon endPoint. */ public endPoint: string; /** ServerIcon icon. */ public icon: Uint8Array; /** ServerIcon iconVersion. */ public iconVersion: number; /** * Creates a new ServerIcon instance using the specified properties. * @param [properties] Properties to set * @returns ServerIcon instance */ public static create(properties?: master.IServerIcon): master.ServerIcon; /** * Encodes the specified ServerIcon message. Does not implicitly {@link master.ServerIcon.verify|verify} messages. * @param message ServerIcon message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: master.IServerIcon, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ServerIcon message, length delimited. Does not implicitly {@link master.ServerIcon.verify|verify} messages. * @param message ServerIcon message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: master.IServerIcon, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ServerIcon message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ServerIcon * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): master.ServerIcon; /** * Decodes a ServerIcon message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ServerIcon * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): master.ServerIcon; /** * Verifies a ServerIcon message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ServerIcon message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ServerIcon */ public static fromObject(object: { [k: string]: any }): master.ServerIcon; /** * Creates a plain object from a ServerIcon message. Also converts values to other types if specified. * @param message ServerIcon * @param [options] Conversion options * @returns Plain object */ public static toObject(message: master.ServerIcon, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ServerIcon to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ServerIcons. */ interface IServerIcons { /** ServerIcons icons */ icons?: (master.IServerIcon[]|null); } /** Represents a ServerIcons. */ class ServerIcons implements IServerIcons { /** * Constructs a new ServerIcons. * @param [properties] Properties to set */ constructor(properties?: master.IServerIcons); /** ServerIcons icons. */ public icons: master.IServerIcon[]; /** * Creates a new ServerIcons instance using the specified properties. * @param [properties] Properties to set * @returns ServerIcons instance */ public static create(properties?: master.IServerIcons): master.ServerIcons; /** * Encodes the specified ServerIcons message. Does not implicitly {@link master.ServerIcons.verify|verify} messages. * @param message ServerIcons message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: master.IServerIcons, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ServerIcons message, length delimited. Does not implicitly {@link master.ServerIcons.verify|verify} messages. * @param message ServerIcons message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: master.IServerIcons, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ServerIcons message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ServerIcons * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): master.ServerIcons; /** * Decodes a ServerIcons message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ServerIcons * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): master.ServerIcons; /** * Verifies a ServerIcons message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ServerIcons message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ServerIcons */ public static fromObject(object: { [k: string]: any }): master.ServerIcons; /** * Creates a plain object from a ServerIcons message. Also converts values to other types if specified. * @param message ServerIcons * @param [options] Conversion options * @returns Plain object */ public static toObject(message: master.ServerIcons, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ServerIcons to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyusd_auditanddiagnosticssetting_Information { interface tab_ActivityTrackingTab_Sections { tab_2_section_1: DevKit.Controls.Section; } interface tab_Diagnosticstab_Sections { Diagnosticstab_section_2: DevKit.Controls.Section; tab_3_section_2: DevKit.Controls.Section; } interface tab_UserSchemaSettingstab_Sections { tab_4_section_1: DevKit.Controls.Section; tab_4_section_UCI: DevKit.Controls.Section; } interface tab_ActivityTrackingTab extends DevKit.Controls.ITab { Section: tab_ActivityTrackingTab_Sections; } interface tab_Diagnosticstab extends DevKit.Controls.ITab { Section: tab_Diagnosticstab_Sections; } interface tab_UserSchemaSettingstab extends DevKit.Controls.ITab { Section: tab_UserSchemaSettingstab_Sections; } interface Tabs { ActivityTrackingTab: tab_ActivityTrackingTab; Diagnosticstab: tab_Diagnosticstab; UserSchemaSettingstab: tab_UserSchemaSettingstab; } interface Body { Tab: Tabs; IFRAME_userschemasettings: DevKit.Controls.IFrame; /** Select whether activity tracking should be enabled or not. */ msdyusd_ATEnabled: DevKit.Controls.Boolean; /** Select whether activity tracking for action calls should be enabled or not. */ msdyusd_ATforActionCalls: DevKit.Controls.Boolean; /** Select whether activity tracking for agent login should be enabled or not. */ msdyusd_ATforAgentLogin: DevKit.Controls.Boolean; /** Select whether activity tracking for agent scripts should be enabled or not. */ msdyusd_ATforAgentScripts: DevKit.Controls.Boolean; /** Select whether activity tracking for customer session should be enabled or not. */ msdyusd_ATforCustomerSession: DevKit.Controls.Boolean; /** Select whether activity tracking for events should be enabled or not. */ msdyusd_ATforEvents: DevKit.Controls.Boolean; /** Select whether activity tracking for hosted controls should be enabled or not. */ msdyusd_ATforHostedControl: DevKit.Controls.Boolean; /** Select whether activity tracking for sub action calls should be enabled or not. */ msdyusd_ATforSubActionCalls: DevKit.Controls.Boolean; /** Select whether activity tracking for UII Action should be enabled or not. */ msdyusd_ATforUIIAction: DevKit.Controls.Boolean; /** Select whether activity tracking for window navigation rules should be enabled or not. */ msdyusd_ATforWindowsNavRules: DevKit.Controls.Boolean; /** Cache Size Audit & Diagnostics Setting. */ msdyusd_CacheSize: DevKit.Controls.Integer; /** Choose whether to generate a memory dump for unhandled exceptions. */ msdyusd_CrashDumpEnabled: DevKit.Controls.Boolean; /** Select whether diagnostic tracking should be enabled or not. */ msdyusd_DGTEnabled: DevKit.Controls.Boolean; /** Select the verbosity level for diagnostics. */ msdyusd_DGTVerbosityLevel: DevKit.Controls.OptionSet; /** Select whether Enable Caching for UII Action should be enabled or not. */ msdyusd_EnableCaching: DevKit.Controls.Boolean; /** Choose whether to collect a diagnostics report when the application closes unexpectedly. */ msdyusd_ExitMonitoringEnabled: DevKit.Controls.Boolean; /** Enter the folder name where diagnostics logs are stored. */ msdyusd_LogsDirectory: DevKit.Controls.String; /** Enter the maximum size in megabytes (MB) of the folder where diagnostics logs are stored. */ msdyusd_MaxDiagnosticLogsSizeInMB: DevKit.Controls.Integer; /** Enter the name of the Audit & Diagnostics Setting. */ msdyusd_name: DevKit.Controls.String; /** Enter the shortcut key combination for on demand diagnostics report collection. */ msdyusd_ODDShortcut: DevKit.Controls.String; /** Shortcut to begin performance marker logs at runtime */ msdyusd_ODPerfBeginShortcut: DevKit.Controls.String; /** Shortcut to end performance marker logs at runtime */ msdyusd_ODPerfEndShortcut: DevKit.Controls.String; usercontrol_id: DevKit.Controls.ActionCards; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyusd_auditdiag_tracesourcesetting: DevKit.Controls.NavigationItem } interface Grid { TraceSourceSettings: DevKit.Controls.Grid; } } class Formmsdyusd_auditanddiagnosticssetting_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyusd_auditanddiagnosticssetting_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyusd_auditanddiagnosticssetting_Information */ Body: DevKit.Formmsdyusd_auditanddiagnosticssetting_Information.Body; /** The Navigation of form msdyusd_auditanddiagnosticssetting_Information */ Navigation: DevKit.Formmsdyusd_auditanddiagnosticssetting_Information.Navigation; /** The Grid of form msdyusd_auditanddiagnosticssetting_Information */ Grid: DevKit.Formmsdyusd_auditanddiagnosticssetting_Information.Grid; } class msdyusd_auditanddiagnosticssettingApi { /** * DynamicsCrm.DevKit msdyusd_auditanddiagnosticssettingApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Select whether activity tracking should be enabled or not. */ msdyusd_ATEnabled: DevKit.WebApi.BooleanValue; /** Select whether activity tracking for action calls should be enabled or not. */ msdyusd_ATforActionCalls: DevKit.WebApi.BooleanValue; /** Select whether activity tracking for agent login should be enabled or not. */ msdyusd_ATforAgentLogin: DevKit.WebApi.BooleanValue; /** Select whether activity tracking for agent scripts should be enabled or not. */ msdyusd_ATforAgentScripts: DevKit.WebApi.BooleanValue; /** Select whether activity tracking for customer session should be enabled or not. */ msdyusd_ATforCustomerSession: DevKit.WebApi.BooleanValue; /** Select whether activity tracking for events should be enabled or not. */ msdyusd_ATforEvents: DevKit.WebApi.BooleanValue; /** Select whether activity tracking for hosted controls should be enabled or not. */ msdyusd_ATforHostedControl: DevKit.WebApi.BooleanValue; /** Select whether activity tracking for sub action calls should be enabled or not. */ msdyusd_ATforSubActionCalls: DevKit.WebApi.BooleanValue; /** Select whether activity tracking for UII Action should be enabled or not. */ msdyusd_ATforUIIAction: DevKit.WebApi.BooleanValue; /** Select whether activity tracking for window navigation rules should be enabled or not. */ msdyusd_ATforWindowsNavRules: DevKit.WebApi.BooleanValue; /** Unique identifier for entity instances */ msdyusd_auditanddiagnosticssettingId: DevKit.WebApi.GuidValue; /** Cache Size Audit & Diagnostics Setting. */ msdyusd_CacheSize: DevKit.WebApi.IntegerValue; /** Choose whether to generate a memory dump for unhandled exceptions. */ msdyusd_CrashDumpEnabled: DevKit.WebApi.BooleanValue; /** Select whether diagnostic tracking should be enabled or not. */ msdyusd_DGTEnabled: DevKit.WebApi.BooleanValue; /** Select the verbosity level for diagnostics. */ msdyusd_DGTVerbosityLevel: DevKit.WebApi.OptionSetValue; /** Select whether Enable Caching for UII Action should be enabled or not. */ msdyusd_EnableCaching: DevKit.WebApi.BooleanValue; /** Choose whether to collect a diagnostics report when the application closes unexpectedly. */ msdyusd_ExitMonitoringEnabled: DevKit.WebApi.BooleanValue; msdyusd_IsDefault: DevKit.WebApi.BooleanValue; /** Enter the folder name where diagnostics logs are stored. */ msdyusd_LogsDirectory: DevKit.WebApi.StringValue; /** Enter the maximum size in megabytes (MB) of the folder where diagnostics logs are stored. */ msdyusd_MaxDiagnosticLogsSizeInMB: DevKit.WebApi.IntegerValue; /** Enter the name of the Audit & Diagnostics Setting. */ msdyusd_name: DevKit.WebApi.StringValue; /** Enter the shortcut key combination for on demand diagnostics report collection. */ msdyusd_ODDShortcut: DevKit.WebApi.StringValue; /** Shortcut to begin performance marker logs at runtime */ msdyusd_ODPerfBeginShortcut: DevKit.WebApi.StringValue; /** Shortcut to end performance marker logs at runtime */ msdyusd_ODPerfEndShortcut: DevKit.WebApi.StringValue; /** User Schema Settings */ msdyusd_userschemasettings: DevKit.WebApi.StringValue; /** Choose whether to enable Windows Error Reporting. */ msdyusd_WEREnabled: DevKit.WebApi.BooleanValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Contains the id of the process associated with the entity. */ processid: DevKit.WebApi.GuidValue; /** Contains the id of the stage where the entity is located. */ stageid: DevKit.WebApi.GuidValue; /** Status of the Audit & Diagnostics Setting. */ statecode: DevKit.WebApi.OptionSetValue; /** Status Reason of the Audit & Diagnostics Setting. */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */ traversedpath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyusd_auditanddiagnosticssetting { enum msdyusd_DGTVerbosityLevel { /** 100000000 */ Error, /** 100000002 */ Information, /** 100000003 */ Verbose, /** 100000001 */ Warning } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { Smithchart, SmithchartLegend, TooltipRender, ISmithchartLoadedEventArgs } from '../../../src/smithchart/index'; import { createElement, remove } from '@syncfusion/ej2-base'; import { MouseEvents } from '../base/events.spec'; import { profile, inMB, getMemoryProfile } from '../../common.spec'; Smithchart.Inject(SmithchartLegend, TooltipRender); /** * theme spec */ describe('Smithchart legend properties tesing', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe(' default themes testing', () => { let id: string = 'smithchart'; let smithchart: Smithchart; let ele: HTMLDivElement; let targetElement: HTMLElement; let tooltipElement: HTMLElement; let trigger: MouseEvents = new MouseEvents(); let spec: Element; beforeAll(() => { ele = <HTMLDivElement>createElement('div', { id: id, styles: 'height: 512px; width: 512px;' }); document.body.appendChild(ele); smithchart = new Smithchart({ title: { text: 'Impedance Transmission' }, horizontalAxis: { minorGridLines: { visible: true }, majorGridLines: { visible: true } }, series: [{ points: [ { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.5, reactance: 0.2 }, { resistance: 1.0, reactance: 0.4 }, { resistance: 1.5, reactance: 0.5 }, { resistance: 2.0, reactance: 0.5 }, { resistance: 2.5, reactance: 0.4 }, { resistance: 3.5, reactance: 0.0 }, { resistance: 4.5, reactance: -0.5 }, { resistance: 5.0, reactance: -1.0 } ], name: 'Transmission1', tooltip: { visible: true }, marker: { visible: true, dataLabel: { visible: true } } }], legendSettings: { visible: true, } }, '#' + id); }); afterAll(() => { remove(ele); smithchart.destroy(); }); it('Checking with axis Label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_RLabel_0'); expect(element.getAttribute('fill')).toEqual('#686868'); }; smithchart.refresh(); }); it('Checking with axis Line', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_series0_points'); expect(element.getAttribute('stroke')).toEqual('#00bdae'); }; smithchart.refresh(); }); it('Checking with major GridLine', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_horizontalAxisMajorGridLines'); expect(element.getAttribute('stroke')).toEqual('#dbdbdb'); }; smithchart.refresh(); }); it('Checking with minor GridLine', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_horizontalAxisMinorGridLines'); expect(element.getAttribute('stroke')).toEqual('#eaeaea'); }; smithchart.refresh(); }); it('Checking with chartTitle', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Smithchart_title'); expect(element.getAttribute('fill')).toEqual('#424242'); }; smithchart.refresh(); }); it('Checking with legend label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_LegendItemText0'); expect(element.getAttribute('fill')).toEqual('#353535'); }; smithchart.refresh(); }); it('Checking with background', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_SmithchartBorder'); expect(element.getAttribute('fill')).toEqual('#FFFFFF'); }; smithchart.refresh(); }); it('Checking with data label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_symbol0'); expect(element.getAttribute('fill')).toEqual('#00bdae'); }; smithchart.refresh(); }); it('Checking with data label font family', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_displayText0'); expect(element.getAttribute('font-family')).toEqual('Roboto, Segoe UI, Noto, Sans-serif'); }; smithchart.refresh(); }); it('Checking with data label font size', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_displayText0'); expect(element.getAttribute('font-size')).toEqual('12px'); }; smithchart.refresh(); }); // it('tooltip checking with mouse move', (done: Function) => { // smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { // let element: Element = document.getElementById(smithchart.element.id + '_series0_points'); // trigger.mousemoveEvent(element, 0, 0, 50, 255); // debugger; // element = document.getElementById(smithchart.element.id + '_smithchart_tooltip_div_text'); // expect(element.getAttribute('fill')).toBe('rgba(0, 8, 22, 0.75)'); // trigger.mousemoveEvent(element, 0, 0, 35, 255); // done(); // }; // smithchart.refresh(); // }); }); describe('Material themes testing', () => { let id: string = 'smithchart'; let smithchart: Smithchart; let ele: HTMLDivElement; let targetElement: HTMLElement; let tooltipElement: HTMLElement; let trigger: MouseEvents = new MouseEvents(); let spec: Element; beforeAll(() => { ele = <HTMLDivElement>createElement('div', { id: id, styles: 'height: 512px; width: 512px;' }); document.body.appendChild(ele); smithchart = new Smithchart({ theme: 'MaterialDark', title: { text: 'Impedance Transmission' }, horizontalAxis: { minorGridLines: { visible: true }, majorGridLines: { visible: true } }, series: [{ points: [ { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.5, reactance: 0.2 }, { resistance: 1.0, reactance: 0.4 }, { resistance: 1.5, reactance: 0.5 }, { resistance: 2.0, reactance: 0.5 }, { resistance: 2.5, reactance: 0.4 }, { resistance: 3.5, reactance: 0.0 }, { resistance: 4.5, reactance: -0.5 }, { resistance: 5.0, reactance: -1.0 } ], name: 'Transmission1', tooltip: { visible: true }, marker: { visible: true, dataLabel: { visible: true } } }], legendSettings: { visible: true, } }, '#' + id); }); afterAll(() => { remove(ele); smithchart.destroy(); }); it('Checking with axis Label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_RLabel_0'); expect(element.getAttribute('fill')).toEqual('#DADADA'); }; smithchart.refresh(); }); it('Checking with axis Line', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_series0_points'); expect(element.getAttribute('stroke')).toEqual('#9ECB08'); }; smithchart.refresh(); }); it('Checking with major GridLine', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_horizontalAxisMajorGridLines'); expect(element.getAttribute('stroke')).toEqual('#414040'); }; smithchart.refresh(); }); it('Checking with minor GridLine', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_horizontalAxisMinorGridLines'); expect(element.getAttribute('stroke')).toEqual('#514F4F'); }; smithchart.refresh(); }); it('Checking with chartTitle', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Smithchart_title'); expect(element.getAttribute('fill')).toEqual('#ffffff'); }; smithchart.refresh(); }); it('Checking with legend label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_LegendItemText0'); expect(element.getAttribute('fill')).toEqual('#DADADA'); }; smithchart.refresh(); }); it('Checking with background', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_SmithchartBorder'); expect(element.getAttribute('fill')).toEqual('#383838'); }; smithchart.refresh(); }); it('Checking with data label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_symbol0'); expect(element.getAttribute('fill')).toEqual('#9ECB08'); }; smithchart.refresh(); }); it('Checking with data label font family', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_displayText0'); expect(element.getAttribute('font-family')).toEqual('Roboto, Segoe UI, Noto, Sans-serif'); }; smithchart.refresh(); }); it('Checking with data label font size', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_displayText0'); expect(element.getAttribute('font-size')).toEqual('12px'); }; smithchart.refresh(); }); // it('tooltip checking with mouse move', (done: Function) => { // smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { // let element: Element = document.getElementById(smithchart.element.id + '_series0_points'); // trigger.mousemoveEvent(element, 0, 0, 50, 255); // debugger; // element = document.getElementById(smithchart.element.id + '_smithchart_tooltip_div_text'); // expect(element.getAttribute('fill')).toBe('rgba(0, 8, 22, 0.75)'); // trigger.mousemoveEvent(element, 0, 0, 35, 255); // done(); // }; // smithchart.refresh(); // }); }); describe('High Contrast themes testing', () => { let id: string = 'smithchart'; let smithchart: Smithchart; let ele: HTMLDivElement; let targetElement: HTMLElement; let tooltipElement: HTMLElement; let trigger: MouseEvents = new MouseEvents(); let spec: Element; beforeAll(() => { ele = <HTMLDivElement>createElement('div', { id: id, styles: 'height: 512px; width: 512px;' }); document.body.appendChild(ele); smithchart = new Smithchart({ theme: 'HighContrast', title: { text: 'Impedance Transmission' }, horizontalAxis: { minorGridLines: { visible: true }, majorGridLines: { visible: true } }, series: [{ points: [ { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.5, reactance: 0.2 }, { resistance: 1.0, reactance: 0.4 }, { resistance: 1.5, reactance: 0.5 }, { resistance: 2.0, reactance: 0.5 }, { resistance: 2.5, reactance: 0.4 }, { resistance: 3.5, reactance: 0.0 }, { resistance: 4.5, reactance: -0.5 }, { resistance: 5.0, reactance: -1.0 } ], name: 'Transmission1', tooltip: { visible: true }, marker: { visible: true, dataLabel: { visible: true } } }], legendSettings: { visible: true, } }, '#' + id); }); afterAll(() => { remove(ele); smithchart.destroy(); }); it('Checking with axis Label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_RLabel_0'); expect(element.getAttribute('fill')).toEqual('#ffffff'); }; smithchart.refresh(); }); it('Checking with axis Line', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_series0_points'); expect(element.getAttribute('stroke')).toEqual('#79ECE4'); }; smithchart.refresh(); }); it('Checking with major GridLine', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_horizontalAxisMajorGridLines'); expect(element.getAttribute('stroke')).toEqual('#BFBFBF'); }; smithchart.refresh(); }); it('Checking with minor GridLine', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_horizontalAxisMinorGridLines'); expect(element.getAttribute('stroke')).toEqual('#969696'); }; smithchart.refresh(); }); it('Checking with chartTitle', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Smithchart_title'); expect(element.getAttribute('fill')).toEqual('#ffffff'); }; smithchart.refresh(); }); it('Checking with legend label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_LegendItemText0'); expect(element.getAttribute('fill')).toEqual('#ffffff'); }; smithchart.refresh(); }); it('Checking with background', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_SmithchartBorder'); expect(element.getAttribute('fill')).toEqual('#000000'); }; smithchart.refresh(); }); it('Checking with data label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_symbol0'); expect(element.getAttribute('fill')).toEqual('#79ECE4'); }; smithchart.refresh(); }); it('Checking with data label font family', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_displayText0'); expect(element.getAttribute('font-family')).toEqual('Roboto, Segoe UI, Noto, Sans-serif'); }; smithchart.refresh(); }); it('Checking with data label font size', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_displayText0'); expect(element.getAttribute('font-size')).toEqual('12px'); }; smithchart.refresh(); }); // it('tooltip checking with mouse move', (done: Function) => { // smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { // let element: Element = document.getElementById(smithchart.element.id + '_series0_points'); // trigger.mousemoveEvent(element, 0, 0, 50, 255); // debugger; // element = document.getElementById(smithchart.element.id + '_smithchart_tooltip_div_text'); // expect(element.getAttribute('fill')).toBe('rgba(0, 8, 22, 0.75)'); // trigger.mousemoveEvent(element, 0, 0, 35, 255); // done(); // }; // smithchart.refresh(); // }); }); describe('Bootstrap4 themes testing', () => { let id: string = 'smithchart'; let smithchart: Smithchart; let ele: HTMLDivElement; let targetElement: HTMLElement; let tooltipElement: HTMLElement; let trigger: MouseEvents = new MouseEvents(); let spec: Element; beforeAll(() => { ele = <HTMLDivElement>createElement('div', { id: id, styles: 'height: 512px; width: 512px;' }); document.body.appendChild(ele); smithchart = new Smithchart({ theme: 'Bootstrap4', title: { text: 'Impedance Transmission' }, horizontalAxis: { minorGridLines: { visible: true }, majorGridLines: { visible: true } }, series: [{ points: [ { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.5, reactance: 0.2 }, { resistance: 1.0, reactance: 0.4 }, { resistance: 1.5, reactance: 0.5 }, { resistance: 2.0, reactance: 0.5 }, { resistance: 2.5, reactance: 0.4 }, { resistance: 3.5, reactance: 0.0 }, { resistance: 4.5, reactance: -0.5 }, { resistance: 5.0, reactance: -1.0 } ], name: 'Transmission1', tooltip: { visible: true }, marker: { visible: true, dataLabel: { visible: true } } }], legendSettings: { visible: true, } }, '#' + id); }); afterAll(() => { remove(ele); smithchart.destroy(); }); it('Checking with axis Label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_RLabel_0'); expect(element.getAttribute('fill')).toEqual('#212529'); }; smithchart.refresh(); }); it('Checking with axis Line', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_series0_points'); expect(element.getAttribute('stroke')).toEqual('#a16ee5'); }; smithchart.refresh(); }); it('Checking with major GridLine', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_horizontalAxisMajorGridLines'); expect(element.getAttribute('stroke')).toEqual('#CED4DA'); }; smithchart.refresh(); }); it('Checking with minor GridLine', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_horizontalAxisMinorGridLines'); expect(element.getAttribute('stroke')).toEqual('#DEE2E6'); }; smithchart.refresh(); }); it('Checking with chartTitle', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Smithchart_title'); expect(element.getAttribute('fill')).toEqual('#212529'); }; smithchart.refresh(); }); it('Checking with legend label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_LegendItemText0'); expect(element.getAttribute('fill')).toEqual('#212529'); }; smithchart.refresh(); }); it('Checking with background', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_SmithchartBorder'); expect(element.getAttribute('fill')).toEqual('#FFFFFF'); }; smithchart.refresh(); }); it('Checking with data label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_symbol0'); expect(element.getAttribute('fill')).toEqual('#a16ee5'); }; smithchart.refresh(); }); it('Checking with data label font family', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_displayText0'); expect(element.getAttribute('font-family')).toEqual('Roboto, Segoe UI, Noto, Sans-serif'); }; smithchart.refresh(); }); it('Checking with data label font size', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_displayText0'); expect(element.getAttribute('font-size')).toEqual('12px'); }; smithchart.refresh(); }); // it('tooltip checking with mouse move', (done: Function) => { // smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { // let element: Element = document.getElementById(smithchart.element.id + '_series0_points'); // trigger.mousemoveEvent(element, 0, 0, 50, 255); // debugger; // element = document.getElementById(smithchart.element.id + '_smithchart_tooltip_div_text'); // expect(element.getAttribute('fill')).toBe('rgba(0, 8, 22, 0.75)'); // trigger.mousemoveEvent(element, 0, 0, 35, 255); // done(); // }; // smithchart.refresh(); // }); }); describe('Tailwind themes testing', () => { let id: string = 'smithchart'; let smithchart: Smithchart; let ele: HTMLDivElement; let targetElement: HTMLElement; let tooltipElement: HTMLElement; let trigger: MouseEvents = new MouseEvents(); let spec: Element; beforeAll(() => { ele = <HTMLDivElement>createElement('div', { id: id, styles: 'height: 512px; width: 512px;' }); document.body.appendChild(ele); smithchart = new Smithchart({ theme: 'Tailwind', title: { text: 'Impedance Transmission' }, horizontalAxis: { minorGridLines: { visible: true }, majorGridLines: { visible: true } }, series: [{ points: [ { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.5, reactance: 0.2 }, { resistance: 1.0, reactance: 0.4 }, { resistance: 1.5, reactance: 0.5 }, { resistance: 2.0, reactance: 0.5 }, { resistance: 2.5, reactance: 0.4 }, { resistance: 3.5, reactance: 0.0 }, { resistance: 4.5, reactance: -0.5 }, { resistance: 5.0, reactance: -1.0 } ], name: 'Transmission1', tooltip: { visible: true }, marker: { visible: true, dataLabel: { visible: true } } }], legendSettings: { visible: true, } }, '#' + id); }); afterAll(() => { remove(ele); smithchart.destroy(); }); it('Checking with axis Label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_RLabel_0'); expect(element.getAttribute('fill')).toEqual('#6B7280'); }; smithchart.refresh(); }); it('Checking with major GridLine', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_horizontalAxisMajorGridLines'); expect(element.getAttribute('stroke')).toEqual('#E5E7EB'); }; smithchart.refresh(); }); it('Checking with minor GridLine', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_horizontalAxisMinorGridLines'); expect(element.getAttribute('stroke')).toEqual('#D1D5DB'); }; smithchart.refresh(); }); it('Checking with chartTitle', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Smithchart_title'); expect(element.getAttribute('fill')).toEqual('#374151'); }; smithchart.refresh(); }); it('Checking with legend label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_LegendItemText0'); expect(element.getAttribute('fill')).toEqual('#374151'); }; smithchart.refresh(); }); it('Checking with background', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_SmithchartBorder'); expect(element.getAttribute('fill')).toEqual('#FFFFFF'); }; smithchart.refresh(); }); it('Checking with data label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_symbol0'); expect(element.getAttribute('fill')).toEqual('#5A61F6'); }; smithchart.refresh(); }); it('Checking with data label font family', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_displayText0'); expect(element.getAttribute('font-family')).toEqual('Roboto, Segoe UI, Noto, Sans-serif'); }; smithchart.refresh(); }); it('Checking with data label font size', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_displayText0'); expect(element.getAttribute('font-size')).toEqual('12px'); }; smithchart.refresh(); }); }); describe('TailwindDark themes testing', () => { let id: string = 'smithchart'; let smithchart: Smithchart; let ele: HTMLDivElement; let targetElement: HTMLElement; let tooltipElement: HTMLElement; let trigger: MouseEvents = new MouseEvents(); let spec: Element; beforeAll(() => { ele = <HTMLDivElement>createElement('div', { id: id, styles: 'height: 512px; width: 512px;' }); document.body.appendChild(ele); smithchart = new Smithchart({ theme: 'TailwindDark', title: { text: 'Impedance Transmission' }, horizontalAxis: { minorGridLines: { visible: true }, majorGridLines: { visible: true } }, series: [{ points: [ { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0, reactance: 0.05 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.3, reactance: 0.1 }, { resistance: 0.5, reactance: 0.2 }, { resistance: 1.0, reactance: 0.4 }, { resistance: 1.5, reactance: 0.5 }, { resistance: 2.0, reactance: 0.5 }, { resistance: 2.5, reactance: 0.4 }, { resistance: 3.5, reactance: 0.0 }, { resistance: 4.5, reactance: -0.5 }, { resistance: 5.0, reactance: -1.0 } ], name: 'Transmission1', tooltip: { visible: true }, marker: { visible: true, dataLabel: { visible: true } } }], legendSettings: { visible: true, } }, '#' + id); }); afterAll(() => { remove(ele); smithchart.destroy(); }); it('Checking with axis Label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_RLabel_0'); expect(element.getAttribute('fill')).toEqual('#9CA3AF'); }; smithchart.refresh(); }); it('Checking with major GridLine', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_horizontalAxisMajorGridLines'); expect(element.getAttribute('stroke')).toEqual('#374151'); }; smithchart.refresh(); }); it('Checking with minor GridLine', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_horizontalAxisMinorGridLines'); expect(element.getAttribute('stroke')).toEqual('#4B5563'); }; smithchart.refresh(); }); it('Checking with chartTitle', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Smithchart_title'); expect(element.getAttribute('fill')).toEqual('#D1D5DB'); }; smithchart.refresh(); }); it('Checking with legend label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_LegendItemText0'); expect(element.getAttribute('fill')).toEqual('#D1D5DB'); }; smithchart.refresh(); }); it('Checking with background', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_SmithchartBorder'); expect(element.getAttribute('fill')).toEqual('#1f2937'); }; smithchart.refresh(); }); it('Checking with data label', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_symbol0'); expect(element.getAttribute('fill')).toEqual('#8B5CF6'); }; smithchart.refresh(); }); it('Checking with data label font family', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_displayText0'); expect(element.getAttribute('font-family')).toEqual('Roboto, Segoe UI, Noto, Sans-serif'); }; smithchart.refresh(); }); it('Checking with data label font size', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Series0_Points0_dataLabel_displayText0'); expect(element.getAttribute('font-size')).toEqual('12px'); }; smithchart.refresh(); }); }); });
the_stack
import * as assert from 'assert'; import * as path from 'path'; import * as vscode from 'vscode'; import { formatInstance } from '../providers/ModuleInstantiator'; const testFolderLocation = '../../src/test'; suite('ModuleInstantiator Tests', () => { test('test #1: formatInstance without parameters', async () => { let uri = vscode.Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'ModuleInstantiator.test.1.v')); let document = await vscode.workspace.openTextDocument(uri); // Range of the module in the document let fullRange = new vscode.Range(document.positionAt(585), document.positionAt(1129)); const container = document.getText(fullRange).replace(/^\s+|\s+$/g, ''); uri = vscode.Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'ModuleInstantiator.test.2.v')); document = await vscode.workspace.openTextDocument(uri); fullRange = new vscode.Range(document.positionAt(152), document.positionAt(354)); let instance = document.getText(fullRange).trim(); // Replace multiple space with a single space instance = instance.replace(/ +/g, ' '); let actual_instance; try { actual_instance = formatInstance('adder', container).trim(); } catch (error) { assert.fail(`formatInstance produced an error: ${error}`); } // Replace multiple space with a single space actual_instance = actual_instance.replace(/ +/g, ' '); assert.strictEqual(actual_instance, instance); }); test('test #2: formatInstance with parameters', async () => { let uri = vscode.Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'ModuleInstantiator.test.1.v')); let document = await vscode.workspace.openTextDocument(uri); // Range of the module in the document let fullRange = new vscode.Range(document.positionAt(1278), document.positionAt(1872)); let container = document.getText(fullRange).replace(/^\s+|\s+$/g, ''); // Replace multiple space with a single space container = container.replace(/ +/g, ' '); uri = vscode.Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'ModuleInstantiator.test.2.v')); document = await vscode.workspace.openTextDocument(uri); fullRange = new vscode.Range(document.positionAt(506), document.positionAt(785)); let instance = document.getText(fullRange).trim(); // Replace multiple space with a single space instance = instance.replace(/ +/g, ' '); let actual_instance; try { actual_instance = formatInstance('bar', container).trim(); } catch (error) { assert.fail(`formatInstance produced an error: ${error}`); } // Replace multiple space with a single space actual_instance = actual_instance.replace(/ +/g, ' '); assert.strictEqual(actual_instance, instance); }); test('test #3: formatInstance without parameters, ports in header', async () => { let uri = vscode.Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'ModuleInstantiator.test.1.v')); let document = await vscode.workspace.openTextDocument(uri); // Range of the module in the document let fullRange = new vscode.Range(document.positionAt(2041), document.positionAt(2611)); let container = document.getText(fullRange).replace(/^\s+|\s+$/g, ''); // Replace multiple space with a single space container = container.replace(/ +/g, ' '); uri = vscode.Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'ModuleInstantiator.test.2.v')); document = await vscode.workspace.openTextDocument(uri); fullRange = new vscode.Range(document.positionAt(954), document.positionAt(1071)); let instance = document.getText(fullRange).trim(); // Replace multiple space with a single space instance = instance.replace(/ +/g, ' '); let actual_instance; try { actual_instance = formatInstance('akker', container).trim(); } catch (error) { assert.fail(`formatInstance produced an error: ${error}`); } // Replace multiple space with a single space actual_instance = actual_instance.replace(/ +/g, ' '); assert.strictEqual(actual_instance, instance); }); test('test #4: formatInstance with parameters, ports in header', async () => { let uri = vscode.Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'ModuleInstantiator.test.1.v')); let document = await vscode.workspace.openTextDocument(uri); // range of the module in the document let fullRange = new vscode.Range(document.positionAt(2777), document.positionAt(3398)); let container = document.getText(fullRange).replace(/^\s+|\s+$/g, ''); // Replace multiple space with a single space container = container.replace(/ +/g, ' '); uri = vscode.Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'ModuleInstantiator.test.2.v')); document = await vscode.workspace.openTextDocument(uri); fullRange = new vscode.Range(document.positionAt(1240), document.positionAt(1407)); let instance = document.getText(fullRange).trim(); // Replace multiple space with a single space instance = instance.replace(/ +/g, ' '); let actual_instance; try { actual_instance = formatInstance('accer', container).trim(); } catch (error) { assert.fail(`formatInstance produced an error: ${error}`); } // Replace multiple white spaces with a single space actual_instance = actual_instance.replace(/ +/g, ' '); assert.strictEqual(actual_instance, instance); }); test('test #5: formatInstance with defaulted parameters.', async () => { let uri = vscode.Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'ModuleInstantiator.test.1.v')); let document = await vscode.workspace.openTextDocument(uri); // Range of the module in the document let fullRange = new vscode.Range(document.positionAt(3597), document.positionAt(3942)); let container = document.getText(fullRange).replace(/^\s+|\s+$/g, ''); // Replace multiple space with a single space container = container.replace(/ +/g, ' '); uri = vscode.Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'ModuleInstantiator.test.2.v')); document = await vscode.workspace.openTextDocument(uri); fullRange = new vscode.Range(document.positionAt(1590), document.positionAt(1747)); let instance = document.getText(fullRange).trim(); // Replace multiple space with a single space instance = instance.replace(/ +/g, ' '); let actual_instance; try { actual_instance = formatInstance('anner', container).trim(); } catch (error) { assert.fail(`formatInstance produced an error: ${error}`); } // Replace multiple white spaces with a single space actual_instance = actual_instance.replace(/ +/g, ' '); assert.strictEqual(actual_instance, instance); }); test('test #6: empty and undefined container/symbol scenarios', async () => { let actual_instance; // Empty container with valid symbol try { actual_instance = formatInstance('bar', ''); assert.strictEqual(actual_instance, undefined); } catch (error) { assert.fail(`formatInstance produced an error: ${error}`); } // Undefined container with valid symbol try { actual_instance = formatInstance('bar', undefined); assert.strictEqual(actual_instance, undefined); } catch (error) { assert.fail(`formatInstance produced an error: ${error}`); } const uri = vscode.Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'ModuleInstantiator.test.1.v')); const document = await vscode.workspace.openTextDocument(uri); // Range of the module in the document const fullRange = new vscode.Range(document.positionAt(1293), document.positionAt(1899)); let container = document.getText(fullRange).replace(/^\s+|\s+$/g, ''); // Replace multiple space with a single space container = container.replace(/ +/g, ' '); // Empty symbol with valid container try { actual_instance = formatInstance('', container); assert.strictEqual(actual_instance, undefined); } catch (error) { assert.fail(`formatInstance produced an error: ${error}`); } // Undefined symbol with valid container try { actual_instance = formatInstance(undefined, container); assert.strictEqual(actual_instance, undefined); } catch (error) { assert.fail(`formatInstance produced an error: ${error}`); } // Empty symbol and container try { actual_instance = formatInstance('', ''); assert.strictEqual(actual_instance, undefined); } catch (error) { assert.fail(`formatInstance produced an error: ${error}`); } // Undefined symbol and container try { actual_instance = formatInstance(undefined, undefined); assert.strictEqual(actual_instance, undefined); } catch (error) { assert.fail(`formatInstance produced an error: ${error}`); } // Valid symbol and null container try { actual_instance = formatInstance('bar', null); assert.strictEqual(actual_instance, undefined); } catch (error) { assert.fail(`formatInstance produced an error: ${error}`); } // Null symbol and container try { actual_instance = formatInstance(null, null); assert.strictEqual(actual_instance, undefined); } catch (error) { assert.fail(`formatInstance produced an error: ${error}`); } }); test('test #7: formatInstance golden output.', async () => { let uri = vscode.Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'ModuleInstantiator.test.1.v')); let document = await vscode.workspace.openTextDocument(uri); // Range of the module in the document let fullRange = new vscode.Range(document.positionAt(5269), document.positionAt(5814)); let container = document.getText(fullRange).replace(/^\s+|\s+$/g, ''); // Replace multiple space with a single space container = container.replace(/ +/g, ' '); uri = vscode.Uri.file(path.join(__dirname, testFolderLocation, 'test-files', 'ModuleInstantiator.test.2.v')); document = await vscode.workspace.openTextDocument(uri); fullRange = new vscode.Range(document.positionAt(2636), document.positionAt(2856)); const instance = document.getText(fullRange).trim(); let actual_instance; try { actual_instance = formatInstance('golden', container).trim(); } catch (error) { assert.fail(`formatInstance produced an error: ${error}`); } assert.strictEqual(actual_instance, instance); }); });
the_stack
import { promises as fs, exists } from 'fs'; import * as path from 'path'; import * as lockfile from '@yarnpkg/lockfile'; import * as semver from 'semver'; import { hoistDependencies } from './hoisting'; import { PackageJson, PackageLock, PackageLockEntry, PackageLockPackage, YarnLock } from './types'; export interface ShrinkwrapOptions { /** * The package.json file to start scanning for dependencies */ packageJsonFile: string; /** * The output lockfile to generate * * @default - Don't generate the file, just return the calculated output */ outputFile?: string; /** * Whether to hoist dependencies * * @default true */ hoist?: boolean; } export async function generateShrinkwrap(options: ShrinkwrapOptions): Promise<PackageLock> { // No args (yet) const packageJsonFile = options.packageJsonFile; const packageJsonDir = path.dirname(packageJsonFile); const yarnLockLoc = await findYarnLock(packageJsonDir); const yarnLock: YarnLock = lockfile.parse(await fs.readFile(yarnLockLoc, { encoding: 'utf8' })); const pkgJson = await loadPackageJson(packageJsonFile); const lock = await generateLockFile(pkgJson, yarnLock, packageJsonDir); if (options.hoist ?? true) { hoistDependencies({ version: '*', dependencies: lock.dependencies }); } validateTree(lock); if (options.outputFile) { // Write the shrinkwrap file await fs.writeFile(options.outputFile, JSON.stringify(lock, undefined, 2), { encoding: 'utf8' }); } return lock; } async function generateLockFile(pkgJson: PackageJson, yarnLock: YarnLock, rootDir: string): Promise<PackageLock> { const lockFile = { name: pkgJson.name, version: pkgJson.version, lockfileVersion: 1, requires: true, dependencies: await dependenciesFor(pkgJson.dependencies || {}, yarnLock, rootDir, [pkgJson.name]), }; checkRequiredVersions(lockFile); return lockFile; } const CYCLES_REPORTED = new Set<string>(); // eslint-disable-next-line max-len async function dependenciesFor(deps: Record<string, string>, yarnLock: YarnLock, rootDir: string, dependencyPath: string[]): Promise<Record<string, PackageLockPackage>> { const ret: Record<string, PackageLockPackage> = {}; // Get rid of any monorepo symlinks rootDir = await fs.realpath(rootDir); for (const [depName, versionRange] of Object.entries(deps)) { if (dependencyPath.includes(depName)) { const index = dependencyPath.indexOf(depName); const beforeCycle = dependencyPath.slice(0, index); const inCycle = [...dependencyPath.slice(index), depName]; const cycleString = inCycle.join(' => '); if (!CYCLES_REPORTED.has(cycleString)) { // eslint-disable-next-line no-console console.warn(`Dependency cycle: ${beforeCycle.join(' => ')} => [ ${cycleString} ]. Dropping dependency '${inCycle.slice(-2).join(' => ')}'.`); CYCLES_REPORTED.add(cycleString); } continue; } const depDir = await findPackageDir(depName, rootDir); const depPkgJsonFile = path.join(depDir, 'package.json'); const depPkgJson = await loadPackageJson(depPkgJsonFile); const yarnKey = `${depName}@${versionRange}`; // Sanity check if (depPkgJson.name !== depName) { throw new Error(`Looking for '${depName}' from ${rootDir}, but found '${depPkgJson.name}' in ${depDir}`); } const yarnResolved = yarnLock.object[yarnKey]; if (yarnResolved) { // Resolved by Yarn ret[depName] = { version: yarnResolved.version, integrity: yarnResolved.integrity, resolved: yarnResolved.resolved, requires: depPkgJson.dependencies, dependencies: await dependenciesFor(depPkgJson.dependencies || {}, yarnLock, depDir, [...dependencyPath, depName]), }; } else { // Comes from monorepo, just use whatever's in package.json ret[depName] = { version: depPkgJson.version, requires: depPkgJson.dependencies, dependencies: await dependenciesFor(depPkgJson.dependencies || {}, yarnLock, depDir, [...dependencyPath, depName]), }; } // Simplify by removing useless entries if (Object.keys(ret[depName].requires ?? {}).length === 0) { delete ret[depName].requires; } if (Object.keys(ret[depName].dependencies ?? {}).length === 0) { delete ret[depName].dependencies; } } return ret; } async function findYarnLock(start: string) { return findUp('yarn.lock', start); } async function findUp(fileName: string, start: string) { start = path.resolve(start); let dir = start; const yarnLockHere = () => path.join(dir, fileName); while (!await fileExists(yarnLockHere())) { const parent = path.dirname(dir); if (parent === dir) { throw new Error(`No ${fileName} found upwards from ${start}`); } dir = parent; } return yarnLockHere(); } async function loadPackageJson(fileName: string): Promise<PackageJson> { return JSON.parse(await fs.readFile(fileName, { encoding: 'utf8' })); } async function fileExists(fullPath: string): Promise<boolean> { try { await fs.stat(fullPath); return true; } catch (e) { if (e.code === 'ENOENT' || e.code === 'ENOTDIR') { return false; } throw e; } } export function formatPackageLock(entry: PackageLockEntry) { const lines = new Array<string>(); recurse([], entry); return lines.join('\n'); function recurse(names: string[], thisEntry: PackageLockEntry) { if (names.length > 0) { // eslint-disable-next-line no-console lines.push(`${names.join(' -> ')} @ ${thisEntry.version}`); } for (const [depName, depEntry] of Object.entries(thisEntry.dependencies || {})) { recurse([...names, depName], depEntry); } } } /** * Find package directory * * Do this by walking upwards in the directory tree until we find * `<dir>/node_modules/<package>/package.json`. * * ------- * * Things that we tried but don't work: * * 1. require.resolve(`${depName}/package.json`, { paths: [rootDir] }); * * Breaks with ES Modules if `package.json` has not been exported, which is * being enforced starting Node12. * * 2. findPackageJsonUpwardFrom(require.resolve(depName, { paths: [rootDir] })) * * Breaks if a built-in NodeJS package name conflicts with an NPM package name * (in Node15 `string_decoder` is introduced...) */ async function findPackageDir(depName: string, rootDir: string) { let prevDir; let dir = rootDir; while (dir !== prevDir) { const candidateDir = path.join(dir, 'node_modules', depName); if (await new Promise(ok => exists(path.join(candidateDir, 'package.json'), ok))) { return candidateDir; } prevDir = dir; dir = path.dirname(dir); // dirname('/') -> '/', dirname('c:\\') -> 'c:\\' } throw new Error(`Did not find '${depName}' upwards of '${rootDir}'`); } /** * We may sometimes try to adjust a package version to a version that's incompatible with the declared requirement. * * For example, this recently happened for 'netmask', where the package we * depend on has `{ requires: { netmask: '^1.0.6', } }`, but we need to force-substitute in version `2.0.1`. * * If NPM processes the shrinkwrap and encounters the following situation: * * ``` * { * netmask: { version: '2.0.1' }, * resolver: { * requires: { * netmask: '^1.0.6' * } * } * } * ``` * * NPM is going to disregard the swhinkrwap and still give `resolver` its own private * copy of netmask `^1.0.6`. * * We tried overriding the `requires` version, and that works for `npm install` (yay) * but if anyone runs `npm ls` afterwards, `npm ls` is going to check the actual source * `package.jsons` against the actual `node_modules` file tree, and complain that the * versions don't match. * * We run `npm ls` in our tests to make sure our dependency tree is sane, and our customers * might too, so this is not a great solution. * * To cut any discussion short in the future, we're going to detect this situation and * tell our future selves that is cannot and will not work, and we should find another * solution. */ export function checkRequiredVersions(root: PackageLock | PackageLockPackage) { recurse(root, []); function recurse(entry: PackageLock | PackageLockPackage, parentChain: PackageLockEntry[]) { // On the root, 'requires' is the value 'true', for God knows what reason. Don't care about those. if (typeof entry.requires === 'object') { // For every 'requires' dependency, find the version it actually got resolved to and compare. for (const [name, range] of Object.entries(entry.requires)) { const resolvedPackage = findResolved(name, [entry, ...parentChain]); if (!resolvedPackage) { continue; } if (!semver.satisfies(resolvedPackage.version, range)) { // Ruh-roh. throw new Error(`Looks like we're trying to force '${name}' to version '${resolvedPackage.version}', but the dependency ` + `is specified as '${range}'. This can never properly work via shrinkwrapping. Try vendoring a patched ` + 'version of the intermediary dependencies instead.'); } } } for (const dep of Object.values(entry.dependencies ?? {})) { recurse(dep, [entry, ...parentChain]); } } /** * Find a package name in a package lock tree. */ function findResolved(name: string, chain: PackageLockEntry[]) { for (const level of chain) { if (level.dependencies?.[name]) { return level.dependencies?.[name]; } } return undefined; } } /** * Check that all packages still resolve their dependencies to the right versions * * We have manipulated the tree a bunch. Do a sanity check to ensure that all declared * dependencies are satisfied. */ function validateTree(lock: PackageLock) { let failed = false; recurse(lock, [lock]); if (failed) { throw new Error('Could not satisfy one or more dependencies'); } function recurse(pkg: PackageLockEntry, rootPath: PackageLockEntry[]) { for (const pack of Object.values(pkg.dependencies ?? {})) { const p = [pack, ...rootPath]; checkRequiresOf(pack, p); recurse(pack, p); } } // rootPath: most specific one first function checkRequiresOf(pack: PackageLockPackage, rootPath: PackageLockEntry[]) { for (const [name, declaredRange] of Object.entries(pack.requires ?? {})) { const foundVersion = rootPath.map((p) => p.dependencies?.[name]?.version).find(isDefined); if (!foundVersion) { // eslint-disable-next-line no-console console.error(`Dependency on ${name} not satisfied: not found`); failed = true; } else if (!semver.satisfies(foundVersion, declaredRange)) { // eslint-disable-next-line no-console console.error(`Dependency on ${name} not satisfied: declared range '${declaredRange}', found '${foundVersion}'`); failed = true; } } } } function isDefined<A>(x: A): x is NonNullable<A> { return x !== undefined; }
the_stack
import { JsPsych, JsPsychPlugin, ParameterType, TrialType } from "jspsych"; const info = <const>{ name: "image-slider-response", parameters: { /** The image to be displayed */ stimulus: { type: ParameterType.IMAGE, pretty_name: "Stimulus", default: undefined, }, /** Set the image height in pixels */ stimulus_height: { type: ParameterType.INT, pretty_name: "Image height", default: null, }, /** Set the image width in pixels */ stimulus_width: { type: ParameterType.INT, pretty_name: "Image width", default: null, }, /** Maintain the aspect ratio after setting width or height */ maintain_aspect_ratio: { type: ParameterType.BOOL, pretty_name: "Maintain aspect ratio", default: true, }, /** Sets the minimum value of the slider. */ min: { type: ParameterType.INT, pretty_name: "Min slider", default: 0, }, /** Sets the maximum value of the slider */ max: { type: ParameterType.INT, pretty_name: "Max slider", default: 100, }, /** Sets the starting value of the slider */ slider_start: { type: ParameterType.INT, pretty_name: "Slider starting value", default: 50, }, /** Sets the step of the slider */ step: { type: ParameterType.INT, pretty_name: "Step", default: 1, }, /** Array containing the labels for the slider. Labels will be displayed at equidistant locations along the slider. */ labels: { type: ParameterType.HTML_STRING, pretty_name: "Labels", default: [], array: true, }, /** Width of the slider in pixels. */ slider_width: { type: ParameterType.INT, pretty_name: "Slider width", default: null, }, /** Label of the button to advance. */ button_label: { type: ParameterType.STRING, pretty_name: "Button label", default: "Continue", array: false, }, /** If true, the participant will have to move the slider before continuing. */ require_movement: { type: ParameterType.BOOL, pretty_name: "Require movement", default: false, }, /** Any content here will be displayed below the slider. */ prompt: { type: ParameterType.HTML_STRING, pretty_name: "Prompt", default: null, }, /** How long to show the stimulus. */ stimulus_duration: { type: ParameterType.INT, pretty_name: "Stimulus duration", default: null, }, /** How long to show the trial. */ trial_duration: { type: ParameterType.INT, pretty_name: "Trial duration", default: null, }, /** If true, trial will end when user makes a response. */ response_ends_trial: { type: ParameterType.BOOL, pretty_name: "Response ends trial", default: true, }, /** * If true, the image will be drawn onto a canvas element (prevents blank screen between consecutive images in some browsers). * If false, the image will be shown via an img element. */ render_on_canvas: { type: ParameterType.BOOL, pretty_name: "Render on canvas", default: true, }, }, }; type Info = typeof info; /** * **image-slider-response** * * jsPsych plugin for showing an image stimulus and getting a slider response * * @author Josh de Leeuw * @see {@link https://www.jspsych.org/plugins/jspsych-image-slider-response/ image-slider-response plugin documentation on jspsych.org} */ class ImageSliderResponsePlugin implements JsPsychPlugin<Info> { static info = info; constructor(private jsPsych: JsPsych) {} trial(display_element: HTMLElement, trial: TrialType<Info>) { var height, width; var html; // half of the thumb width value from jspsych.css, used to adjust the label positions var half_thumb_width = 7.5; if (trial.render_on_canvas) { var image_drawn = false; // first clear the display element (because the render_on_canvas method appends to display_element instead of overwriting it with .innerHTML) if (display_element.hasChildNodes()) { // can't loop through child list because the list will be modified by .removeChild() while (display_element.firstChild) { display_element.removeChild(display_element.firstChild); } } // create wrapper div, canvas element and image var content_wrapper = document.createElement("div"); content_wrapper.id = "jspsych-image-slider-response-wrapper"; content_wrapper.style.margin = "100px 0px"; var canvas = document.createElement("canvas"); canvas.id = "jspsych-image-slider-response-stimulus"; canvas.style.margin = "0"; canvas.style.padding = "0"; var ctx = canvas.getContext("2d"); var img = new Image(); img.onload = () => { // if image wasn't preloaded, then it will need to be drawn whenever it finishes loading if (!image_drawn) { getHeightWidth(); // only possible to get width/height after image loads ctx.drawImage(img, 0, 0, width, height); } }; img.src = trial.stimulus; // get/set image height and width - this can only be done after image loads because uses image's naturalWidth/naturalHeight properties const getHeightWidth = () => { if (trial.stimulus_height !== null) { height = trial.stimulus_height; if (trial.stimulus_width == null && trial.maintain_aspect_ratio) { width = img.naturalWidth * (trial.stimulus_height / img.naturalHeight); } } else { height = img.naturalHeight; } if (trial.stimulus_width !== null) { width = trial.stimulus_width; if (trial.stimulus_height == null && trial.maintain_aspect_ratio) { height = img.naturalHeight * (trial.stimulus_width / img.naturalWidth); } } else if (!(trial.stimulus_height !== null && trial.maintain_aspect_ratio)) { // if stimulus width is null, only use the image's natural width if the width value wasn't set // in the if statement above, based on a specified height and maintain_aspect_ratio = true width = img.naturalWidth; } canvas.height = height; canvas.width = width; }; getHeightWidth(); // call now, in case image loads immediately (is cached) // create container with slider and labels var slider_container = document.createElement("div"); slider_container.classList.add("jspsych-image-slider-response-container"); slider_container.style.position = "relative"; slider_container.style.margin = "0 auto 3em auto"; if (trial.slider_width !== null) { slider_container.style.width = trial.slider_width.toString() + "px"; } // create html string with slider and labels, and add to slider container html = '<input type="range" class="jspsych-slider" value="' + trial.slider_start + '" min="' + trial.min + '" max="' + trial.max + '" step="' + trial.step + '" id="jspsych-image-slider-response-response"></input>'; html += "<div>"; for (var j = 0; j < trial.labels.length; j++) { var label_width_perc = 100 / (trial.labels.length - 1); var percent_of_range = j * (100 / (trial.labels.length - 1)); var percent_dist_from_center = ((percent_of_range - 50) / 50) * 100; var offset = (percent_dist_from_center * half_thumb_width) / 100; html += '<div style="border: 1px solid transparent; display: inline-block; position: absolute; ' + "left:calc(" + percent_of_range + "% - (" + label_width_perc + "% / 2) - " + offset + "px); text-align: center; width: " + label_width_perc + '%;">'; html += '<span style="text-align: center; font-size: 80%;">' + trial.labels[j] + "</span>"; html += "</div>"; } html += "</div>"; slider_container.innerHTML = html; // add canvas and slider to content wrapper div content_wrapper.insertBefore(canvas, content_wrapper.firstElementChild); content_wrapper.insertBefore(slider_container, canvas.nextElementSibling); // add content wrapper div to screen and draw image on canvas display_element.insertBefore(content_wrapper, null); if (img.complete && Number.isFinite(width) && Number.isFinite(height)) { // if image has loaded and width/height have been set, then draw it now // (don't rely on img onload function to draw image when image is in the cache, because that causes a delay in the image presentation) ctx.drawImage(img, 0, 0, width, height); image_drawn = true; } // add prompt if there is one if (trial.prompt !== null) { display_element.insertAdjacentHTML("beforeend", trial.prompt); } // add submit button var submit_btn = document.createElement("button") as HTMLButtonElement; submit_btn.id = "jspsych-image-slider-response-next"; submit_btn.classList.add("jspsych-btn"); submit_btn.disabled = trial.require_movement ? true : false; submit_btn.innerHTML = trial.button_label; display_element.insertBefore(submit_btn, display_element.nextElementSibling); } else { html = '<div id="jspsych-image-slider-response-wrapper" style="margin: 100px 0px;">'; html += '<div id="jspsych-image-slider-response-stimulus">'; html += '<img src="' + trial.stimulus + '" style="'; if (trial.stimulus_height !== null) { html += "height:" + trial.stimulus_height + "px; "; if (trial.stimulus_width == null && trial.maintain_aspect_ratio) { html += "width: auto; "; } } if (trial.stimulus_width !== null) { html += "width:" + trial.stimulus_width + "px; "; if (trial.stimulus_height == null && trial.maintain_aspect_ratio) { html += "height: auto; "; } } html += '"></img>'; html += "</div>"; html += '<div class="jspsych-image-slider-response-container" style="position:relative; margin: 0 auto 3em auto; width:'; if (trial.slider_width !== null) { html += trial.slider_width + "px;"; } else { html += "auto;"; } html += '">'; html += '<input type="range" class="jspsych-slider" value="' + trial.slider_start + '" min="' + trial.min + '" max="' + trial.max + '" step="' + trial.step + '" id="jspsych-image-slider-response-response"></input>'; html += "<div>"; for (var j = 0; j < trial.labels.length; j++) { var label_width_perc = 100 / (trial.labels.length - 1); var percent_of_range = j * (100 / (trial.labels.length - 1)); var percent_dist_from_center = ((percent_of_range - 50) / 50) * 100; var offset = (percent_dist_from_center * half_thumb_width) / 100; html += '<div style="border: 1px solid transparent; display: inline-block; position: absolute; ' + "left:calc(" + percent_of_range + "% - (" + label_width_perc + "% / 2) - " + offset + "px); text-align: center; width: " + label_width_perc + '%;">'; html += '<span style="text-align: center; font-size: 80%;">' + trial.labels[j] + "</span>"; html += "</div>"; } html += "</div>"; html += "</div>"; html += "</div>"; if (trial.prompt !== null) { html += trial.prompt; } // add submit button html += '<button id="jspsych-image-slider-response-next" class="jspsych-btn" ' + (trial.require_movement ? "disabled" : "") + ">" + trial.button_label + "</button>"; display_element.innerHTML = html; // set image dimensions after image has loaded (so that we have access to naturalHeight/naturalWidth) var img = display_element.querySelector("img") as HTMLImageElement; if (trial.stimulus_height !== null) { height = trial.stimulus_height; if (trial.stimulus_width == null && trial.maintain_aspect_ratio) { width = img.naturalWidth * (trial.stimulus_height / img.naturalHeight); } } else { height = img.naturalHeight; } if (trial.stimulus_width !== null) { width = trial.stimulus_width; if (trial.stimulus_height == null && trial.maintain_aspect_ratio) { height = img.naturalHeight * (trial.stimulus_width / img.naturalWidth); } } else if (!(trial.stimulus_height !== null && trial.maintain_aspect_ratio)) { // if stimulus width is null, only use the image's natural width if the width value wasn't set // in the if statement above, based on a specified height and maintain_aspect_ratio = true width = img.naturalWidth; } img.style.height = height.toString() + "px"; img.style.width = width.toString() + "px"; } var response = { rt: null, response: null, }; if (trial.require_movement) { const enable_button = () => { display_element.querySelector<HTMLInputElement>( "#jspsych-image-slider-response-next" ).disabled = false; }; display_element .querySelector("#jspsych-image-slider-response-response") .addEventListener("mousedown", enable_button); display_element .querySelector("#jspsych-image-slider-response-response") .addEventListener("touchstart", enable_button); } const end_trial = () => { this.jsPsych.pluginAPI.clearAllTimeouts(); // save data var trialdata = { rt: response.rt, stimulus: trial.stimulus, slider_start: trial.slider_start, response: response.response, }; display_element.innerHTML = ""; // next trial this.jsPsych.finishTrial(trialdata); }; display_element .querySelector("#jspsych-image-slider-response-next") .addEventListener("click", () => { // measure response time var endTime = performance.now(); response.rt = Math.round(endTime - startTime); response.response = display_element.querySelector<HTMLInputElement>( "#jspsych-image-slider-response-response" ).valueAsNumber; if (trial.response_ends_trial) { end_trial(); } else { display_element.querySelector<HTMLButtonElement>( "#jspsych-image-slider-response-next" ).disabled = true; } }); if (trial.stimulus_duration !== null) { this.jsPsych.pluginAPI.setTimeout(() => { display_element.querySelector<HTMLElement>( "#jspsych-image-slider-response-stimulus" ).style.visibility = "hidden"; }, trial.stimulus_duration); } // end trial if trial_duration is set if (trial.trial_duration !== null) { this.jsPsych.pluginAPI.setTimeout(() => { end_trial(); }, trial.trial_duration); } var startTime = performance.now(); } } export default ImageSliderResponsePlugin;
the_stack
import { ActivityType, IdMap } from "./messages"; import { Activity, PassiveEntity, TraceDataUpdate, SendOp, ReceiveOp, DynamicScope } from "./execution-data"; import { getEntityId, getEntityGroupId, getEntityGroupVizId, getEntityVizId } from "./view"; import { KomposMetaModel, EntityRefType } from "./meta-model"; const NUM_ACTIVITIES_STARTING_GROUP = 4; const NUM_ENTITIES_STARTING_GROUP = 3; const HORIZONTAL_DISTANCE = 100; const VERTICAL_DISTANCE = 100; export abstract class NodeImpl implements d3.layout.force.Node { public index?: number; public px?: number; public py?: number; public fixed?: boolean; public weight?: number; private _x: number; private _y: number; constructor(x: number, y: number) { this._x = x; this._y = y; } public get x(): number { return this._x; } public set x(val: number) { if (val > 5000) { val = 5000; } else if (val < -5000) { val = -5000; } this._x = val; } public get y(): number { return this._y; } public set y(val: number) { if (val > 5000) { val = 5000; } else if (val < -5000) { val = -5000; } this._y = val; } } export abstract class EntityNode extends NodeImpl { constructor(x: number, y: number) { super(x, y); } public abstract getDataId(): string; public abstract getSystemViewId(): string; public abstract getEntityType(): EntityRefType; } export abstract class ActivityNode extends EntityNode { public readonly reflexive: boolean; constructor(reflexive: boolean, x: number, y: number) { super(x, y); this.reflexive = reflexive; } public abstract getGroupSize(): number; public abstract isRunning(): boolean; public abstract getName(): string; public abstract getQueryForCodePane(): string; public abstract getType(): ActivityType; public abstract getActivityId(): number; public getEntityType() { return EntityRefType.Activity; } } class ActivityNodeImpl extends ActivityNode { public readonly activity: Activity; constructor(activity: Activity, reflexive: boolean, x: number, y: number) { super(reflexive, x, y); this.activity = activity; } public getGroupSize() { return 1; } public isRunning() { return this.activity.running; } public getCreationScope() { return this.activity.creationScope; } public getName() { return this.activity.name; } public getDataId() { return getEntityId(this.activity.id); } public getSystemViewId() { return getEntityVizId(this.activity.id); } public getQueryForCodePane() { return "#" + getEntityId(this.activity.id); } public getType() { return this.activity.type; } public getActivityId() { return this.activity.id; } } class ActivityGroupNode extends ActivityNode { private group: ActivityGroup; constructor(group: ActivityGroup, reflexive: boolean, x: number, y: number) { super(reflexive, x, y); this.group = group; } public getGroupSize() { return this.group.activities.length; } public isRunning() { // TODO: GroupNode.isRunning() not yet implemented return true; } public getName() { return this.group.activities[0].name; } public getDataId() { return getEntityGroupId(this.group.id); } public getSystemViewId() { return getEntityGroupVizId(this.group.id); } public getQueryForCodePane() { let result = ""; for (const act of this.group.activities) { if (result !== "") { result += ","; } result += "#" + getEntityId(act.id); } return result; } public getType() { return this.group.activities[0].type; } public getActivityId() { return this.group.activities[0].id; } } export abstract class PassiveEntityNode extends EntityNode { public readonly reflexive: boolean; constructor(x: number, y: number) { super(x, y); } public abstract getGroupSize(): number; public abstract getLocationId(): string; public abstract getDataId(): string; public abstract getSystemViewId(): string; public abstract getEntityType(): EntityRefType; } function getPassiveEntityLocationId(pe: PassiveEntity): string { const ss = pe.origin; return ss.uri + ":" + ss.startLine + ":" + ss.startColumn + ":" + ss.charLength } export class PassiveEntityNodeImpl extends PassiveEntityNode { public readonly entity: PassiveEntity; public messages?: number[][]; constructor(entity: PassiveEntity, x: number, y: number) { super(x, y); this.entity = entity; } public getGroupSize() { return 1; } public getDataId() { return getEntityId(this.entity.id); } public getSystemViewId() { return getEntityVizId(this.entity.id); } public getLocationId() { return getPassiveEntityLocationId(this.entity); } public getEntityType() { return EntityRefType.PassiveEntity; } } class PassiveGroupNode extends PassiveEntityNode { private group: PassiveEntityGroup; constructor(group: PassiveEntityGroup, x: number, y: number) { super(x, y); this.group = group; } public getGroupSize() { return this.group.entities.length; } public getDataId() { return getEntityGroupId(this.group.id); } public getSystemViewId() { return getEntityGroupVizId(this.group.id); } public getLocationId() { return getPassiveEntityLocationId(this.group.entities[0]); } public getQueryForCodePane() { let result = ""; for (const e of this.group.entities) { if (result !== "") { result += ","; } result += "#" + getEntityId(e.id); } return result; } public getEntityType() { return EntityRefType.PassiveEntity; } } export interface EntityLink extends d3.layout.force.Link<EntityNode> { left: boolean; right: boolean; messageCount: number; creation?: boolean; } interface ActivityGroup { id: number; activities: Activity[]; groupNode?: ActivityGroupNode; } interface PassiveEntityGroup { id: number; entities: PassiveEntity[]; groupNode?: PassiveGroupNode; } type SourceTargetMap = Map<EntityNode, Map<EntityNode, number>>; function sourceTargetInc(map: SourceTargetMap, source: EntityNode, target: EntityNode, inc = 1) { let s = map.get(source); if (s === undefined) { s = new Map(); map.set(source, s); } let t = s.get(target); if (t === undefined) { t = 0; } t += inc; s.set(target, t); } export class SystemViewData { private metaModel: KomposMetaModel; private activities: IdMap<ActivityNodeImpl>; private activitiesPerType: IdMap<ActivityGroup>; private passiveEntities: IdMap<PassiveEntityNodeImpl>; private passiveEntitiesPerLocation: IdMap<PassiveEntityGroup>; private messages: SourceTargetMap; private maxMessageCount; constructor() { this.reset(); } public setMetaModel(metaModel: KomposMetaModel) { this.metaModel = metaModel; } public reset() { this.activities = {}; this.activitiesPerType = {}; this.passiveEntities = {}; this.passiveEntitiesPerLocation = {}; this.maxMessageCount = 0; this.messages = new Map(); } public updateTraceData(data: TraceDataUpdate) { console.assert(this.metaModel !== undefined, "Meta Model not yet initialized. Is there a race?"); for (const act of data.activities) { this.addActivity(act); } for (const e of data.passiveEntities) { this.addPassiveEntity(e); } for (const send of data.sendOps) { this.addMessage(send); } for (const rcv of data.receiveOps) { this.addMessageRcv(rcv); } } private addActivity(act: Activity) { const numGroups = Object.keys(this.activitiesPerType).length; if (!this.activitiesPerType[act.name]) { this.activitiesPerType[act.name] = { id: numGroups, activities: [] }; } this.activitiesPerType[act.name].activities.push(act); const node = new ActivityNodeImpl(act, false, // self-sends TODO what is this used for, maybe set to true when checking mailbox. HORIZONTAL_DISTANCE + HORIZONTAL_DISTANCE * this.activitiesPerType[act.name].activities.length, VERTICAL_DISTANCE * numGroups); this.activities[act.id.toString()] = node; } private addPassiveEntity(pe: PassiveEntity) { const numGroups = Object.keys(this.passiveEntitiesPerLocation).length; const locationId = getPassiveEntityLocationId(pe); if (!this.passiveEntitiesPerLocation[locationId]) { this.passiveEntitiesPerLocation[locationId] = { id: numGroups, entities: [] }; } this.passiveEntitiesPerLocation[locationId].entities.push(pe); const node = new PassiveEntityNodeImpl(pe, HORIZONTAL_DISTANCE + HORIZONTAL_DISTANCE * this.passiveEntitiesPerLocation[locationId].entities.length, VERTICAL_DISTANCE * numGroups); this.passiveEntities[pe.id.toString()] = node; } private getActivityGroupOrActivity(id: number): ActivityNode { const node = this.activities[id]; console.assert(node !== undefined); const group = this.activitiesPerType[node.getName()]; if (group.groupNode) { return group.groupNode; } return node; } private getPassiveGroupOrEntity(id: number): PassiveEntityNode { const node = this.passiveEntities[id]; console.assert(node !== undefined); const group = this.passiveEntitiesPerLocation[node.getLocationId()]; if (group.groupNode) { return group.groupNode; } return node; } private getNode(type: EntityRefType, entity: number | Activity | DynamicScope | PassiveEntity) { switch (type) { case EntityRefType.Activity: return this.activities[(<Activity> entity).id]; case EntityRefType.PassiveEntity: return this.passiveEntities[(<PassiveEntity> entity).id]; } } private addMessage(sendOp: SendOp) { const source = this.activities[sendOp.creationActivity.id]; const target = this.getNode(this.metaModel.sendOps[sendOp.type].target, sendOp.target); sourceTargetInc(this.messages, source, target); } private addMessageRcv(rcvOp: ReceiveOp) { const target = this.activities[rcvOp.creationActivity.id]; const source = this.getNode(this.metaModel.receiveOps[rcvOp.type].source, rcvOp.source); sourceTargetInc(this.messages, source, target); } public getMaxMessageSends() { return this.maxMessageCount; } public getActivityNodes(): ActivityNode[] { const groupStarted = {}; const arr: ActivityNode[] = []; for (const i in this.activities) { const a = this.activities[i]; const name = a.getName(); const group = this.activitiesPerType[name]; if (group.activities.length > NUM_ACTIVITIES_STARTING_GROUP) { if (!groupStarted[name]) { groupStarted[name] = true; const groupNode = new ActivityGroupNode(group, false, // todo reflexive HORIZONTAL_DISTANCE + HORIZONTAL_DISTANCE * group.activities.length, VERTICAL_DISTANCE * Object.keys(this.activitiesPerType).length); group.groupNode = groupNode; arr.push(groupNode); } } else { arr.push(a); } } return arr; } public getEntityNodes(): PassiveEntityNode[] { const groupStarted = {}; const result: PassiveEntityNode[] = []; for (const i in this.passiveEntities) { const p = this.passiveEntities[i]; const name = p.getLocationId(); const group = this.passiveEntitiesPerLocation[name]; if (group.entities.length > NUM_ENTITIES_STARTING_GROUP) { if (!groupStarted[name]) { groupStarted[name] = true; const groupNode = new PassiveGroupNode(group, HORIZONTAL_DISTANCE + HORIZONTAL_DISTANCE * group.entities.length, VERTICAL_DISTANCE * Object.keys(this.passiveEntitiesPerLocation).length); group.groupNode = groupNode; result.push(groupNode); } } else { result.push(p); } } return result; } private collectMessageLinks(links: EntityLink[]) { const messages: SourceTargetMap = new Map(); // first, consider groups for links for (const [source, m] of this.messages) { for (const [target, cnt] of m) { this.maxMessageCount = Math.max(this.maxMessageCount, cnt); let sender; switch (source.getEntityType()) { case EntityRefType.Activity: sender = this.getActivityGroupOrActivity((<ActivityNodeImpl> source).activity.id); break; case EntityRefType.PassiveEntity: sender = this.getPassiveGroupOrEntity((<PassiveEntityNodeImpl> source).entity.id); break; } let receiver; switch (target.getEntityType()) { case EntityRefType.Activity: receiver = this.getActivityGroupOrActivity((<ActivityNodeImpl> target).activity.id); break; case EntityRefType.PassiveEntity: receiver = this.getPassiveGroupOrEntity((<PassiveEntityNodeImpl> target).entity.id); break; } sourceTargetInc(messages, sender, receiver, cnt); } } // then, populate the list of links for (const [source, m] of messages) { for (const [target, cnt] of m) { links.push({ source: source, target: target, left: false, right: true, creation: false, messageCount: cnt }); } } } private collectCreationLinks(links: EntityLink[]) { const connections: SourceTargetMap = new Map(); for (const i in this.activities) { const act = this.activities[i]; if (act.activity.creationActivity === null) { // ignore first activity, it is created ex nihilo continue; } const target = this.getActivityGroupOrActivity(act.activity.id); const source = this.getActivityGroupOrActivity(act.activity.creationActivity.id); sourceTargetInc(connections, source, target); } for (const i in this.passiveEntities) { const e = this.passiveEntities[i]; const source = this.getActivityGroupOrActivity(e.entity.creationActivity.id); const target = this.getPassiveGroupOrEntity(e.entity.id); sourceTargetInc(connections, source, target); } for (const [source, m] of connections) { for (const [target, cnt] of m) { links.push(this.creationLink(source, target, cnt)); } } } private creationLink(source: EntityNode, target: EntityNode, cnt: number): EntityLink { return { source: source, target: target, left: false, right: true, creation: true, messageCount: cnt }; } public getLinks(): EntityLink[] { const links: EntityLink[] = []; this.collectMessageLinks(links); this.collectCreationLinks(links); return links; } }
the_stack
* Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you 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. */ /* * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. */ import { duration } from 'moment'; import { loggingSystemMock } from '../../logging/logging_system.mock'; import { LegacyOpenSearchClientConfig, parseOpenSearchClientConfig, } from './opensearch_client_config'; import { DEFAULT_HEADERS } from '../default_headers'; const logger = loggingSystemMock.create(); afterEach(() => jest.clearAllMocks()); test('parses minimally specified config', () => { expect( parseOpenSearchClientConfig( { apiVersion: 'master', customHeaders: { xsrf: 'something' }, logQueries: false, sniffOnStart: false, sniffOnConnectionFault: false, hosts: ['http://localhost/opensearch'], requestHeadersWhitelist: [], }, logger.get() ) ).toMatchInlineSnapshot(` Object { "apiVersion": "master", "hosts": Array [ Object { "headers": Object { "x-opensearch-product-origin": "opensearch-dashboards", "xsrf": "something", }, "host": "localhost", "path": "/opensearch", "port": "80", "protocol": "http:", "query": null, }, ], "keepAlive": true, "log": [Function], "sniffOnConnectionFault": false, "sniffOnStart": false, } `); }); test('parses fully specified config', () => { const opensearchConfig: LegacyOpenSearchClientConfig = { apiVersion: 'v7.0.0', customHeaders: { xsrf: 'something' }, logQueries: true, sniffOnStart: true, sniffOnConnectionFault: true, hosts: [ 'http://localhost/opensearch', 'http://domain.com:1234/opensearch', 'https://opensearch.local', ], requestHeadersWhitelist: [], username: 'opensearch', password: 'changeme', pingTimeout: 12345, requestTimeout: 54321, sniffInterval: 11223344, ssl: { verificationMode: 'certificate', certificateAuthorities: ['content-of-ca-path-1', 'content-of-ca-path-2'], certificate: 'content-of-certificate-path', key: 'content-of-key-path', keyPassphrase: 'key-pass', alwaysPresentCertificate: true, }, }; const opensearchClientConfig = parseOpenSearchClientConfig(opensearchConfig, logger.get()); // Check that original references aren't used. for (const host of opensearchClientConfig.hosts) { expect(opensearchConfig.customHeaders).not.toBe(host.headers); } expect(opensearchConfig.ssl).not.toBe(opensearchClientConfig.ssl); expect(opensearchClientConfig).toMatchInlineSnapshot(` Object { "apiVersion": "v7.0.0", "hosts": Array [ Object { "auth": "opensearch:changeme", "headers": Object { "x-opensearch-product-origin": "opensearch-dashboards", "xsrf": "something", }, "host": "localhost", "path": "/opensearch", "port": "80", "protocol": "http:", "query": null, }, Object { "auth": "opensearch:changeme", "headers": Object { "x-opensearch-product-origin": "opensearch-dashboards", "xsrf": "something", }, "host": "domain.com", "path": "/opensearch", "port": "1234", "protocol": "http:", "query": null, }, Object { "auth": "opensearch:changeme", "headers": Object { "x-opensearch-product-origin": "opensearch-dashboards", "xsrf": "something", }, "host": "opensearch.local", "path": "/", "port": "443", "protocol": "https:", "query": null, }, ], "keepAlive": true, "log": [Function], "pingTimeout": 12345, "requestTimeout": 54321, "sniffInterval": 11223344, "sniffOnConnectionFault": true, "sniffOnStart": true, "ssl": Object { "ca": Array [ "content-of-ca-path-1", "content-of-ca-path-2", ], "cert": "content-of-certificate-path", "checkServerIdentity": [Function], "key": "content-of-key-path", "passphrase": "key-pass", "rejectUnauthorized": true, }, } `); }); test('parses config timeouts of moment.Duration type', () => { expect( parseOpenSearchClientConfig( { apiVersion: 'master', customHeaders: { xsrf: 'something' }, logQueries: false, sniffOnStart: false, sniffOnConnectionFault: false, pingTimeout: duration(100, 'ms'), requestTimeout: duration(30, 's'), sniffInterval: duration(1, 'minute'), hosts: ['http://localhost:9200/opensearch'], requestHeadersWhitelist: [], }, logger.get() ) ).toMatchInlineSnapshot(` Object { "apiVersion": "master", "hosts": Array [ Object { "headers": Object { "x-opensearch-product-origin": "opensearch-dashboards", "xsrf": "something", }, "host": "localhost", "path": "/opensearch", "port": "9200", "protocol": "http:", "query": null, }, ], "keepAlive": true, "log": [Function], "pingTimeout": 100, "requestTimeout": 30000, "sniffInterval": 60000, "sniffOnConnectionFault": false, "sniffOnStart": false, } `); }); describe('#auth', () => { test('is not set if #auth = false even if username and password are provided', () => { expect( parseOpenSearchClientConfig( { apiVersion: 'v7.0.0', customHeaders: { xsrf: 'something' }, logQueries: true, sniffOnStart: true, sniffOnConnectionFault: true, hosts: ['http://user:password@localhost/opensearch', 'https://opensearch.local'], username: 'opensearch', password: 'changeme', requestHeadersWhitelist: [], }, logger.get(), { auth: false } ) ).toMatchInlineSnapshot(` Object { "apiVersion": "v7.0.0", "hosts": Array [ Object { "headers": Object { "x-opensearch-product-origin": "opensearch-dashboards", "xsrf": "something", }, "host": "localhost", "path": "/opensearch", "port": "80", "protocol": "http:", "query": null, }, Object { "headers": Object { "x-opensearch-product-origin": "opensearch-dashboards", "xsrf": "something", }, "host": "opensearch.local", "path": "/", "port": "443", "protocol": "https:", "query": null, }, ], "keepAlive": true, "log": [Function], "sniffOnConnectionFault": true, "sniffOnStart": true, } `); }); test('is not set if username is not specified', () => { expect( parseOpenSearchClientConfig( { apiVersion: 'v7.0.0', customHeaders: { xsrf: 'something' }, logQueries: true, sniffOnStart: true, sniffOnConnectionFault: true, hosts: ['https://opensearch.local'], requestHeadersWhitelist: [], password: 'changeme', }, logger.get(), { auth: true } ) ).toMatchInlineSnapshot(` Object { "apiVersion": "v7.0.0", "hosts": Array [ Object { "headers": Object { "x-opensearch-product-origin": "opensearch-dashboards", "xsrf": "something", }, "host": "opensearch.local", "path": "/", "port": "443", "protocol": "https:", "query": null, }, ], "keepAlive": true, "log": [Function], "sniffOnConnectionFault": true, "sniffOnStart": true, } `); }); test('is not set if password is not specified', () => { expect( parseOpenSearchClientConfig( { apiVersion: 'v7.0.0', customHeaders: { xsrf: 'something' }, logQueries: true, sniffOnStart: true, sniffOnConnectionFault: true, hosts: ['https://opensearch.local'], requestHeadersWhitelist: [], username: 'opensearch', }, logger.get(), { auth: true } ) ).toMatchInlineSnapshot(` Object { "apiVersion": "v7.0.0", "hosts": Array [ Object { "headers": Object { "x-opensearch-product-origin": "opensearch-dashboards", "xsrf": "something", }, "host": "opensearch.local", "path": "/", "port": "443", "protocol": "https:", "query": null, }, ], "keepAlive": true, "log": [Function], "sniffOnConnectionFault": true, "sniffOnStart": true, } `); }); }); describe('#customHeaders', () => { test('override the default headers', () => { const headerKey = Object.keys(DEFAULT_HEADERS)[0]; const parsedConfig = parseOpenSearchClientConfig( { apiVersion: 'master', customHeaders: { [headerKey]: 'foo' }, logQueries: false, sniffOnStart: false, sniffOnConnectionFault: false, hosts: ['http://localhost/opensearch'], requestHeadersWhitelist: [], }, logger.get() ); expect(parsedConfig.hosts[0].headers).toEqual({ [headerKey]: 'foo', }); }); }); describe('#log', () => { test('default logger with #logQueries = false', () => { const parsedConfig = parseOpenSearchClientConfig( { apiVersion: 'master', customHeaders: { xsrf: 'something' }, logQueries: false, sniffOnStart: false, sniffOnConnectionFault: false, hosts: ['http://localhost/opensearch'], requestHeadersWhitelist: [], }, logger.get() ); const Logger = new parsedConfig.log(); Logger.error('some-error'); Logger.warning('some-warning'); Logger.trace('some-trace'); Logger.info('some-info'); Logger.debug('some-debug'); expect(typeof Logger.close).toBe('function'); expect(loggingSystemMock.collect(logger)).toMatchInlineSnapshot(` Object { "debug": Array [], "error": Array [ Array [ "some-error", ], ], "fatal": Array [], "info": Array [], "log": Array [], "trace": Array [], "warn": Array [ Array [ "some-warning", ], ], } `); }); test('default logger with #logQueries = true', () => { const parsedConfig = parseOpenSearchClientConfig( { apiVersion: 'master', customHeaders: { xsrf: 'something' }, logQueries: true, sniffOnStart: false, sniffOnConnectionFault: false, hosts: ['http://localhost/opensearch'], requestHeadersWhitelist: [], }, logger.get() ); const Logger = new parsedConfig.log(); Logger.error('some-error'); Logger.warning('some-warning'); Logger.trace('METHOD', { path: '/some-path' }, '?query=2', 'unknown', '304'); Logger.info('some-info'); Logger.debug('some-debug'); expect(typeof Logger.close).toBe('function'); expect(loggingSystemMock.collect(logger)).toMatchInlineSnapshot(` Object { "debug": Array [ Array [ "304 METHOD /some-path ?query=2", Object { "tags": Array [ "query", ], }, ], ], "error": Array [ Array [ "some-error", ], ], "fatal": Array [], "info": Array [], "log": Array [], "trace": Array [], "warn": Array [ Array [ "some-warning", ], ], } `); }); test('custom logger', () => { const customLogger = jest.fn(); const parsedConfig = parseOpenSearchClientConfig( { apiVersion: 'master', customHeaders: { xsrf: 'something' }, logQueries: true, sniffOnStart: false, sniffOnConnectionFault: false, hosts: ['http://localhost/opensearch'], requestHeadersWhitelist: [], log: customLogger, }, logger.get() ); expect(parsedConfig.log).toBe(customLogger); }); }); describe('#ssl', () => { test('#verificationMode = none', () => { expect( parseOpenSearchClientConfig( { apiVersion: 'v7.0.0', customHeaders: {}, logQueries: true, sniffOnStart: true, sniffOnConnectionFault: true, hosts: ['https://opensearch.local'], requestHeadersWhitelist: [], ssl: { verificationMode: 'none' }, }, logger.get() ) ).toMatchInlineSnapshot(` Object { "apiVersion": "v7.0.0", "hosts": Array [ Object { "headers": Object { "x-opensearch-product-origin": "opensearch-dashboards", }, "host": "opensearch.local", "path": "/", "port": "443", "protocol": "https:", "query": null, }, ], "keepAlive": true, "log": [Function], "sniffOnConnectionFault": true, "sniffOnStart": true, "ssl": Object { "ca": undefined, "rejectUnauthorized": false, }, } `); }); test('#verificationMode = certificate', () => { const clientConfig = parseOpenSearchClientConfig( { apiVersion: 'v7.0.0', customHeaders: {}, logQueries: true, sniffOnStart: true, sniffOnConnectionFault: true, hosts: ['https://opensearch.local'], requestHeadersWhitelist: [], ssl: { verificationMode: 'certificate' }, }, logger.get() ); // `checkServerIdentity` shouldn't check hostname when verificationMode is certificate. expect( clientConfig.ssl!.checkServerIdentity!('right.com', { subject: { CN: 'wrong.com' } } as any) ).toBeUndefined(); expect(clientConfig).toMatchInlineSnapshot(` Object { "apiVersion": "v7.0.0", "hosts": Array [ Object { "headers": Object { "x-opensearch-product-origin": "opensearch-dashboards", }, "host": "opensearch.local", "path": "/", "port": "443", "protocol": "https:", "query": null, }, ], "keepAlive": true, "log": [Function], "sniffOnConnectionFault": true, "sniffOnStart": true, "ssl": Object { "ca": undefined, "checkServerIdentity": [Function], "rejectUnauthorized": true, }, } `); }); test('#verificationMode = full', () => { expect( parseOpenSearchClientConfig( { apiVersion: 'v7.0.0', customHeaders: {}, logQueries: true, sniffOnStart: true, sniffOnConnectionFault: true, hosts: ['https://opensearch.local'], requestHeadersWhitelist: [], ssl: { verificationMode: 'full' }, }, logger.get() ) ).toMatchInlineSnapshot(` Object { "apiVersion": "v7.0.0", "hosts": Array [ Object { "headers": Object { "x-opensearch-product-origin": "opensearch-dashboards", }, "host": "opensearch.local", "path": "/", "port": "443", "protocol": "https:", "query": null, }, ], "keepAlive": true, "log": [Function], "sniffOnConnectionFault": true, "sniffOnStart": true, "ssl": Object { "ca": undefined, "rejectUnauthorized": true, }, } `); }); test('#verificationMode is unknown', () => { expect(() => parseOpenSearchClientConfig( { apiVersion: 'v7.0.0', customHeaders: {}, logQueries: true, sniffOnStart: true, sniffOnConnectionFault: true, hosts: ['https://opensearch.local'], requestHeadersWhitelist: [], ssl: { verificationMode: 'misspelled' as any }, }, logger.get() ) ).toThrowErrorMatchingInlineSnapshot(`"Unknown ssl verificationMode: misspelled"`); }); test('#ignoreCertAndKey = true', () => { expect( parseOpenSearchClientConfig( { apiVersion: 'v7.0.0', customHeaders: {}, logQueries: true, sniffOnStart: true, sniffOnConnectionFault: true, hosts: ['https://opensearch.local'], requestHeadersWhitelist: [], ssl: { verificationMode: 'certificate', certificateAuthorities: ['content-of-ca-path'], certificate: 'content-of-certificate-path', key: 'content-of-key-path', keyPassphrase: 'key-pass', alwaysPresentCertificate: true, }, }, logger.get(), { ignoreCertAndKey: true } ) ).toMatchInlineSnapshot(` Object { "apiVersion": "v7.0.0", "hosts": Array [ Object { "headers": Object { "x-opensearch-product-origin": "opensearch-dashboards", }, "host": "opensearch.local", "path": "/", "port": "443", "protocol": "https:", "query": null, }, ], "keepAlive": true, "log": [Function], "sniffOnConnectionFault": true, "sniffOnStart": true, "ssl": Object { "ca": Array [ "content-of-ca-path", ], "checkServerIdentity": [Function], "rejectUnauthorized": true, }, } `); }); });
the_stack
import { BasetoolError } from "@/lib/errors"; import { Column } from "@/features/fields/types"; import { DataSource } from "@prisma/client"; import { GoogleSheetsCredentials, GoogleSheetsDataSource } from "./types"; import { GoogleSpreadsheet, GoogleSpreadsheetRow } from "google-spreadsheet"; import { IFilter } from "@/features/tables/types"; import { IQueryService, RecordResponse, RecordsResponse } from "../types"; import { OAuth2Client } from "google-auth-library"; import { decrypt, encrypt } from "@/lib/crypto"; import { getBaseOptions } from "@/features/fields"; import { isNull, isNumber, isUndefined, merge } from "lodash"; import { logger } from "@sentry/utils"; import GoogleDriveService from "./GoogleDriveService"; import cache from "@/features/cache"; import prisma from "@/prisma"; export type GoogleDataSourceOptions = { cache: boolean; expiresIn: number; // number of seconds }; const CACHE_EXPIRATION_TIME = 900; // 15 minutes class QueryService implements IQueryService { public client; public spreadsheetId; public dataSource: GoogleSheetsDataSource; public options?: GoogleDataSourceOptions; private doc: GoogleSpreadsheet | undefined; public oauthClient: OAuth2Client; constructor({ dataSource, options, }: { dataSource: GoogleSheetsDataSource; options?: GoogleDataSourceOptions; }) { // Set the default options this.options = merge( { cache: false, expiresIn: CACHE_EXPIRATION_TIME }, options ); if (!dataSource || !dataSource.encryptedCredentials) throw new Error("No data source provided."); // Set the datasource and spreadsheet this.dataSource = dataSource; this.spreadsheetId = dataSource?.options?.spreadsheetId; const oauthClient = initOauthClient(this.dataSource); if (!oauthClient) throw new Error("Failed to initialize the OAuth client"); this.oauthClient = oauthClient; // Initialize the clien this.client = new GoogleDriveService(dataSource); } public async connect(): Promise<this> { // Initialize the sheet - doc ID is the long id in the sheets URL if (this.spreadsheetId) { this.doc = new GoogleSpreadsheet(this.spreadsheetId); // add authentication const oauthClient = initOauthClient(this.dataSource); if (oauthClient) { this.oauthClient = oauthClient; this.doc.useOAuth2Client(oauthClient); } } return this; } public async disconnect(): Promise<this> { // This client does not need to disconnect return this; } /** Getters **/ public async getTables(): Promise<{ name: string }[]> { await this.loadInfo(); if (!this?.dataSource?.options?.spreadsheetId || !this.doc) return []; // Go through the provided sheets and return a commonly object const sheets = Object.entries(this.doc.sheetsByTitle).map( ([title, sheet]) => ({ name: title, }) ); return sheets; } public async getColumns({ tableName, storedColumns, }: { tableName: string; storedColumns?: Column[]; }): Promise<Column[]> { const key = `${this.dataSource.constructor.name}.getColumns({tableName:"${tableName}"})`; return await cache.fetch<Column[]>({ key, options: { fresh: this?.options?.cache !== true, expiresIn: this.options?.expiresIn, }, callback: async () => { await this.loadInfo(); if (!this.doc) return []; const sheet = this.doc.sheetsByTitle[tableName]; if (!sheet) return []; await sheet.loadHeaderRow(); if (sheet.headerValues.includes("")) throw new BasetoolError( `We might not know how to parse the column headers of your spreadsheet. Some might be empty. Would you please check the docs on how the spreadsheet should be formatted? However, the founding engineer team has been notified, and they are on it to fix it.`, { // links: ["https://google.com/link"], } ); const convertedHeaders = sheet.headerValues.map( (headerName: string) => { const columnSettings = storedColumns && storedColumns[headerName as any]; const fieldType = columnSettings?.fieldType || "Text"; const baseOptions = merge( getBaseOptions(), columnSettings?.baseOptions ); const fieldOptions = merge({}, columnSettings?.fieldOptions); return { name: headerName, label: headerName, fieldType, baseOptions, dataSourceInfo: {}, fieldOptions, primaryKey: false, }; } ); convertedHeaders.unshift({ name: "id", label: "id", fieldType: "Id", primaryKey: true, baseOptions: getBaseOptions(), dataSourceInfo: {}, fieldOptions: {}, }); return convertedHeaders; }, }); } public async getRecordsCount({ tableName, filters, }: { tableName: string; filters: IFilter[]; }): Promise<number> { await this.loadInfo(); if (!this.doc) return 0; const sheet = this.doc.sheetsByTitle[tableName]; const rows = await sheet.getRows(); return rows.length; } public async getRecords({ tableName, limit, offset, filters, orderBy, orderDirection, columns, }: { tableName: string; filters: []; limit: number; offset: number; orderBy: string; orderDirection: string; columns: Column[]; }): Promise<RecordsResponse> { await this.loadInfo(); if (!this.doc) return { records: [] }; const sheet = this.doc.sheetsByTitle[tableName]; const rawRows = await sheet.getRows(); const records = rawRows.map((row) => { return Object.fromEntries( Object.entries(row) .map(([key, value]) => { // Convert the rowNumber to an ID if (key === "_rowNumber") return ["id", value - 1]; return [key, value]; }) .filter(([key, value]) => !key.startsWith("_")) // Remove private fields off the object ); }); return { records }; } public async getRecord({ tableName, recordId, columns, }: { tableName: string; recordId: string; columns: Column[]; }): Promise<RecordResponse | undefined> { await this.loadInfo(); if (!this.doc) return; const row = await this.getRow(tableName, parseInt(recordId) - 1); if (!row) return; const record = Object.fromEntries( Object.entries(row) .map(([key, value]) => { // Convert the rowNumber to an ID if (key === "_rowNumber") return ["id", value - 1]; return [key, value]; }) .filter(([key, value]) => !key.startsWith("_")) // Remove private fields off the object ); return { record }; } public async createRecord({ tableName, data, }: { tableName: string; data: unknown; }): Promise<string | undefined> { await this.loadInfo(); if (!this.doc) return; const sheet = this.doc.sheetsByTitle[tableName]; try { const response = await sheet.addRow(data as any); if (response instanceof GoogleSpreadsheetRow) { return (response._rowNumber - 1).toString(); } } catch (error) {} return undefined; } public async updateRecord({ tableName, recordId, data, }: { tableName: string; recordId: string; data: unknown; }): Promise<boolean | number | string | undefined> { await this.loadInfo(); if (!this.doc) return; const row = await this.getRow(tableName, parseInt(recordId) - 1); if (!row) return; Object.entries(data as Record<string, unknown>).map(([key, value]) => { // Because the GoogleSpreadsheet library uses setters to set the data we can't dynamically assign the changes. // We're going to manually assign the change to _rawData. // Get index for column const columnIndex = row._sheet.headerValues.findIndex( (col: string) => col === key ); // Use the columnIndex to set the data. if (isNumber(columnIndex)) { row._rawData[columnIndex] = value; } }); try { await row.save(); return true; } catch (error: any) { logger.error(error.message); return false; } } public async deleteRecord({ tableName, recordId, }: { tableName: string; recordId: string; }): Promise<unknown> { return []; } public async deleteRecords({ tableName, recordIds, }: { tableName: string; recordIds: number[]; }): Promise<unknown> { return []; } private async loadInfo() { try { // loads document properties and worksheets await this.doc?.loadInfo(); } catch (error: any) { if ( error.message.includes( "No refresh token or refresh handler callback is set" ) ) { await refreshTokens(this.dataSource, this.oauthClient); const oauthClient = initOauthClient(this.dataSource); if (oauthClient) { this.oauthClient = oauthClient; this.doc?.useOAuth2Client(oauthClient); } await this.doc?.loadInfo(); } } } private async getRow( sheetName: string, id: number ): Promise<GoogleSpreadsheetRow | undefined> { await this.loadInfo(); if (!this.doc) return; const sheet = this.doc.sheetsByTitle[sheetName]; const rawRows = await sheet.getRows(); // Subtract one. Array start from 0 const row = rawRows[id]; if (!row) return; return row; } } export const getDecryptedCredentials = ( dataSource: DataSource ): GoogleSheetsCredentials => { if ( isUndefined(dataSource?.encryptedCredentials) || isNull(dataSource.encryptedCredentials) ) throw new Error("No credentials on record."); const credentialsAsAString = decrypt(dataSource.encryptedCredentials); if (!credentialsAsAString) throw new Error("No credentials on record."); let credentials: GoogleSheetsCredentials | null; try { credentials = JSON.parse(credentialsAsAString); } catch (error) { throw new Error("Failed to parse encrypted credentials"); } if (isNull(credentials)) throw new Error("No credentials on record"); return credentials; }; export const mergeAndEncryptCredentials = async ( dataSource: DataSource, newCredentials: unknown ) => { const existingCredentials = getDecryptedCredentials(dataSource); const mergedCredentials = merge(existingCredentials, newCredentials); const encryptedCredentials = encrypt(JSON.stringify(mergedCredentials)); await prisma.dataSource.update({ where: { id: dataSource.id }, data: { encryptedCredentials, }, }); }; export const refreshTokens = async ( dataSource: DataSource, oauthClient: OAuth2Client ) => { const { tokens } = getDecryptedCredentials(dataSource); const { refresh_token } = tokens; await oauthClient?.getToken( refresh_token, async (err: any, newTokens: any) => { if (err) { console.error("Error getting oAuth tokens:"); throw err; } await mergeAndEncryptCredentials(dataSource, newTokens); } ); }; export const initOauthClient = ( dataSource: DataSource ): OAuth2Client | undefined => { if (!dataSource.encryptedCredentials) return; // Initialize the OAuth2Client with your app's oauth credentials const oauthClient = new OAuth2Client({ clientId: process.env.GSHEETS_CLIENT_ID, clientSecret: process.env.GSHEETS_CLIENT_SECRET, }); const credentialsAsAString = decrypt(dataSource.encryptedCredentials); if (!credentialsAsAString) throw new Error("No credentials on record."); let credentials: GoogleSheetsCredentials | null; try { credentials = JSON.parse(credentialsAsAString); } catch (error) { throw new Error("Failed to parse encrypted credentials."); } if (!credentials || !credentials.tokens) throw new Error("No credentials on record."); const { tokens } = credentials; oauthClient.credentials.access_token = tokens.access_token; oauthClient.credentials.refresh_token = tokens.refresh_token; oauthClient.credentials.expiry_date = tokens.expiry_date; // We should refresh the tokens when neccesarry oauthClient.on("tokens", async (newTokens) => { await mergeAndEncryptCredentials(dataSource, newTokens); }); return oauthClient; }; export default QueryService;
the_stack
import { AfterViewChecked, ChangeDetectionStrategy, Component, OnInit, ViewChild, OnDestroy, Inject, } from '@angular/core'; // @ts-ignore import { SohoDataGridComponent } from 'ids-enterprise-ng'; import { PAGING_COLUMNS, PAGING_DATA } from './datagrid-paging-data'; const customErrorFormatter = function (row: any, cell: any, value: any, col: any, item: any, api: any) { value = `<svg class="icon datagrid-alert-icon icon-alert" style="height: 15px; margin-right: 6px; top: -2px; position: relative;" focusable="false" aria-hidden="true" role="presentation"> <use href="#icon-alert"></use> </svg><span>${value}</span>`; return Soho.Formatters.Expander(row, cell, value, col, item, api); }; @Component({ template: ` <div> <div soho-datagrid [columns]="columns" [data]="data" [filterable]="false" [selectable]="'single'" ></div> </div> `, }) export class NestedDatagridDemoComponent implements OnDestroy { columns?: SohoDataGridColumn[]; data?: any[]; id: any; constructor(@Inject('args') public args: any) { if (args && args.inputsData) { this.columns = args.inputsData; } if (args && args.data) { this.data = args.data; } if (args && args.item) { this.id = args.item.id; } } ngOnDestroy() { // console.log(`DemoCellFormatterComponent ${this.args.row} destroyed`); } } @Component({ selector: 'app-datagrid-expandable-row-nested-demo', templateUrl: 'datagrid-expandable-row-nested.demo.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class DataGridExpandableRowNestedDemoComponent implements AfterViewChecked, OnInit { @ViewChild(SohoDataGridComponent) sohoDataGridComponent?: SohoDataGridComponent; constructor() { } gridOptions?: SohoDataGridOptions = undefined; ngOnInit() { this.gridOptions = this.buildGridOptions(); } ngAfterViewChecked() { } private buildGridOptions(): SohoDataGridOptions { PAGING_DATA[0].detail = [ { id: '0' + '-121225', partName: 'Large Cooling Fan', quantity: 0.1, price: 0.35, amount: 0.035, }, { id: '0' + '-121226', partName: 'Extra Cooling System', quantity: 0.2, price: 0.05, amount: 0.01, }, { id: '0' + '-121227', partName: 'Electronics / Hardware', quantity: 0.3, price: 0.15, amount: 0.045, }, { id: '0' + '-121228', partName: 'Resilant Sub-Compressor', quantity: 0.3, price: 0.25, amount: 0.075, }, ]; PAGING_DATA[1].detail = [ { id: '1' + '-121225', partName: 'Large Cooling Fan', quantity: 0.1, price: 0.35, amount: 0.035, }, { id: '1' + '-121226', partName: 'Extra Cooling System', quantity: 0.2, price: 0.05, amount: 0.01, }, { id: '1' + '-121227', partName: 'Electronics / Hardware', quantity: 0.3, price: 0.15, amount: 0.045, }, { id: '1' + '-121228', partName: 'Resilant Sub-Compressor', quantity: 0.3, price: 0.25, amount: 0.075, }, ]; PAGING_DATA[2].detail = [ { id: '2' + '-121225', partName: 'Large Cooling Fan', quantity: 0.1, price: 0.35, amount: 0.035, }, { id: '2' + '-121226', partName: 'Extra Cooling System', quantity: 0.2, price: 0.05, amount: 0.01, }, { id: '2' + '-121227', partName: 'Electronics / Hardware', quantity: 0.3, price: 0.15, amount: 0.045, }, { id: '2' + '-121228', partName: 'Resilant Sub-Compressor', quantity: 0.3, price: 0.25, amount: 0.075, }, ]; PAGING_DATA[3].detail = [ { id: '3' + '-121225', partName: 'Large Cooling Fan', quantity: 0.1, price: 0.35, amount: 0.035, }, { id: '3' + '-121226', partName: 'Extra Cooling System', quantity: 0.2, price: 0.05, amount: 0.01, }, { id: '3' + '-121227', partName: 'Electronics / Hardware', quantity: 0.3, price: 0.15, amount: 0.045, }, { id: '3' + '-121228', partName: 'Resilant Sub-Compressor', quantity: 0.3, price: 0.25, amount: 0.075, }, ]; PAGING_DATA[4].detail = [ { id: '4' + '-121225', partName: 'Large Cooling Fan', quantity: 0.1, price: 0.35, amount: 0.035, }, { id: '4' + '-121226', partName: 'Extra Cooling System', quantity: 0.2, price: 0.05, amount: 0.01, }, { id: '4' + '-121227', partName: 'Electronics / Hardware', quantity: 0.3, price: 0.15, amount: 0.045, }, { id: '4' + '-121228', partName: 'Resilant Sub-Compressor', quantity: 0.3, price: 0.25, amount: 0.075, }, ]; PAGING_DATA[5].detail = [ { id: '5' + '-121225', partName: 'Large Cooling Fan', quantity: 0.1, price: 0.35, amount: 0.035, }, { id: '5' + '-121226', partName: 'Extra Cooling System', quantity: 0.2, price: 0.05, amount: 0.01, }, { id: '5' + '-121227', partName: 'Electronics / Hardware', quantity: 0.3, price: 0.15, amount: 0.045, }, { id: '5' + '-121228', partName: 'Resilant Sub-Compressor', quantity: 0.3, price: 0.25, amount: 0.075, }, ]; PAGING_DATA[6].detail = [ { id: '6' + '-121225', partName: 'Large Cooling Fan', quantity: 0.1, price: 0.35, amount: 0.035, }, { id: '6' + '-121226', partName: 'Extra Cooling System', quantity: 0.2, price: 0.05, amount: 0.01, }, { id: '6' + '-121227', partName: 'Electronics / Hardware', quantity: 0.3, price: 0.15, amount: 0.045, }, { id: '6' + '-121228', partName: 'Resilant Sub-Compressor', quantity: 0.3, price: 0.25, amount: 0.075, }, ]; PAGING_DATA[7].detail = [ { id: '7' + '-121225', partName: 'Large Cooling Fan', quantity: 0.1, price: 0.35, amount: 0.035, }, { id: '7' + '-121226', partName: 'Extra Cooling System', quantity: 0.2, price: 0.05, amount: 0.01, }, { id: '7' + '-121227', partName: 'Electronics / Hardware', quantity: 0.3, price: 0.15, amount: 0.045, }, { id: '7' + '-121228', partName: 'Resilant Sub-Compressor', quantity: 0.3, price: 0.25, amount: 0.075, }, ]; PAGING_DATA[8].detail = [ { id: '8' + '-121225', partName: 'Large Cooling Fan', quantity: 0.1, price: 0.35, amount: 0.035, }, { id: '8' + '-121226', partName: 'Extra Cooling System', quantity: 0.2, price: 0.05, amount: 0.01, }, { id: '8' + '-121227', partName: 'Electronics / Hardware', quantity: 0.3, price: 0.15, amount: 0.045, }, { id: '8' + '-121228', partName: 'Resilant Sub-Compressor', quantity: 0.3, price: 0.25, amount: 0.075, }, ]; PAGING_DATA[9].detail = [ { id: '9' + '-121225', partName: 'Large Cooling Fan', quantity: 0.1, price: 0.35, amount: 0.035, }, { id: '9' + '-121226', partName: 'Extra Cooling System', quantity: 0.2, price: 0.05, amount: 0.01, }, { id: '9' + '-121227', partName: 'Electronics / Hardware', quantity: 0.3, price: 0.15, amount: 0.045, }, { id: '9' + '-121228', partName: 'Resilant Sub-Compressor', quantity: 0.3, price: 0.25, amount: 0.075, }, ]; PAGING_DATA[10].detail = [ { id: '10' + '-121225', partName: 'Large Cooling Fan', quantity: 0.1, price: 0.35, amount: 0.035, }, { id: '10' + '-121226', partName: 'Extra Cooling System', quantity: 0.2, price: 0.05, amount: 0.01, }, { id: '10' + '-121227', partName: 'Electronics / Hardware', quantity: 0.3, price: 0.15, amount: 0.045, }, { id: '10' + '-121228', partName: 'Resilant Sub-Compressor', quantity: 0.3, price: 0.25, amount: 0.075, }, ]; PAGING_DATA[11].detail = [ { id: '11' + '-121225', partName: 'Large Cooling Fan', quantity: 0.1, price: 0.35, amount: 0.035, }, { id: '11' + '-121226', partName: 'Extra Cooling System', quantity: 0.2, price: 0.05, amount: 0.01, }, { id: '11' + '-121227', partName: 'Electronics / Hardware', quantity: 0.3, price: 0.15, amount: 0.045, }, { id: '11' + '-121228', partName: 'Resilant Sub-Compressor', quantity: 0.3, price: 0.25, amount: 0.075, }, ]; PAGING_DATA[12].detail = [ { id: '12' + '-121225', partName: 'Large Cooling Fan', quantity: 0.1, price: 0.35, amount: 0.035, }, { id: '12' + '-121226', partName: 'Extra Cooling System', quantity: 0.2, price: 0.05, amount: 0.01, }, { id: '12' + '-121227', partName: 'Electronics / Hardware', quantity: 0.3, price: 0.15, amount: 0.045, }, { id: '12' + '-121228', partName: 'Resilant Sub-Compressor', quantity: 0.3, price: 0.25, amount: 0.075, }, ]; PAGING_DATA[13].detail = [ { id: '13' + '-121225', partName: 'Large Cooling Fan', quantity: 0.1, price: 0.35, amount: 0.035, }, { id: '13' + '-121226', partName: 'Extra Cooling System', quantity: 0.2, price: 0.05, amount: 0.01, }, { id: '13' + '-121227', partName: 'Electronics / Hardware', quantity: 0.3, price: 0.15, amount: 0.045, }, { id: '13' + '-121228', partName: 'Resilant Sub-Compressor', quantity: 0.3, price: 0.25, amount: 0.075, }, ]; // Replace the first two column with an expander PAGING_COLUMNS[0] = { id: 'expander', field: 'productId', formatter: customErrorFormatter, // or just use Soho.Formatters.Expander, filterType: 'text', width: '15%', }; PAGING_COLUMNS[1].hidden = true; const NESTED_COLUMNS: SohoDataGridColumn[] = [ { id: 'id', name: 'Part Id', field: 'id', width: 200 }, { id: 'partName', name: 'Part Name', field: 'partName', formatter: Soho.Formatters.Hyperlink, }, { id: 'price', name: 'Price', field: 'price' }, { id: 'amount', name: 'Amount', field: 'amount' }, { id: 'quantity', name: 'Quantity', field: 'quantity' }, { id: 'action', name: 'Active', sortable: false, width: 80, formatter: Soho.Formatters.Button, icon: 'delete', headerTooltip: 'Delete', click: (_e, args) => { console.log(args[0].cell, args[0].row, args[0].item.id); }, }, ]; return { columns: PAGING_COLUMNS, dataset: PAGING_DATA, selectable: false, rowTemplateComponent: NestedDatagridDemoComponent, rowTemplateField: 'detail', rowTemplateComponentInputs: NESTED_COLUMNS, rowTemplate: ` <div class="datagrid-cell-layout"> </div> `, } as SohoDataGridOptions; } }
the_stack
import Adapt, { ActionInfo, AdaptElementOrNull, ChangeType, FinalDomElement, findElementsInDom, Handle, isHandle, QueryDomain, registerPlugin, Style, WidgetChange, WidgetPair, WidgetPlugin, } from "@adpt/core"; import { isEqualUnorderedArrays } from "@adpt/utils"; import { compact, pick } from "lodash"; import AWS from "./aws-sdk"; import { CFResourcePrimitive, CFResourceProps, isCFResourcePrimitiveElement, } from "./CFResource"; import { CFStackPrimitive, CFStackPrimitiveProps, isCFStackPrimitiveFinalElement, } from "./CFStack"; import { adaptDeployIdTag, adaptIdFromElem, adaptResourceId, adaptResourceIdTag, adaptStackIdTag, addTag, getTag, Tagged, } from "./plugin_utils"; export enum TemplateFormatVersion { current = "2010-09-09", } export type ResourceId = string; export interface Resources { [ id: string ]: CFResourceProps; // id is ResourceId } export interface Template { AWSTemplateFormatVersion?: TemplateFormatVersion; Description?: string; Metadata?: any; Parameters?: any; Mappings?: any; Conditions?: any; Transform?: any; Resources: Resources; Outputs?: any; } interface AwsRegion { region: string; accessKeyId: string; } interface AwsSecret { awsSecretAccessKey: string; } type StackObs = AWS.CloudFormation.Stack; interface LogicalRef { Ref: string; } function cfLogicalRef(handle: Handle): LogicalRef { return { Ref: adaptResourceId(handle) }; } function addAdaptDeployId(input: AWS.CloudFormation.CreateStackInput, deployID: string) { addTag(input, adaptDeployIdTag, deployID); } export function getAdaptDeployId(stack: StackObs) { return getTag(stack, adaptDeployIdTag); } function addAdaptStackId(input: AWS.CloudFormation.CreateStackInput, id: string) { addTag(input, adaptStackIdTag, id); } export function getAdaptStackId(stack: StackObs) { return getTag(stack, adaptStackIdTag); } function addAdaptResourceId(input: Tagged, id: ResourceId) { addTag(input, adaptResourceIdTag, id); } export function getAdaptResourceId(item: Tagged) { return getTag(item, adaptResourceIdTag); } export function isStatusActive(status: AWS.CloudFormation.StackStatus) { switch (status) { case "CREATE_FAILED": case "DELETE_IN_PROGRESS": case "DELETE_COMPLETE": return false; default: return true; } } export function isStackActive(stack: StackObs) { return isStatusActive(stack.StackStatus); } // Exported for testing export function createTemplate(stackEl: StackElement): Template { const template: Template = { AWSTemplateFormatVersion: TemplateFormatVersion.current, Resources: {}, }; const resources = findResourceElems(stackEl); for (const r of resources) { const resourceId = adaptResourceId(r); // Don't modify the element's props. Clone. const properties = { ...r.props.Properties }; for (const k of Object.keys(properties)) { if (isHandle(properties[k])) { properties[k] = cfLogicalRef(properties[k]); } } if (!r.props.tagsUnsupported) { // Don't modify the tags on the element either properties.Tags = properties.Tags ? properties.Tags.slice() : []; addAdaptResourceId(properties, resourceId); } template.Resources[resourceId] = { Type: r.props.Type, Properties: properties, }; } return template; } function toTemplateBody(template: Template): string { return JSON.stringify(template, null, 2); } function queryDomain(stackEl: StackElement): AwsQueryDomain { const creds = stackEl.props.awsCredentials; if (creds == null) throw new Error(`Required AWS credentials not set`); const id = { region: creds.awsRegion, accessKeyId: creds.awsAccessKeyId, }; const secret = { awsSecretAccessKey: creds.awsSecretAccessKey, }; return { id, secret }; } function adaptStackId(el: StackElement): string { return adaptIdFromElem("CFStack", el); } function findResourceElems(dom: AdaptElementOrNull) { const rules = <Style>{CFResourcePrimitive} {Adapt.rule()}</Style>; const candidateElems = findElementsInDom(rules, dom); return compact(candidateElems.map((e) => isCFResourcePrimitiveElement(e) ? e : null)); } export function findStackElems(dom: AdaptElementOrNull): StackElement[] { const rules = <Style>{CFStackPrimitive} {Adapt.rule()}</Style>; const candidateElems = findElementsInDom(rules, dom); return compact(candidateElems.map((e) => isCFStackPrimitiveFinalElement(e) ? e : null)); } export function stacksWithDeployID(stacks: StackObs[] | undefined, deployID: string): StackObs[] { if (stacks == null) return []; return stacks.filter((s) => (getAdaptDeployId(s) === deployID)); } const createDefaults = { Capabilities: [], NotificationARNs: [], Parameters: [], Tags: [], RollbackConfiguration: {}, }; interface StackParams extends Partial<AWS.CloudFormation.Stack> { TemplateBody?: string; } /** * Given a CFStackPrimitiveElement, creates a representation of the stack * that can be given to the client to create the stack. */ export function createStackParams(el: StackElement, deployID: string) { const { handle, key, awsCredentials, children, ...params } = el.props; addAdaptDeployId(params, deployID); addAdaptStackId(params, adaptStackId(el)); params.TemplateBody = toTemplateBody(createTemplate(el)); return { ...createDefaults, ...params }; } const modifyProps: (keyof StackParams)[] = [ "Capabilities", "Description", "EnableTerminationProtection", // UpdateTerminationProtection API "NotificationARNs", "Parameters", "RoleARN", "RollbackConfiguration", "Tags", "TemplateBody", // StackPolicyBody? // StackPolicyURL? ]; const replaceProps: (keyof StackParams)[] = [ "StackName", // Have to replace? ]; interface StackParams extends Partial<AWS.CloudFormation.Stack> { TemplateBody?: string; } function areEqual<T extends object>( expected: T, actual: T, propsToCompare: (keyof T)[], ) { const exp = pick(expected, propsToCompare); const act = pick(actual, propsToCompare); return isEqualUnorderedArrays(exp, act); } export function computeStackChanges( change: WidgetChange<StackElement>, actual: StackObs | undefined, deployID: string, ): ActionInfo { const { to, from } = change; const getElems = () => { const els: FinalDomElement[] = []; const root = to || from || null; if (root) els.push(root as FinalDomElement); return els.concat(findResourceElems(root)); }; // TODO: Ask AWS for detail on resource changes via change set API const actionInfo = (type: ChangeType, detail: string, elDetailTempl = detail) => ({ type, detail, changes: getElems().map((element) => { const elDetail = element.componentType === CFStackPrimitive ? detail : elDetailTempl.replace("{TYPE}", element.props.Type || "resource"); return { type, element, detail: elDetail, }; }) }); if (from == null && to == null) { return actionInfo(ChangeType.delete, "Destroying unrecognized CFStack"); } if (to == null) { return actual ? actionInfo(ChangeType.delete, "Destroying CFStack", "Destroying {TYPE} due to CFStack deletion") : actionInfo(ChangeType.none, "No changes required"); } if (actual == null) { return actionInfo(ChangeType.create, "Creating CFStack", "Creating {TYPE}"); } const expected = createStackParams(to, deployID); // Ugh. Special case. OnFailure doesn't show up in describeStacks output, // but instead transforms into DisableRollback. const onFailure = expected.OnFailure; switch (onFailure) { case "DO_NOTHING": expected.DisableRollback = true; break; case "DELETE": case "ROLLBACK": expected.DisableRollback = false; break; } if (!areEqual<StackParams>(expected, actual, replaceProps)) { return actionInfo(ChangeType.replace, "Replacing CFStack", "Replacing {TYPE} due to replacing CFStack"); } if (!areEqual<StackParams>(expected, actual, modifyProps)) { // TODO: Because we're modifying the stack, each resource within the // stack could be created, deleted, updated, or replaced...we must // ask the AWS API to know. return actionInfo(ChangeType.modify, "Modifying CFStack", "Resource {TYPE} may be affected by CFStack modification"); } return actionInfo(ChangeType.none, "No changes required"); } type AwsQueryDomain = QueryDomain<AwsRegion, AwsSecret>; type StackElement = FinalDomElement<CFStackPrimitiveProps>; type StackPair = WidgetPair<StackElement, StackObs>; // Exported for testing export class AwsPluginImpl extends WidgetPlugin<StackElement, StackObs, AwsQueryDomain> { findElems = (dom: AdaptElementOrNull): StackElement[] => { return findStackElems(dom); } getElemQueryDomain = (el: StackElement) => { return queryDomain(el); } getWidgetTypeFromObs = (_obs: StackObs): string => { return "CloudFormation Stack"; } getWidgetIdFromObs = (obs: StackObs): string => { return getAdaptStackId(obs) || obs.StackId || obs.StackName; } getWidgetTypeFromElem = (_el: StackElement): string => { return "CloudFormation Stack"; } getWidgetIdFromElem = (el: StackElement): string => { return adaptStackId(el); } computeChanges = (change: WidgetChange<StackElement>, obs: StackObs | undefined): ActionInfo => { return computeStackChanges(change, obs, this.deployID); } getObservations = async (domain: AwsQueryDomain, deployID: string): Promise<StackObs[]> => { const client = this.getClient(domain); const resp = await client.describeStacks().promise(); const stacks = stacksWithDeployID(resp.Stacks, deployID) .filter((stk) => isStackActive(stk)); let s: StackParams; for (s of stacks) { const r = await client.getTemplate({ StackName: s.StackId || s.StackName }).promise(); s.TemplateBody = r.TemplateBody; } return stacks; } createWidget = async ( domain: AwsQueryDomain, deployID: string, resource: StackPair): Promise<void> => { const el = resource.element; if (!el) throw new Error(`resource element null`); const params = createStackParams(el, deployID); const client = this.getClient(domain); await client.createStack(params).promise(); } destroyWidget = async ( domain: AwsQueryDomain, _deployID: string, resource: StackPair): Promise<void> => { const stackName = resource.observed && (resource.observed.StackId || resource.observed.StackName); if (!stackName) throw new Error(`Unable to delete stack that doesn't exist`); const client = this.getClient(domain); await client.deleteStack({ StackName: stackName }).promise(); } modifyWidget = async ( domain: AwsQueryDomain, deployID: string, resource: StackPair): Promise<void> => { const stackName = resource.observed && (resource.observed.StackId || resource.observed.StackName); if (!stackName) throw new Error(`Unable to update stack that doesn't exist`); const el = resource.element; if (!el) throw new Error(`resource element null`); const updateable = pick(createStackParams(el, deployID), modifyProps); // tslint:disable-next-line:no-object-literal-type-assertion const params = { StackName: stackName, ...updateable } as AWS.CloudFormation.UpdateStackInput; const client = this.getClient(domain); await client.updateStack(params).promise(); } getClient(domain: AwsQueryDomain) { // TODO(mark): Cache a client for each domain. return new AWS.CloudFormation({ region: domain.id.region, accessKeyId: domain.id.accessKeyId, secretAccessKey: domain.secret.awsSecretAccessKey, }); } } // Exported for testing export function createAwsPlugin() { return new AwsPluginImpl(); } registerPlugin({ name: "aws", module, create: createAwsPlugin, });
the_stack
export interface InstanceState { condition: Condition; since: Date; activeSince?: Date; healthy?: boolean; goal: Goal; } export interface Instance { instanceId: string; state: InstanceState; agentInfo?: AgentInfo; runSpecVersion: Date; unreachableStrategy: unknown; // TODO: implement unions; } export interface AgentInfo { host: string; agentId?: string; region?: string; zone?: string; attributes: AgentAttribute[]; } export interface Status { stagedAt: Date; startedAt?: Date; mesosStatus?: string; condition: Condition; networkInfo: NetworkInfo; } export interface Task { appId: string; healthCheckResults?: Health[]; checkResult?: CheckStatus; host: string; id: string; ipAddresses?: IpAddr[]; ports?: number[]; servicePorts?: number[]; slaveId?: string; state: MesosTaskState; stagedAt?: string; startedAt?: string; version?: string; localVolumes?: LocalVolumeId[]; region?: string; zone?: string; } export interface IpAddr { ipAddress: string; protocol: IpProtocol; } export interface NetworkInfo { hostName: string; hostPorts: number[]; ipAddresses: NetworkInfoIPAddress[]; } export interface TaskList { tasks: Task[]; } export interface NetworkInfoIPAddress { ipAddress: string; protocol: IpProtocol; } export interface TaskSingle { task: Task; } export enum TaskStatusCondition { running = "running", staging = "staging", } export interface VersionInfo { lastScalingAt: Date; lastConfigChangeAt: Date; } export interface NetworkStatus { name?: string; addresses?: string[]; } export interface ContainerEndpointStatus { name: string; allocatedHostPort?: number; healthy?: boolean; } export interface ContainerTerminationHistory { containerId: string; lastKnownState?: string; termination?: ContainerTerminationState; } export interface TerminationHistory { instanceID: string; startedAt: Date; terminatedAt: Date; message?: string; containers?: ContainerTerminationHistory[]; } export interface StatusCondition { name: string; lastChanged: Date; lastUpdated: Date; value: string; reason?: string; } export interface PodStatus { id: string; spec: Pod; status: PodState; statusSince: Date; message?: string; instances?: PodInstanceStatus[]; terminationHistory?: TerminationHistory[]; lastUpdated: Date; lastChanged: Date; } export interface ContainerStatus { name: string; status: string; statusSince: Date; message?: string; conditions?: StatusCondition[]; containerId?: string; endpoints?: ContainerEndpointStatus[]; resources?: Resources; termination?: ContainerTerminationState; lastUpdated: Date; lastChanged: Date; } export enum PodState { DEGRADED = "DEGRADED", STABLE = "STABLE", TERMINAL = "TERMINAL", } export interface PodInstanceStatus { id: string; status: PodInstanceState; statusSince: Date; message?: string; conditions?: StatusCondition[]; agentHostname?: string; agentId?: string; agentRegion?: string; agentZone?: string; resources?: Resources; networks?: NetworkStatus[]; containers?: ContainerStatus[]; specReference?: string; localVolumes?: LocalVolumeId[]; lastUpdated: Date; lastChanged: Date; } export interface ContainerTerminationState { exitCode?: number; message?: string; } export enum PodInstanceState { PENDING = "PENDING", STAGING = "STAGING", STABLE = "STABLE", DEGRADED = "DEGRADED", TERMINAL = "TERMINAL", } export interface Resources { cpus: number; mem: number; disk?: number; gpus?: number; } export interface Pod { id: string; labels?: object; version?: Date; user?: string; environment?: object; containers: PodContainer[]; secrets?: object; volumes?: unknown; // TODO: implement unions[]; networks?: Network[]; scaling?: PodScalingPolicy; scheduling?: PodSchedulingPolicy; executorResources?: ExecutorResources; } export interface Constraint { fieldName: string; operator: ConstraintOperator; value?: string; } export enum ConstraintOperator { UNIQUE = "UNIQUE", CLUSTER = "CLUSTER", GROUP_BY = "GROUP_BY", LIKE = "LIKE", UNLIKE = "UNLIKE", MAX_PER = "MAX_PER", IS = "IS", } export enum KillSelection { YOUNGEST_FIRST = "YOUNGEST_FIRST", OLDEST_FIRST = "OLDEST_FIRST", } export interface Health { alive: boolean; consecutiveFailures: number; firstSuccess?: string; instanceId: string; lastSuccess?: string; lastFailure?: string; lastFailureCause?: string; } export interface HealthCheck { http?: HttpCheck; tcp?: TcpCheck; exec?: CommandCheck; gracePeriodSeconds?: number; intervalSeconds?: number; maxConsecutiveFailures?: number; timeoutSeconds?: number; delaySeconds?: number; } export interface AppCommandCheck { value: string; } export enum AppHealthCheckProtocol { HTTP = "HTTP", HTTPS = "HTTPS", TCP = "TCP", COMMAND = "COMMAND", MESOS_TCP = "MESOS_TCP", MESOS_HTTP = "MESOS_HTTP", MESOS_HTTPS = "MESOS_HTTPS", } export interface AppHealthCheck { command?: AppCommandCheck; gracePeriodSeconds?: number; ignoreHttp1xx?: boolean; intervalSeconds?: number; maxConsecutiveFailures?: number; path?: string; port?: number; portIndex?: number; protocol?: AppHealthCheckProtocol; ipProtocol?: IpProtocol; timeoutSeconds?: number; delaySeconds?: number; } export interface CommandCheck { command: unknown; // TODO: implement unions; } export enum IpProtocol { IPv4 = "IPv4", IPv6 = "IPv6", } export interface DeploymentPlan { id: string; steps: DeploymentSteps; version: Date; } export interface DeploymentSteps { steps: DeploymentStep[]; } export interface ExecutorResources { cpus?: number; mem?: number; disk?: number; } export interface SecretDef { source: string; } export interface DeploymentActionInfo { action: DeploymentActionName; app?: string; pod?: string; readinessCheckResults: TaskReadinessCheckResult[]; } export interface DeploymentStepInfo { id: string; steps: DeploymentSteps; version: Date; affectedApps: string[]; affectedPods: string[]; currentActions: DeploymentActionInfo[]; currentStep: number; totalSteps: number; } export interface ReadinessCheck { name?: string; protocol?: HttpScheme; path?: string; portName?: string; intervalSeconds?: number; timeoutSeconds?: number; httpStatusCodesForReady?: number[]; preserveLastResponse?: boolean; } export interface ReadinessCheckHttpResponse { status: number; contentType: string; body: string; } export interface TaskReadinessCheckResult { name: string; taskId: string; ready: boolean; lastResponse?: ReadinessCheckHttpResponse; } export enum HttpScheme { HTTP = "HTTP", HTTPS = "HTTPS", } export interface ErrorDetail { message?: string; errors?: string[]; } export interface Error { message: string; details?: ErrorDetail[]; } export interface LoggerChange { level: LoggerLevel; logger: string; durationSeconds?: number; } export enum LoggerLevel { trace = "trace", debug = "debug", info = "info", warn = "warn", error = "error", } export interface DeleteTasks { ids: string[]; } export interface DockerContainer { credential?: DockerCredentials; pullConfig?: DockerPullConfig; forcePullImage?: boolean; image: string; network?: DockerNetwork; parameters?: DockerParameter[]; portMappings?: ContainerPortMapping[]; privileged?: boolean; } export interface DockerCredentials { principal: string; secret?: string; } export interface AppCContainer { image: string; id?: string; labels?: object; forcePullImage?: boolean; } export interface Container { type: EngineType; docker?: DockerContainer; appc?: AppCContainer; volumes?: unknown; // TODO: implement unions[]; portMappings?: ContainerPortMapping[]; } export interface DockerParameter { key: string; value: string; } export enum DockerNetwork { BRIDGE = "BRIDGE", HOST = "HOST", NONE = "NONE", USER = "USER", } export enum EngineType { MESOS = "MESOS", DOCKER = "DOCKER", } export interface ContainerPortMapping { containerPort: number; hostPort?: number; labels?: object; name?: string; protocol?: NetworkProtocol; servicePort?: number; networkNames?: string[]; } export enum NetworkProtocol { tcp = "tcp", udp = "udp", udp_tcp = "udp,tcp", } export interface DockerPullConfig { secret: string; } export interface UnreachableEnabled { inactiveAfterSeconds?: number; expungeAfterSeconds?: number; } export enum UnreachableDisabled { disabled = "disabled", } export enum Condition { Error = "Error", Failed = "Failed", Finished = "Finished", Killed = "Killed", Killing = "Killing", Running = "Running", Staging = "Staging", Starting = "Starting", Unreachable = "Unreachable", UnreachableInactive = "UnreachableInactive", Gone = "Gone", Dropped = "Dropped", Unknown = "Unknown", } export enum MesosTaskState { TASK_ERROR = "TASK_ERROR", TASK_FAILED = "TASK_FAILED", TASK_FINISHED = "TASK_FINISHED", TASK_KILLED = "TASK_KILLED", TASK_KILLING = "TASK_KILLING", TASK_RUNNING = "TASK_RUNNING", TASK_STAGING = "TASK_STAGING", TASK_STARTING = "TASK_STARTING", TASK_UNREACHABLE = "TASK_UNREACHABLE", TASK_GONE = "TASK_GONE", TASK_DROPPED = "TASK_DROPPED", } export interface Message { message: string; } export enum TaskLostBehavior { WAIT_FOREVER = "WAIT_FOREVER", RELAUNCH_AFTER_TIMEOUT = "RELAUNCH_AFTER_TIMEOUT", } export enum Goal { Running = "Running", Stopped = "Stopped", Decommissioned = "Decommissioned", } export enum ReadMode { RO = "RO", RW = "RW", } export interface App { id: string; acceptedResourceRoles?: string[]; args?: string[]; backoffFactor?: number; backoffSeconds?: number; cmd?: string; constraints?: string[][]; container?: Container; cpus?: number; dependencies?: string[]; disk?: number; env?: object; executor?: string; executorResources?: ExecutorResources; fetch?: Artifact[]; healthChecks?: AppHealthCheck[]; check?: AppCheck; instances?: number; labels?: object; maxLaunchDelaySeconds?: number; mem?: number; gpus?: number; ipAddress?: IpAddress; networks?: Network[]; ports?: number[]; portDefinitions?: PortDefinition[]; readinessChecks?: ReadinessCheck[]; residency?: AppResidency; requirePorts?: boolean; secrets?: object; taskKillGracePeriodSeconds?: number; upgradeStrategy?: UpgradeStrategy; uris?: string[]; user?: string; version?: Date; versionInfo?: VersionInfo; killSelection?: KillSelection; unreachableStrategy?: unknown; // TODO: implement unions; tty?: boolean; } export interface AppResidency { relaunchEscalationTimeoutSeconds: number; taskLostBehavior: TaskLostBehavior; } export interface VersionList { versions: Date[]; } export interface AppList { apps: App[]; } export interface UpgradeStrategy { maximumOverCapacity: number; minimumHealthCapacity: number; } export interface IpAddress { discovery?: IpDiscovery; groups?: string[]; labels?: object; networkName?: string; } export interface EnvVarSecret { secret: string; } export interface Lifecycle { killGracePeriodSeconds?: number; } export interface MesosExec { command: unknown; // TODO: implement unions; overrideEntrypoint?: boolean; } export interface Image { kind: ImageType; id: string; pullConfig?: DockerPullConfig; forcePull?: boolean; labels?: object; } export interface PodContainer { name: string; exec?: MesosExec; resources: Resources; endpoints?: Endpoint[]; image?: Image; environment?: object; user?: string; healthCheck?: HealthCheck; check?: Check; volumeMounts?: VolumeMount[]; artifacts?: Artifact[]; labels?: object; lifecycle?: Lifecycle; tty?: boolean; } export enum ImageType { DOCKER = "DOCKER", APPC = "APPC", } export interface Check { http?: HttpCheck; tcp?: TcpCheck; exec?: CommandCheck; intervalSeconds?: number; timeoutSeconds?: number; delaySeconds?: number; } export interface ApiPostEvent { clientIp: string; uri: string; appDefinition: App; eventType: string; timestamp: string; } export interface DeprecatedHistogram { count: number; min: number; max: number; p50: number; p75: number; p98: number; p99: number; p999: number; mean: number; tags: object; unit: unknown; // TODO: implement unions; } export interface DeprecatedGeneralMeasurement { name: string; label: string; } export interface DeprecatedCounter { count: number; tags: object; unit: unknown; // TODO: implement unions; } export interface MarathonInfo { name: string; version: string; buildref: string; elected: boolean; leader?: string; frameworkId?: string; marathon_config: MarathonConfig; zookeeper_config: ZooKeeperConfig; http_config: HttpConfig; } export interface ZooKeeperConfig { zk: string; zk_compression?: boolean; zk_compression_threshold?: number; zk_connection_timeout: number; zk_max_node_size?: number; zk_max_versions: number; zk_session_timeout: number; zk_timeout: number; } export interface LeaderInfo { leader: string; } export interface HttpConfig { http_port: number; https_port: number; } export interface MarathonConfig { access_control_allow_origin?: string[]; checkpoint?: boolean; decline_offer_duration?: number; default_network_name?: string; env_vars_prefix?: string; executor?: string; failover_timeout?: number; features: string[]; framework_name?: string; ha?: boolean; hostname?: string; launch_token?: number; launch_token_refresh_interval?: number; leader_proxy_connection_timeout_ms?: number; leader_proxy_read_timeout_ms?: number; local_port_max?: number; local_port_min?: number; master?: string; max_instances_per_offer?: number; mesos_bridge_name?: string; mesos_heartbeat_failure_threshold?: number; mesos_heartbeat_interval?: number; mesos_leader_ui_url?: string; mesos_role?: string; mesos_user?: string; min_revive_offers_interval?: number; offer_matching_timeout?: number; on_elected_prepare_timeout?: number; reconciliation_initial_delay?: number; reconciliation_interval?: number; revive_offers_for_new_apps?: boolean; revive_offers_repetitions?: number; scale_apps_initial_delay?: number; scale_apps_interval?: number; store_cache?: boolean; task_launch_confirm_timeout?: number; task_launch_timeout?: number; task_lost_expunge_initial_delay: number; task_lost_expunge_interval: number; task_reservation_timeout?: number; webui_url?: string; } export interface PersistentVolumeInfo { type?: PersistentVolumeType; size: number; maxSize?: number; profileName?: string; constraints?: string[][]; } export interface AppPersistentVolume { containerPath: string; persistent: PersistentVolumeInfo; mode: ReadMode; } export interface ExternalVolumeInfo { size?: number; name?: string; provider?: string; options?: object; } export interface AppHostVolume { containerPath: string; hostPath: string; mode: ReadMode; } export interface PodHostVolume { name: string; host: string; } export enum PersistentVolumeType { root = "root", path = "path", mount = "mount", } export interface PodPersistentVolume { name: string; persistent: PersistentVolumeInfo; } export interface AppSecretVolume { containerPath: string; secret: string; } export interface VolumeMount { name: string; mountPath: string; readOnly?: boolean; } export interface PodEphemeralVolume { name: string; } export interface PodSecretVolume { name: string; secret: string; } export interface AppExternalVolume { containerPath: string; external: ExternalVolumeInfo; mode: ReadMode; } export interface Group { id: string; apps?: App[]; pods?: Pod[]; groups?: Group[]; dependencies?: string[]; version?: Date; } export interface GroupInfo { id: string; apps?: App[]; pods?: PodStatus[]; groups?: GroupInfo[]; dependencies?: string[]; version?: Date; } export interface GroupUpdate { id: string; apps?: App[]; groups?: GroupUpdate[]; dependencies?: string[]; scaleBy?: number; version?: Date; } export interface RuntimeConfiguration { backup?: string; restore?: string; } export interface LocalVolumeId { runSpecId: string; containerPath: string; uuid: string; persistenceId: string; } export interface FixedPodScalingPolicy { kind: PodScalingPolicyType; instances: number; } export interface PodScalingPolicy { kind: PodScalingPolicyType; } export interface PodSchedulingBackoffStrategy { backoff?: number; backoffFactor?: number; maxLaunchDelay?: number; } export enum PodScalingPolicyType { fixed = "fixed", } export interface PodPlacementPolicy { constraints?: Constraint[]; acceptedResourceRoles?: string[]; } export interface PodSchedulingPolicy { backoff?: PodSchedulingBackoffStrategy; upgrade?: PodUpgradeStrategy; placement?: PodPlacementPolicy; killSelection?: KillSelection; unreachableStrategy?: unknown; // TODO: implement unions; } export interface PodUpgradeStrategy { minimumHealthCapacity?: number; maximumOverCapacity?: number; } export interface Artifact { uri: string; extract?: boolean; executable?: boolean; cache?: boolean; destPath?: string; } export interface NumberRange { begin: number; end: number; } export interface AgentAttribute { name: string; text?: string; scalar?: number; ranges?: NumberRange[]; set?: string[]; } export interface OfferResource { name: string; role: string; scalar?: number; ranges?: NumberRange[]; set?: string[]; } export interface Offer { id: string; hostname: string; agentId: string; resources: OfferResource[]; attributes: AgentAttribute[]; } export interface QueueObject { count: number; delay: QueueDelay; since: Date; processedOffersSummary: ProcessedOffersSummary; lastUnusedOffers?: UnusedOffer[]; } export interface QueueApp { count: number; delay: QueueDelay; since: Date; processedOffersSummary: ProcessedOffersSummary; lastUnusedOffers?: UnusedOffer[]; app: App; } export interface QueuePod { count: number; delay: QueueDelay; since: Date; processedOffersSummary: ProcessedOffersSummary; lastUnusedOffers?: UnusedOffer[]; pod: Pod; } export interface DeclinedOfferStep { reason: string; declined: number; processed: number; } export interface QueueDelay { timeLeftSeconds: number; overdue: boolean; } export interface UnusedOffer { offer: Offer; reason: string[]; timestamp: Date; } export interface Queue { queue?: unknown; // TODO: implement unions[]; } export interface ProcessedOffersSummary { processedOffersCount: number; unusedOffersCount: number; lastUnusedOfferAt?: Date; lastUsedOfferAt?: Date; rejectSummaryLastOffers?: DeclinedOfferStep[]; rejectSummaryLaunchAttempt?: DeclinedOfferStep[]; } export interface Histogram { count: number; min: number; mean: number; max: number; p50: number; p75: number; p95: number; p98: number; p99: number; p999: number; stddev: number; } export interface Counter { count: number; } export interface Timer { count: number; min: number; mean: number; max: number; p50: number; p75: number; p95: number; p98: number; p99: number; p999: number; stddev: number; m1_rate: number; m5_rate: number; m15_rate: number; mean_rate: number; duration_units: string; rate_units: string; } export interface Meter { count: number; m1_rate: number; m5_rate: number; m15_rate: number; mean_rate: number; units: string; } export interface NewMetrics { version: string; counters: object; gauges: object; histograms: object; meters: object; timers: object; } export interface Gauge { value: number; } export interface AppCheck { http?: AppHttpCheck; tcp?: AppTcpCheck; exec?: CommandCheck; intervalSeconds?: number; timeoutSeconds?: number; delaySeconds?: number; } export interface CommandCheckStatus { exitCode: number; } export interface AppTcpCheck { portIndex?: number; } export interface CheckStatus { http?: HttpCheckStatus; tcp?: TCPCheckStatus; exec?: CommandCheckStatus; } export interface TcpCheck { endpoint: string; } export interface HttpCheckStatus { statusCode: number; } export interface HttpCheck { endpoint: string; path?: string; scheme?: HttpScheme; } export interface AppHttpCheck { portIndex?: number; path?: string; scheme?: HttpScheme; } export interface TCPCheckStatus { succeeded: boolean; } export interface IpDiscoveryPort { number?: number; name: string; protocol?: NetworkProtocol; labels?: object; } export interface PortDefinition { port?: number; labels?: object; name?: string; protocol?: NetworkProtocol; } export enum NetworkMode { container = "container", container_bridge = "container/bridge", host = "host", } export interface Endpoint { name: string; containerPort?: number; hostPort?: number; protocol?: string[]; labels?: object; networkNames?: string[]; } export interface Network { name?: string; mode?: NetworkMode; labels?: object; } export interface IpDiscovery { ports?: IpDiscoveryPort[]; } export interface DeploymentResult { deploymentId: string; version: Date; } export interface DeploymentStep { actions: DeploymentAction[]; } export interface DeploymentAction { action: DeploymentActionName; app?: string; pod?: string; } export enum DeploymentActionName { StartApplication = "StartApplication", StopApplication = "StopApplication", ScaleApplication = "ScaleApplication", RestartApplication = "RestartApplication", StartPod = "StartPod", StopPod = "StopPod", ScalePod = "ScalePod", RestartPod = "RestartPod", ResolveArtifacts = "ResolveArtifacts", }
the_stack
import { defaultModelAssessmentContext, ErrorCohort, ModelAssessmentContext } from "@responsible-ai/core-ui"; import { localization } from "@responsible-ai/localization"; import { Dropdown, ChoiceGroup, Stack, IDropdownOption, Panel, PrimaryButton, DefaultButton, IChoiceGroupOption } from "office-ui-fabric-react"; import React from "react"; import { modelOverviewChartStyles } from "./ModelOverviewChart.styles"; interface IChartConfigurationFlyoutProps { isOpen: boolean; onDismissFlyout: () => void; datasetCohorts: ErrorCohort[]; featureBasedCohorts: ErrorCohort[]; selectedDatasetCohorts?: number[]; selectedFeatureBasedCohorts?: number[]; updateCohortSelection: ( selectedDatasetCohorts: number[], selectedFeatureBasedCohorts: number[], datasetCohortChartIsSelected: boolean ) => void; datasetCohortViewIsSelected: boolean; } interface IChartConfigurationFlyoutState { newlySelectedDatasetCohorts: number[]; newlySelectedFeatureBasedCohorts: number[]; datasetCohortViewIsNewlySelected: boolean; } const selectAllOptionKey = "selectAll"; export class ChartConfigurationFlyout extends React.Component< IChartConfigurationFlyoutProps, IChartConfigurationFlyoutState > { public static contextType = ModelAssessmentContext; public context: React.ContextType<typeof ModelAssessmentContext> = defaultModelAssessmentContext; private datasetCohortsChoiceGroupOption = "datasetCohorts"; private featureBasedCohortsChoiceGroupOption = "featureBasedCohorts"; constructor(props: IChartConfigurationFlyoutProps) { super(props); this.state = { datasetCohortViewIsNewlySelected: this.props.datasetCohortViewIsSelected, newlySelectedDatasetCohorts: this.props.selectedDatasetCohorts ?? this.props.datasetCohorts.map((_, index) => index), newlySelectedFeatureBasedCohorts: this.props.selectedFeatureBasedCohorts ?? this.props.featureBasedCohorts.map((_, index) => index) }; } public componentDidUpdate(prevProps: IChartConfigurationFlyoutProps) { // reset feature-based cohort selection if the underlying feature-based cohorts changed let newlySelectedFeatureBasedCohorts = this.state.newlySelectedFeatureBasedCohorts; const featureBasedCohortsChanged = prevProps.featureBasedCohorts.length !== this.props.featureBasedCohorts.length || prevProps.featureBasedCohorts.some( (errorCohort, index) => errorCohort.cohort.name !== this.props.featureBasedCohorts[index].cohort.name ); const selectedFeatureBasedCohortsChanged = (prevProps.selectedFeatureBasedCohorts === undefined && this.props.selectedFeatureBasedCohorts !== undefined) || (prevProps.selectedFeatureBasedCohorts && this.props.selectedFeatureBasedCohorts && (this.props.selectedFeatureBasedCohorts.length !== prevProps.selectedFeatureBasedCohorts.length || prevProps.selectedFeatureBasedCohorts.some( (num, index) => num !== this.props.selectedFeatureBasedCohorts?.[index] ))); if (featureBasedCohortsChanged || selectedFeatureBasedCohortsChanged) { newlySelectedFeatureBasedCohorts = this.props.featureBasedCohorts.map( (_, index) => index ); } let datasetCohortViewIsSelected = this.state.datasetCohortViewIsNewlySelected; if ( prevProps.datasetCohortViewIsSelected !== this.props.datasetCohortViewIsSelected ) { datasetCohortViewIsSelected = this.props.datasetCohortViewIsSelected; } // update state only if there are changes if ( this.state.datasetCohortViewIsNewlySelected !== datasetCohortViewIsSelected || this.state.newlySelectedFeatureBasedCohorts.length !== newlySelectedFeatureBasedCohorts.length || this.state.newlySelectedFeatureBasedCohorts.some( (num, index) => num !== newlySelectedFeatureBasedCohorts[index] ) ) this.setState({ ...this.state, datasetCohortViewIsNewlySelected: datasetCohortViewIsSelected, newlySelectedFeatureBasedCohorts }); } public render(): React.ReactNode { const classNames = modelOverviewChartStyles(); const selectAllOption = { key: selectAllOptionKey, text: localization.ModelAssessment.ModelOverview.selectAllCohortsOption }; const datasetCohortOptions = this.getIndexAndNames( this.props.datasetCohorts ); const featureBasedCohortOptions = this.getIndexAndNames( this.props.featureBasedCohorts ); const datasetCohortDropdownSelectedKeys: string[] = this.state.newlySelectedDatasetCohorts.map((n) => n.toString()); if ( this.state.newlySelectedDatasetCohorts.length > 0 && this.state.newlySelectedDatasetCohorts.length === this.props.datasetCohorts.length ) { datasetCohortDropdownSelectedKeys.push(selectAllOptionKey); } const featureBasedCohortDropdownSelectedKeys: string[] = this.state.newlySelectedFeatureBasedCohorts.map((n) => n.toString()); if ( this.state.newlySelectedFeatureBasedCohorts.length > 0 && this.state.newlySelectedFeatureBasedCohorts.length === this.props.featureBasedCohorts.length ) { featureBasedCohortDropdownSelectedKeys.push(selectAllOptionKey); } const choiceGroupOptions = [ { key: this.datasetCohortsChoiceGroupOption, text: localization.ModelAssessment.ModelOverview .dataCohortsChartSelectionHeader }, { disabled: this.props.featureBasedCohorts.length === 0, key: this.featureBasedCohortsChoiceGroupOption, text: localization.ModelAssessment.ModelOverview .featureBasedCohortsChartSelectionHeader } ]; const noCohortSelected = this.noCohortIsSelected(); return ( <Panel isOpen={this.props.isOpen} closeButtonAriaLabel="Close" onDismiss={this.props.onDismissFlyout} onRenderFooterContent={this.onRenderFooterContent} isFooterAtBottom > <Stack tokens={{ childrenGap: "10px" }}> <ChoiceGroup options={choiceGroupOptions} onChange={this.onChoiceGroupChange} selectedKey={ this.state.datasetCohortViewIsNewlySelected ? this.datasetCohortsChoiceGroupOption : this.featureBasedCohortsChoiceGroupOption } /> <Dropdown className={classNames.chartConfigDropdown} label={ localization.ModelAssessment.ModelOverview .dataCohortsChartSelectionHeader } multiSelect options={[selectAllOption, ...datasetCohortOptions]} onChange={this.onChartDatasetCohortOptionSelectionChange} selectedKeys={datasetCohortDropdownSelectedKeys} errorMessage={ noCohortSelected && this.state.datasetCohortViewIsNewlySelected ? localization.ModelAssessment.ModelOverview .chartCohortSelectionPlaceholder : undefined } placeholder={ localization.ModelAssessment.ModelOverview .chartConfigDatasetCohortSelectionPlaceholder } disabled={!this.state.datasetCohortViewIsNewlySelected} /> {this.props.featureBasedCohorts.length > 0 && ( <Dropdown className={classNames.chartConfigDropdown} label={ localization.ModelAssessment.ModelOverview .featureBasedCohortsChartSelectionHeader } multiSelect options={[selectAllOption, ...featureBasedCohortOptions]} onChange={this.onChartFeatureBasedCohortOptionSelectionChange} selectedKeys={featureBasedCohortDropdownSelectedKeys} errorMessage={ noCohortSelected && !this.state.datasetCohortViewIsNewlySelected ? localization.ModelAssessment.ModelOverview .chartCohortSelectionPlaceholder : undefined } placeholder={ localization.ModelAssessment.ModelOverview .chartConfigFeatureBasedCohortSelectionPlaceholder } disabled={this.state.datasetCohortViewIsNewlySelected} /> )} </Stack> </Panel> ); } private onRenderFooterContent = () => { return ( <Stack horizontal tokens={{ childrenGap: "10px" }}> <PrimaryButton onClick={this.onConfirm} text={localization.ModelAssessment.ModelOverview.chartConfigConfirm} disabled={this.noCohortIsSelected()} /> <DefaultButton onClick={this.props.onDismissFlyout} text={localization.ModelAssessment.ModelOverview.chartConfigCancel} /> </Stack> ); }; private noCohortIsSelected = () => { return ( (this.state.datasetCohortViewIsNewlySelected && this.state.newlySelectedDatasetCohorts.length === 0) || (!this.state.datasetCohortViewIsNewlySelected && this.state.newlySelectedFeatureBasedCohorts.length === 0) ); }; private onChoiceGroupChange = ( _ev?: React.FormEvent<HTMLElement | HTMLInputElement> | undefined, option?: IChoiceGroupOption | undefined ): void => { if (option) { if (option.key === this.datasetCohortsChoiceGroupOption) { this.setState({ datasetCohortViewIsNewlySelected: true }); } if (option.key === this.featureBasedCohortsChoiceGroupOption) { this.setState({ datasetCohortViewIsNewlySelected: false }); } } }; private onConfirm = () => { this.props.updateCohortSelection( this.state.newlySelectedDatasetCohorts, this.state.newlySelectedFeatureBasedCohorts, this.state.datasetCohortViewIsNewlySelected ); }; private onChartDatasetCohortOptionSelectionChange = ( _: React.FormEvent<HTMLDivElement>, item?: IDropdownOption ): void => { if (item) { this.setState({ newlySelectedDatasetCohorts: this.makeChartCohortOptionSelectionChange( this.state.newlySelectedDatasetCohorts, this.props.datasetCohorts.map((_cohort, index) => index), item ) }); } }; private onChartFeatureBasedCohortOptionSelectionChange = ( _: React.FormEvent<HTMLDivElement>, item?: IDropdownOption ): void => { if (item) { this.setState({ newlySelectedFeatureBasedCohorts: this.makeChartCohortOptionSelectionChange( this.state.newlySelectedFeatureBasedCohorts, this.props.featureBasedCohorts.map((_cohort, index) => index), item ) }); } }; private makeChartCohortOptionSelectionChange = ( currentlySelected: number[], allItems: number[], item: IDropdownOption ): number[] => { if (item.key === selectAllOptionKey) { // if all items were selected before then unselect all now // if at least some items were not selected before then select all now if (currentlySelected.length !== allItems.length) { return allItems; } return []; } const key = Number(item.key); if (item.selected && !currentlySelected.includes(key)) { // update with newly selected item return currentlySelected.concat([key]); } else if (!item.selected && currentlySelected.includes(key)) { // update by removing the unselected item return currentlySelected.filter((idx) => idx !== key); } return currentlySelected; }; private getIndexAndNames(errorCohorts: ErrorCohort[]) { return errorCohorts.map((cohort, index) => { return { key: index.toString(), text: cohort.cohort.name }; }); } }
the_stack