text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { async, ComponentFixture, fakeAsync, flushMicrotasks, TestBed } from '@angular/core/testing';
import { InteractiveImageClickInput } from './oppia-interactive-image-click-input.component';
import { InteractionAttributesExtractorService } from 'interactions/interaction-attributes-extractor.service';
import { ImageClickAnswer } from 'interactions/answer-defs';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ContextService } from 'services/context.service';
import { ImagePreloaderService } from 'pages/exploration-player-page/services/image-preloader.service';
import { EventEmitter } from '@angular/core';
import { PlayerPositionService } from 'pages/exploration-player-page/services/player-position.service';
import { CurrentInteractionService } from 'pages/exploration-player-page/services/current-interaction.service';
describe('InteractiveImageClickInput', () => {
let fixture: ComponentFixture<InteractiveImageClickInput>;
let contextService: ContextService;
let component: InteractiveImageClickInput;
let imagePreloaderService: ImagePreloaderService;
let currentInteractionService: CurrentInteractionService;
let mockNewCardAvailableEmitter = new EventEmitter();
let playerPositionService: PlayerPositionService;
let imageUrl = '/assetsdevhandler/exploration/expId/assets/image/' +
'img_20210616_110856_oxqveyuhr3_height_778_width_441.svg';
class mockInteractionAttributesExtractorService {
getValuesFromAttributes(interactionId, attributes) {
return {
imageAndRegions: {
value: JSON.parse(attributes.imageAndRegionsWithValue)
},
highlightRegionsOnHover: {
value: JSON.parse(attributes.highlightRegionsOnHoverWithValue)
}
};
}
}
let mockCurrentInteractionService = {
onSubmit: (answer, rulesService) => {
expect(answer).toEqual({ clickPosition: [1, 2], clickedRegions: [] });
},
registerCurrentInteraction: (submitAnswer, validateExpressionFn) => {}
};
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [InteractiveImageClickInput],
providers: [
{
provide: InteractionAttributesExtractorService,
useClass: mockInteractionAttributesExtractorService
},
{
provide: CurrentInteractionService,
useValue: mockCurrentInteractionService
}
]
}).compileComponents();
}));
beforeEach(() => {
imagePreloaderService = TestBed.get(ImagePreloaderService);
contextService = TestBed.inject(ContextService);
currentInteractionService = TestBed.inject(CurrentInteractionService);
playerPositionService = TestBed.get(PlayerPositionService);
fixture = TestBed.createComponent(InteractiveImageClickInput);
component = fixture.componentInstance;
component.imageAndRegionsWithValue = '{' +
' "imagePath": "img_20210616_110856_oxqveyuhr3_height_778_width_' +
'441.svg",' +
' "labeledRegions": [' +
' {' +
' "label": "Region1",' +
' "region": {' +
' "regionType": "Rectangle",' +
' "area": [' +
' [' +
' 0.3557347670250896,' +
' 0.25571807421685533' +
' ],' +
' [' +
' 0.6693548387096774,' +
' 0.4274671235666757' +
' ]' +
' ]' +
' }' +
' },' +
' {' +
' "label": "Region2",' +
' "region": {' +
' "regionType": "Rectangle",' +
' "area": [' +
' [' +
' 0.39695340501792115,' +
' 0.5301100465508879' +
' ],' +
' [' +
' 0.8431899641577061,' +
' 0.7181193609279102' +
' ]' +
' ]' +
' }' +
' }' +
' ]' +
'}';
component.highlightRegionsOnHoverWithValue = 'true';
component.lastAnswer = {
clickPosition: [1, 2],
clickedRegions: ['region1']
} as ImageClickAnswer;
spyOn(contextService, 'getEntityType').and.returnValue('exploration');
spyOn(contextService, 'getEntityId').and.returnValue('expId');
});
afterEach(() => {
component.ngOnDestroy();
});
it('should initialize when interaction is added in the exploration' +
' editor', () => {
spyOn(component, 'loadImage');
spyOn(component, 'updateCurrentlyHoveredRegions');
spyOn(currentInteractionService, 'registerCurrentInteraction');
component.ngOnInit();
expect(component.imageAndRegions).toEqual({
imagePath: 'img_20210616_110856_oxqveyuhr3_height_778_width_441.svg',
labeledRegions: [
{
label: 'Region1',
region: {
regionType: 'Rectangle',
area: [
[
0.3557347670250896,
0.25571807421685533
],
[
0.6693548387096774,
0.4274671235666757
]
]
}
},
{
label: 'Region2',
region: {
regionType: 'Rectangle',
area: [
[
0.39695340501792115,
0.5301100465508879
],
[
0.8431899641577061,
0.7181193609279102
]
]
}
}
]
});
expect(component.highlightRegionsOnHover).toBe(true);
expect(component.filepath)
.toBe('img_20210616_110856_oxqveyuhr3_height_778_width_441.svg');
expect(component.loadingIndicatorUrl)
.toBe('/assets/images/activity/loadingIndicator.gif');
expect(component.isLoadingIndicatorShown).toBe(false);
expect(component.isTryAgainShown).toBe(false);
expect(component.dimensions).toEqual({height: 778, width: 441});
expect(component.imageContainerStyle)
.toEqual({height: '778px', width: '441px'});
expect(component.interactionIsActive).toBe(false);
expect(component.currentlyHoveredRegions).toEqual([]);
expect(component.imageUrl).toBe(imageUrl);
expect(component.mouseX).toBe(1);
expect(component.mouseY).toBe(2);
expect(component.loadImage).not.toHaveBeenCalled();
expect(component.updateCurrentlyHoveredRegions).toHaveBeenCalled();
expect(currentInteractionService.registerCurrentInteraction)
.toHaveBeenCalledWith(null, null);
});
it('should initialize when interaction is played in the exploration' +
' player', () => {
spyOn(imagePreloaderService, 'inExplorationPlayer').and.returnValue(true);
spyOn(component, 'loadImage');
spyOn(component, 'updateCurrentlyHoveredRegions');
spyOn(currentInteractionService, 'registerCurrentInteraction');
component.ngOnInit();
expect(component.imageAndRegions).toEqual({
imagePath: 'img_20210616_110856_oxqveyuhr3_height_778_width_441.svg',
labeledRegions: [
{
label: 'Region1',
region: {
regionType: 'Rectangle',
area: [
[
0.3557347670250896,
0.25571807421685533
],
[
0.6693548387096774,
0.4274671235666757
]
]
}
},
{
label: 'Region2',
region: {
regionType: 'Rectangle',
area: [
[
0.39695340501792115,
0.5301100465508879
],
[
0.8431899641577061,
0.7181193609279102
]
]
}
}
]
});
expect(component.highlightRegionsOnHover).toBe(true);
expect(component.filepath)
.toBe('img_20210616_110856_oxqveyuhr3_height_778_width_441.svg');
expect(component.loadingIndicatorUrl)
.toBe('/assets/images/activity/loadingIndicator.gif');
expect(component.isLoadingIndicatorShown).toBe(true);
expect(component.isTryAgainShown).toBe(false);
expect(component.dimensions).toEqual({height: 778, width: 441});
expect(component.imageContainerStyle).toEqual({height: '778px'});
expect(component.loadingIndicatorStyle)
.toEqual({height: '120px', width: '120px'});
expect(component.interactionIsActive).toBe(false);
expect(component.currentlyHoveredRegions).toEqual([]);
expect(component.imageUrl).toBe('');
expect(component.mouseX).toBe(1);
expect(component.mouseY).toBe(2);
expect(component.loadImage).toHaveBeenCalled();
expect(component.updateCurrentlyHoveredRegions).toHaveBeenCalled();
expect(currentInteractionService.registerCurrentInteraction)
.toHaveBeenCalledWith(null, null);
});
it('should initialize when interaction is played in the exploration' +
' player', () => {
spyOnProperty(playerPositionService, 'onNewCardAvailable').and.returnValue(
mockNewCardAvailableEmitter);
component.ngOnInit();
component.lastAnswer = null;
mockNewCardAvailableEmitter.emit();
expect(component.interactionIsActive).toBe(false);
expect(component.lastAnswer).toEqual({
clickPosition: [1, 2],
clickedRegions: []
});
});
it('should load image when component is initialised', fakeAsync(() => {
spyOn(imagePreloaderService, 'getImageUrlAsync').and
.returnValue(Promise.resolve(imageUrl));
component.filepath =
'img_20210616_110856_oxqveyuhr3_height_778_width_441.svg';
component.isTryAgainShown = true;
component.isLoadingIndicatorShown = true;
component.loadImage();
flushMicrotasks();
expect(component.isTryAgainShown).toBe(false);
expect(component.isLoadingIndicatorShown).toBe(false);
expect(component.imageUrl).toBe(imageUrl);
}));
it('should not load image when image url is not returned', fakeAsync(() => {
spyOn(imagePreloaderService, 'getImageUrlAsync').and
.returnValue(Promise.reject('failure'));
component.filepath =
'img_20210616_110856_oxqveyuhr3_height_778_width_441.svg';
component.isTryAgainShown = false;
component.isLoadingIndicatorShown = true;
component.loadImage();
flushMicrotasks();
expect(component.isTryAgainShown).toBe(true);
expect(component.isLoadingIndicatorShown).toBe(false);
}));
it('should not highlight last answer if interaction is active' +
' in exploration player', () => {
spyOn(component, 'updateCurrentlyHoveredRegions');
component.lastAnswer = null;
component.ngOnInit();
expect(component.interactionIsActive).toBe(true);
expect(component.mouseX).toBe(0);
expect(component.mouseY).toBe(0);
expect(component.updateCurrentlyHoveredRegions).not.toHaveBeenCalled();
});
it('should highlight last answer if interaction is not active' +
' in exploration player', () => {
spyOn(component, 'updateCurrentlyHoveredRegions').and.callThrough();
component.lastAnswer.clickPosition = [0.4, 0.4];
component.ngOnInit();
expect(component.interactionIsActive).toBe(false);
expect(component.mouseX).toBe(0.4);
expect(component.mouseY).toBe(0.4);
expect(component.updateCurrentlyHoveredRegions).toHaveBeenCalled();
expect(component.currentlyHoveredRegions).toEqual(['Region1']);
});
it('should return \'inline\' if mouse is over the region', () => {
component.currentlyHoveredRegions = ['Region1'];
expect(component.getRegionDisplay('Region1')).toBe('inline');
});
it('should return \'none\' if mouse is not over the region', () => {
component.currentlyHoveredRegions = ['Region1'];
expect(component.getRegionDisplay('No_Region')).toBe('none');
});
it('should return dot location when called', () => {
spyOn(Element.prototype, 'querySelectorAll').and.callFake(
jasmine.createSpy('querySelectorAll').and
.returnValue([{
parentElement: {
getBoundingClientRect: () => {
return new DOMRect(300, 300, 300, 300);
}
},
getBoundingClientRect: () => {
return new DOMRect(200, 200, 200, 200);
},
width: 200,
height: 200
}]));
component.ngOnInit();
expect(component.getDotLocation()).toEqual({left: 95, top: 295});
});
it('should check if mouse is over region when mouse moves', () => {
spyOn(Element.prototype, 'querySelectorAll').and.callFake(
jasmine.createSpy('querySelectorAll').and
.returnValue([{
parentElement: {
getBoundingClientRect: () => {
return new DOMRect(300, 300, 300, 300);
}
},
getBoundingClientRect: () => {
return new DOMRect(200, 200, 200, 200);
},
width: 200,
height: 200
}]));
spyOn(component, 'updateCurrentlyHoveredRegions').and.callThrough();
spyOnProperty(MouseEvent.prototype, 'pageX', 'get').and.returnValue(290);
spyOnProperty(MouseEvent.prototype, 'pageY', 'get').and.returnValue(260);
let evt = new MouseEvent('Mousemove');
component.lastAnswer = null;
component.ngOnInit();
expect(component.interactionIsActive).toBe(true);
expect(component.mouseX).toBe(0);
expect(component.mouseY).toBe(0);
expect(component.currentlyHoveredRegions).toEqual([]);
component.onMousemoveImage(evt);
// The mouseX and mouseY variables must be updated only
// when the interaction is active.
expect(component.interactionIsActive).toBe(true);
expect(component.mouseX).toBe(0.45);
expect(component.mouseY).toBe(0.3);
expect(component.currentlyHoveredRegions).toEqual(['Region1']);
});
it('should not check if mouse is over region when interaction is not' +
' active', () => {
spyOn(component, 'updateCurrentlyHoveredRegions').and.callThrough();
spyOnProperty(MouseEvent.prototype, 'pageX', 'get').and.returnValue(290);
spyOnProperty(MouseEvent.prototype, 'pageY', 'get').and.returnValue(260);
let evt = new MouseEvent('Mousemove');
component.lastAnswer.clickPosition = [0.4, 0.4];
component.ngOnInit();
expect(component.interactionIsActive).toBe(false);
expect(component.mouseX).toBe(0.4);
expect(component.mouseY).toBe(0.4);
expect(component.currentlyHoveredRegions).toEqual(['Region1']);
component.onMousemoveImage(evt);
// The mouseX and mouseY variables must be updated only
// when the interaction is active.
expect(component.interactionIsActive).toBe(false);
expect(component.mouseX).toBe(0.4);
expect(component.mouseY).toBe(0.4);
expect(component.currentlyHoveredRegions).toEqual(['Region1']);
});
it('should not check if mouse is over region when interaction is not' +
' active', () => {
spyOn(Element.prototype, 'querySelectorAll').and.callFake(
jasmine.createSpy('querySelectorAll').and
.returnValue([{
parentElement: {
getBoundingClientRect: () => {
return new DOMRect(300, 300, 300, 300);
}
},
getBoundingClientRect: () => {
return new DOMRect(200, 200, 200, 200);
},
width: 200,
height: 200
}]));
spyOn(component, 'updateCurrentlyHoveredRegions').and.callThrough();
var evt = document.createEvent('MouseEvent');
evt.initMouseEvent(
'click', true, true, window, 1,
800, 600, 290, 260, false, false, false, false, 0, null
);
component.ngOnInit();
expect(component.getRegionDimensions(1)).toEqual(
{
left: -20.609318996415766,
top: 6.02200931017758,
width: 89.24731182795699,
height: 37.60186287540446
});
});
it('should submit when image is clicked', () => {
spyOn(currentInteractionService, 'onSubmit').and.callThrough();
component.ngOnInit();
component.onClickImage();
expect(currentInteractionService.onSubmit)
.toHaveBeenCalledWith(
{ clickPosition: [1, 2], clickedRegions: [] }, jasmine.any(Object)
);
});
it('should show region if in exploration editor', () => {
spyOn(contextService, 'getEditorTabContext').and.returnValue('editor');
expect(component.getDotDisplay()).toBe('none');
});
it('should not show region if not in exploration editor', () => {
spyOn(contextService, 'getEditorTabContext').and.returnValue('preview');
expect(component.getDotDisplay()).toBe('inline');
});
}); | the_stack |
GDevelop - Physics Behavior Extension
Copyright (c) 2013-2016 Florian Rival (Florian.Rival@gmail.com)
*/
namespace gdjs {
/**
* Manage the common objects shared by objects having a
* physics behavior.
*/
export class PhysicsSharedData {
stepped: boolean = false;
totalTime: float = 0;
fixedTimeStep: any;
scaleX: any;
scaleY: any;
invScaleX: any;
invScaleY: any;
world: any;
staticBody: any;
//...and prepare contact listeners
contactListener: any;
constructor(runtimeScene, sharedData) {
this.fixedTimeStep = 1 / 60;
this.scaleX = sharedData.scaleX;
this.scaleY = sharedData.scaleY;
this.invScaleX = 1 / this.scaleX;
this.invScaleY = 1 / this.scaleY;
//Setup world...
const b2World = Box2D.b2World;
const b2Vec2 = Box2D.b2Vec2;
this.world = new b2World(
new b2Vec2(sharedData.gravityX, -sharedData.gravityY),
true
);
this.world.SetAutoClearForces(false);
this.staticBody = this.world.CreateBody(new Box2D.b2BodyDef());
this.contactListener = new Box2D.JSContactListener();
this.contactListener.BeginContact = function (contactPtr) {
const contact = Box2D.wrapPointer(contactPtr, Box2D.b2Contact);
if (
contact.GetFixtureA().GetBody() == null ||
contact.GetFixtureB().GetBody() == null
) {
return;
}
const behaviorA = contact.GetFixtureA().GetBody()
.gdjsAssociatedBehavior,
behaviorB = contact.GetFixtureB().GetBody().gdjsAssociatedBehavior;
behaviorA.currentContacts.push(behaviorB);
behaviorB.currentContacts.push(behaviorA);
};
this.contactListener.EndContact = function (contactPtr) {
const contact = Box2D.wrapPointer(contactPtr, Box2D.b2Contact);
if (
contact.GetFixtureA().GetBody() == null ||
contact.GetFixtureB().GetBody() == null
) {
return;
}
if (
contact.GetFixtureA().GetBody() === null ||
contact.GetFixtureB().GetBody() === null
) {
return;
}
const behaviorA = contact.GetFixtureA().GetBody()
.gdjsAssociatedBehavior,
behaviorB = contact.GetFixtureB().GetBody().gdjsAssociatedBehavior;
let i = behaviorA.currentContacts.indexOf(behaviorB);
if (i !== -1) {
behaviorA.currentContacts.splice(i, 1);
}
i = behaviorB.currentContacts.indexOf(behaviorA);
if (i !== -1) {
behaviorB.currentContacts.splice(i, 1);
}
};
this.contactListener.PreSolve = function () {};
this.contactListener.PostSolve = function () {};
this.world.SetContactListener(this.contactListener);
}
/**
* Get the shared data for a scene.
*/
static getSharedData(runtimeScene, name) {
if (!runtimeScene.physicsSharedData) {
//Create the shared data if necessary.
const initialData = runtimeScene.getInitialSharedDataForBehavior(name);
runtimeScene.physicsSharedData = new gdjs.PhysicsSharedData(
runtimeScene,
initialData
);
}
return runtimeScene.physicsSharedData;
}
step(dt) {
this.totalTime += dt;
if (this.totalTime > this.fixedTimeStep) {
let numberOfSteps = Math.floor(this.totalTime / this.fixedTimeStep);
this.totalTime -= numberOfSteps * this.fixedTimeStep;
if (numberOfSteps > 5) {
numberOfSteps = 5;
}
//Process 5 steps at max.
for (let a = 0; a < numberOfSteps; a++) {
this.world.Step(this.fixedTimeStep, 6, 10);
}
this.world.ClearForces();
}
this.stepped = true;
}
}
gdjs.registerRuntimeSceneUnloadedCallback(function (runtimeScene) {
//Callback that destroys the box2d.js world of PhysicsSharedData shared data of the scene
if (runtimeScene.physicsSharedData) {
Box2D.destroy(runtimeScene.physicsSharedData.world);
}
});
/**
* Allows objects to be moved in a realistic way thanks to a physics engine (Box2D).
*/
export class PhysicsRuntimeBehavior extends gdjs.RuntimeBehavior {
_box2DBody: any = null;
_dynamic: any;
_objectOldWidth: float = 0;
_objectOldHeight: float = 0;
_objectOldX: number = 0;
_objectOldY: number = 0;
_objectOldAngle: float = 0;
_angularDamping: any;
_linearDamping: any;
_isBullet: boolean;
_fixedRotation: float;
_massDensity: any;
_averageFriction: any;
_averageRestitution: any;
_shapeType: any;
currentContacts: any = [];
_sharedData: any;
//Temporary objects used to avoid creating garbage:
_tempb2Vec2: any;
constructor(runtimeScene, behaviorData, owner) {
super(runtimeScene, behaviorData, owner);
this._dynamic = behaviorData.dynamic;
this._angularDamping = behaviorData.angularDamping;
this._linearDamping = behaviorData.linearDamping;
this._isBullet = behaviorData.isBullet;
this._fixedRotation = behaviorData.fixedRotation;
this._massDensity = behaviorData.massDensity;
this._averageFriction = behaviorData.averageFriction;
this._averageRestitution = behaviorData.averageRestitution;
this._shapeType = behaviorData.shapeType;
if (this.currentContacts !== undefined) {
this.currentContacts.length = 0;
} else {
}
this._sharedData = PhysicsSharedData.getSharedData(
runtimeScene,
behaviorData.name
);
//Do not create body now: the object is not fully created.
this._tempb2Vec2 = new Box2D.b2Vec2();
}
//See b2Vec2 method
updateFromBehaviorData(oldBehaviorData, newBehaviorData): boolean {
if (oldBehaviorData.dynamic !== newBehaviorData.dynamic) {
if (newBehaviorData.dynamic) {
this.setDynamic();
} else {
this.setStatic();
}
}
if (oldBehaviorData.angularDamping !== newBehaviorData.angularDamping) {
this.setAngularDamping(newBehaviorData.angularDamping);
}
if (oldBehaviorData.linearDamping !== newBehaviorData.linearDamping) {
this.setLinearDamping(newBehaviorData.linearDamping);
}
if (oldBehaviorData.isBullet !== newBehaviorData.isBullet) {
if (newBehaviorData.isBullet) {
this.setAsBullet();
} else {
this.dontSetAsBullet();
}
}
if (oldBehaviorData.fixedRotation !== newBehaviorData.fixedRotation) {
if (newBehaviorData.fixedRotation) {
this.setFixedRotation();
} else {
this.setFreeRotation();
}
}
// TODO: make these properties updatable.
if (oldBehaviorData.massDensity !== newBehaviorData.massDensity) {
return false;
}
if (oldBehaviorData.averageFriction !== newBehaviorData.averageFriction) {
return false;
}
if (
oldBehaviorData.averageRestitution !==
newBehaviorData.averageRestitution
) {
return false;
}
if (oldBehaviorData.shapeType !== newBehaviorData.shapeType) {
return false;
}
return true;
}
onDeActivate() {
if (this._box2DBody !== null) {
this._sharedData.world.DestroyBody(this._box2DBody);
this._box2DBody = null;
}
}
onDestroy() {
this.onDeActivate();
}
/**
* Return a Box2D.b2Vec2 with the specified coordinates.
* Should be used instead of doing 'new Box2D.b2Vec2(x, y)'.
*/
b2Vec2(x, y) {
this._tempb2Vec2.set_x(x);
this._tempb2Vec2.set_y(y);
return this._tempb2Vec2;
}
createBody() {
//Create body from object
const bodyDef = new Box2D.b2BodyDef();
bodyDef.set_type(
this._dynamic ? Box2D.b2_dynamicBody : Box2D.b2_staticBody
);
bodyDef.set_position(
this.b2Vec2(
(this.owner.getDrawableX() + this.owner.getWidth() / 2) *
this._sharedData.invScaleX,
-(this.owner.getDrawableY() + this.owner.getHeight() / 2) *
this._sharedData.invScaleY
)
);
bodyDef.set_angle(-gdjs.toRad(this.owner.getAngle()));
bodyDef.set_angularDamping(
this._angularDamping > 0 ? this._angularDamping : 0
);
bodyDef.set_linearDamping(
this._linearDamping > 0 ? this._linearDamping : 0
);
bodyDef.set_bullet(this._isBullet);
bodyDef.set_fixedRotation(this._fixedRotation);
this._box2DBody = this._sharedData.world.CreateBody(bodyDef);
this._box2DBody.gdjsAssociatedBehavior = this;
//We do not use SetUserData which only accept integers.
//Setup the fixture
let fixDef = null;
/*else if ( this._shapeType === "CustomPolygon" ) {
//TODO
}*/
if (this._shapeType === 'Circle') {
const circle = new Box2D.b2CircleShape();
circle.set_m_radius(
(this.owner.getWidth() * this._sharedData.invScaleX +
this.owner.getHeight() * this._sharedData.invScaleY) /
4
);
if (circle.get_m_radius() <= 0) {
circle.set_m_radius(1);
}
fixDef = new Box2D.b2FixtureDef();
fixDef.set_shape(circle);
} else {
//Box
const box = new Box2D.b2PolygonShape();
box.SetAsBox(
((this.owner.getWidth() > 0 ? this.owner.getWidth() : 1) *
this._sharedData.invScaleX) /
2,
((this.owner.getHeight() > 0 ? this.owner.getHeight() : 1) *
this._sharedData.invScaleY) /
2
);
fixDef = new Box2D.b2FixtureDef();
fixDef.set_shape(box);
}
fixDef.set_density(this._massDensity);
fixDef.set_friction(this._averageFriction);
fixDef.set_restitution(this._averageRestitution);
this._box2DBody.CreateFixture(fixDef);
this._objectOldWidth = this.owner.getWidth();
this._objectOldHeight = this.owner.getHeight();
}
doStepPreEvents(runtimeScene) {
if (this._box2DBody === null) {
this.createBody();
}
//Simulate the world
if (!this._sharedData.stepped) {
this._sharedData.step(
runtimeScene.getTimeManager().getElapsedTime() / 1000
);
}
//Update object position according to Box2D body
this.owner.setX(
this._box2DBody.GetPosition().get_x() * this._sharedData.scaleX -
this.owner.getWidth() / 2 +
this.owner.getX() -
this.owner.getDrawableX()
);
this.owner.setY(
-this._box2DBody.GetPosition().get_y() * this._sharedData.scaleY -
this.owner.getHeight() / 2 +
this.owner.getY() -
this.owner.getDrawableY()
);
this.owner.setAngle(-gdjs.toDegrees(this._box2DBody.GetAngle()));
this._objectOldX = this.owner.getX();
this._objectOldY = this.owner.getY();
this._objectOldAngle = this.owner.getAngle();
}
getBox2DBody() {
if (this._box2DBody === null) {
this.createBody();
}
return this._box2DBody;
}
doStepPostEvents(runtimeScene) {
if (this._box2DBody === null) {
this.createBody();
}
//Ensure the Box2D body width and height are correct.
if (
this._objectOldWidth !== this.owner.getWidth() ||
this._objectOldHeight !== this.owner.getHeight()
) {
//Recreate the body, but remember its movement.
const oldAngularVelocity = this._box2DBody.GetAngularVelocity();
const oldXVelocity = this._box2DBody.GetLinearVelocity().get_x();
const oldYVelocity = this._box2DBody.GetLinearVelocity().get_y();
this._sharedData.world.DestroyBody(this._box2DBody);
this.createBody();
this._box2DBody.SetAngularVelocity(oldAngularVelocity);
this._box2DBody.SetLinearVelocity(
this.b2Vec2(oldXVelocity, oldYVelocity)
);
}
this._sharedData.stepped = false;
//Ensure that the Box2D body position is correct
if (
this._objectOldX == this.owner.getX() &&
this._objectOldY == this.owner.getY() &&
this._objectOldAngle == this.owner.getAngle()
) {
return;
}
const pos = this.b2Vec2(
(this.owner.getDrawableX() + this.owner.getWidth() / 2) *
this._sharedData.invScaleX,
-(this.owner.getDrawableY() + this.owner.getHeight() / 2) *
this._sharedData.invScaleY
);
this._box2DBody.SetTransform(pos, -gdjs.toRad(this.owner.getAngle()));
this._box2DBody.SetAwake(true);
}
setStatic(): void {
this._dynamic = false;
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.SetType(Box2D.b2_staticBody);
}
setDynamic(): void {
this._dynamic = true;
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.SetType(Box2D.b2_dynamicBody);
this._box2DBody.SetAwake(true);
}
setFixedRotation(): void {
this._fixedRotation = true;
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.SetFixedRotation(true);
}
setFreeRotation(): void {
this._fixedRotation = false;
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.SetFixedRotation(false);
}
setAsBullet(): void {
this._isBullet = true;
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.SetBullet(true);
}
dontSetAsBullet() {
this._isBullet = false;
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.SetBullet(false);
}
applyImpulse(xCoordinate, yCoordinate) {
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.ApplyLinearImpulse(
this.b2Vec2(xCoordinate, -yCoordinate),
this._box2DBody.GetPosition()
);
}
applyImpulseUsingPolarCoordinates(angle, length) {
angle = gdjs.toRad(angle);
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.ApplyLinearImpulse(
this.b2Vec2(Math.cos(angle) * length, -Math.sin(angle) * length),
this._box2DBody.GetPosition()
);
}
applyImpulseTowardPosition(xPosition, yPosition, length) {
if (this._box2DBody === null) {
this.createBody();
}
const angle = Math.atan2(
yPosition * this._sharedData.invScaleY +
this._box2DBody.GetPosition().get_y(),
xPosition * this._sharedData.invScaleX -
this._box2DBody.GetPosition().get_x()
);
this._box2DBody.ApplyLinearImpulse(
this.b2Vec2(Math.cos(angle) * length, -Math.sin(angle) * length),
this._box2DBody.GetPosition()
);
}
applyForce(xCoordinate, yCoordinate) {
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.ApplyForce(
this.b2Vec2(xCoordinate, -yCoordinate),
this._box2DBody.GetPosition()
);
}
applyForceUsingPolarCoordinates(angle, length) {
angle = gdjs.toRad(angle);
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.ApplyForce(
this.b2Vec2(Math.cos(angle) * length, -Math.sin(angle) * length),
this._box2DBody.GetPosition()
);
}
applyForceTowardPosition(xPosition, yPosition, length) {
if (this._box2DBody === null) {
this.createBody();
}
const angle = Math.atan2(
yPosition * this._sharedData.invScaleY +
this._box2DBody.GetPosition().get_y(),
xPosition * this._sharedData.invScaleX -
this._box2DBody.GetPosition().get_x()
);
this._box2DBody.ApplyForce(
this.b2Vec2(Math.cos(angle) * length, -Math.sin(angle) * length),
this._box2DBody.GetPosition()
);
}
applyTorque(torque) {
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.ApplyTorque(torque);
}
setLinearVelocity(xVelocity, yVelocity): void {
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.SetLinearVelocity(this.b2Vec2(xVelocity, -yVelocity));
}
setAngularVelocity(angularVelocity): void {
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.SetAngularVelocity(angularVelocity);
}
setLinearDamping(linearDamping): void {
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.SetLinearDamping(linearDamping);
}
setAngularDamping(angularDamping): void {
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.SetAngularDamping(angularDamping);
}
addRevoluteJointBetweenObjects(
object,
scene,
xPosRelativeToMassCenter,
yPosRelativeToMassCenter
) {
if (this._box2DBody === null) {
this.createBody();
}
if (object == null || !object.hasBehavior(this.name)) {
return;
}
const otherBody = object.getBehavior(this.name).getBox2DBody();
if (this._box2DBody == otherBody) {
return;
}
const jointDef = new Box2D.b2RevoluteJointDef();
jointDef.Initialize(
this._box2DBody,
otherBody,
this.b2Vec2(
xPosRelativeToMassCenter * this._sharedData.invScaleX +
this._box2DBody.GetWorldCenter().get_x(),
yPosRelativeToMassCenter * this._sharedData.invScaleY +
this._box2DBody.GetWorldCenter().get_y()
)
);
this._sharedData.world.CreateJoint(jointDef);
}
addRevoluteJoint(xPosition, yPosition) {
if (this._box2DBody === null) {
this.createBody();
}
const jointDef = new Box2D.b2RevoluteJointDef();
jointDef.Initialize(
this._box2DBody,
this._sharedData.staticBody,
this.b2Vec2(
xPosition * this._sharedData.invScaleX,
-yPosition * this._sharedData.invScaleY
)
);
this._sharedData.world.CreateJoint(jointDef);
}
setGravity(xGravity, yGravity): void {
if (this._box2DBody === null) {
this.createBody();
}
this._sharedData.world.SetGravity(this.b2Vec2(xGravity, -yGravity));
}
addGearJointBetweenObjects(object, ratio) {
if (this._box2DBody === null) {
this.createBody();
}
if (object == null || !object.hasBehavior(this.name)) {
return;
}
const otherBody = object.getBehavior(this.name).getBox2DBody();
if (this._box2DBody == otherBody) {
return;
}
//Gear joint need a revolute joint to the ground for the two objects
const jointDef1 = new Box2D.b2RevoluteJointDef();
jointDef1.Initialize(
this._sharedData.world.GetGroundBody(),
this._box2DBody,
this._box2DBody.GetWorldCenter()
);
const jointDef2 = new Box2D.b2RevoluteJointDef();
jointDef2.Initialize(
this._sharedData.world.GetGroundBody(),
otherBody,
otherBody.GetWorldCenter()
);
const jointDef = new Box2D.b2GearJointDef();
jointDef.set_bodyA(this._box2DBody);
jointDef.set_bodyB(otherBody);
jointDef.set_joint1(this._sharedData.world.CreateJoint(jointDef1));
jointDef.set_joint2(this._sharedData.world.CreateJoint(jointDef2));
jointDef.set_ratio(ratio * 3.14159);
this._sharedData.world.CreateJoint(jointDef);
}
setLinearVelocityX(xVelocity): void {
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.SetLinearVelocity(
this.b2Vec2(xVelocity, this._box2DBody.GetLinearVelocity().get_y())
);
}
setLinearVelocityY(yVelocity): void {
if (this._box2DBody === null) {
this.createBody();
}
this._box2DBody.SetLinearVelocity(
this.b2Vec2(this._box2DBody.GetLinearVelocity().get_x(), -yVelocity)
);
}
getLinearVelocityX(): float {
if (this._box2DBody === null) {
this.createBody();
}
return this._box2DBody.GetLinearVelocity().get_x();
}
getLinearVelocityY(): float {
if (this._box2DBody === null) {
this.createBody();
}
return -this._box2DBody.GetLinearVelocity().get_y();
}
getLinearVelocity() {
if (this._box2DBody === null) {
this.createBody();
}
return Math.sqrt(
this._box2DBody.GetLinearVelocity().get_x() *
this._box2DBody.GetLinearVelocity().get_x() +
this._box2DBody.GetLinearVelocity().get_y() *
this._box2DBody.GetLinearVelocity().get_y()
);
}
getAngularVelocity() {
if (this._box2DBody === null) {
this.createBody();
}
return this._box2DBody.GetAngularVelocity();
}
getLinearDamping() {
if (this._box2DBody === null) {
this.createBody();
}
return this._box2DBody.GetLinearDamping();
}
getAngularDamping() {
if (this._box2DBody === null) {
this.createBody();
}
return this._box2DBody.GetAngularDamping();
}
collisionWith(otherObjectsTable) {
if (this._box2DBody === null) {
this.createBody();
}
//Getting a list of all objects which are tested
const objects = gdjs.staticArray(
PhysicsRuntimeBehavior.prototype.collisionWith
);
objects.length = 0;
const objectsLists = gdjs.staticArray2(
PhysicsRuntimeBehavior.prototype.collisionWith
);
otherObjectsTable.values(objectsLists);
for (let i = 0, len = objectsLists.length; i < len; ++i) {
objects.push.apply(objects, objectsLists[i]);
}
//Test if an object of the list is in collision with our object.
for (let i = 0, len = objects.length; i < len; ++i) {
for (let j = 0, lenj = this.currentContacts.length; j < lenj; ++j) {
if (this.currentContacts[j].owner.id === objects[i].id) {
return true;
}
}
}
return false;
}
isStatic(): boolean {
return !this._dynamic;
}
isDynamic(): boolean {
return this._dynamic;
}
}
gdjs.registerBehavior(
'PhysicsBehavior::PhysicsBehavior',
gdjs.PhysicsRuntimeBehavior
);
} | the_stack |
import { GlobalProps } from 'ojs/ojvcomponent';
import { ComponentChildren } from 'preact';
import CommonTypes = require('../ojcommontypes');
import { KeySet } from '../ojkeyset';
import { DataProvider, Item } from '../ojdataprovider';
import { baseComponent, baseComponentEventMap, baseComponentSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojTable<K, D> extends baseComponent<ojTableSettableProperties<K, D>> {
accessibility: {
rowHeader: string | string[];
};
as: string;
columns: Array<ojTable.Column<K, D>> | null;
columnsDefault: ojTable.ColumnDefault<K, D> | null;
currentRow: ojTable.CurrentRow<K> | null;
data: DataProvider<K, D> | null;
display: 'list' | 'grid';
dnd: {
drag: {
rows: {
dataTypes?: string | string[];
drag?: ((param0: DragEvent) => void);
dragEnd?: ((param0: DragEvent) => void);
dragStart?: ((param0: DragEvent, param1: ojTable.DragRowContext<K, D>) => void);
};
};
drop: {
columns: {
dataTypes: string | string[];
dragEnter?: ((param0: DragEvent, param1: ojTable.DropColumnContext) => void);
dragLeave?: ((param0: DragEvent, param1: ojTable.DropColumnContext) => void);
dragOver?: ((param0: DragEvent, param1: ojTable.DropColumnContext) => void);
drop: ((param0: DragEvent, param1: ojTable.DropColumnContext) => void);
};
rows: {
dataTypes: string | string[];
dragEnter?: ((param0: DragEvent, param1: ojTable.DropRowContext) => void);
dragLeave?: ((param0: DragEvent, param1: ojTable.DropRowContext) => void);
dragOver?: ((param0: DragEvent, param1: ojTable.DropRowContext) => void);
drop: ((param0: DragEvent, param1: ojTable.DropRowContext) => void);
};
};
reorder: {
columns: 'enabled' | 'disabled';
};
};
editMode: 'none' | 'rowEdit';
editRow: ojTable.EditRow<K> | null;
readonly firstSelectedRow: CommonTypes.ItemContext<K, D>;
horizontalGridVisible: 'auto' | 'enabled' | 'disabled';
layout: 'contents' | 'fixed';
rowRenderer: ((context: ojTable.RowRendererContext<K, D>) => string | HTMLElement | void) | null;
scrollPolicy: 'auto' | 'loadAll' | 'loadMoreOnScroll';
scrollPolicyOptions: {
fetchSize: number;
maxCount: number;
scroller?: keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap | string;
scrollerOffsetBottom?: number | null;
scrollerOffsetEnd?: number | null;
scrollerOffsetStart?: number | null;
scrollerOffsetTop?: number | null;
};
scrollPosition: {
columnIndex?: number;
columnKey?: any;
offsetX?: number;
offsetY?: number;
rowIndex?: number;
rowKey?: any;
x?: number;
y?: number;
};
scrollToKey: 'auto' | 'capability' | 'always' | 'never';
selected: {
row: KeySet<K>;
column: KeySet<K>;
};
selection: Array<ojTable.RowSelectionStart<K> & ojTable.RowSelectionEnd<K>> | Array<ojTable.ColumnSelectionStart<K> & ojTable.ColumnSelectionEnd<K>>;
selectionMode: {
column: 'none' | 'single' | 'multiple';
row: 'none' | 'single' | 'multiple';
};
selectionRequired: boolean;
verticalGridVisible: 'auto' | 'enabled' | 'disabled';
translations: {
accessibleColumnContext?: string;
accessibleColumnFooterContext?: string;
accessibleColumnHeaderContext?: string;
accessibleRowContext?: string;
accessibleSortAscending?: string;
accessibleSortDescending?: string;
accessibleSortable?: string;
accessibleStateSelected?: string;
labelAccSelectionAffordanceBottom?: string;
labelAccSelectionAffordanceTop?: string;
labelColumnWidth?: string;
labelDisableNonContiguousSelection?: string;
labelEditRow?: string;
labelEnableNonContiguousSelection?: string;
labelResize?: string;
labelResizeColumn?: string;
labelResizeColumnDialog?: string;
labelResizeDialogApply?: string;
labelResizePopupCancel?: string;
labelResizePopupSpinner?: string;
labelResizePopupSubmit?: string;
labelSelectAndEditRow?: string;
labelSelectColum?: string;
labelSelectRow?: string;
labelSort?: string;
labelSortAsc?: string;
labelSortDsc?: string;
msgColumnResizeWidthValidation?: string;
msgFetchingData?: string;
msgInitializing?: string;
msgNoData?: string;
msgScrollPolicyMaxCountDetail?: string;
msgScrollPolicyMaxCountSummary?: string;
msgStatusSortAscending?: string;
msgStatusSortDescending?: string;
};
addEventListener<T extends keyof ojTableEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojTableEventMap<K, D>[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojTableSettableProperties<K, D>>(property: T): ojTable<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojTableSettableProperties<K, D>>(property: T, value: ojTableSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojTableSettableProperties<K, D>>): void;
setProperties(properties: ojTableSettablePropertiesLenient<K, D>): void;
getContextByNode(node: Element): {
subId: 'oj-table-cell';
rowIndex: number;
columnIndex: number;
key: string;
} | {
subId: 'oj-table-footer' | 'oj-table-header';
index: number;
};
getDataForVisibleRow(rowIndex: number): {
data: D;
index: number;
key: K;
} | null;
refresh(): void;
refreshRow(rowIdx: number): Promise<boolean>;
}
export namespace ojTable {
interface ojAnimateEnd extends CustomEvent<{
action: 'add' | 'remove' | 'update';
element: Element;
[propName: string]: any;
}> {
}
interface ojAnimateStart extends CustomEvent<{
action: 'add' | 'remove' | 'update';
element: Element;
endCallback: (() => void);
[propName: string]: any;
}> {
}
interface ojBeforeCurrentRow<K> extends CustomEvent<{
currentRow: CurrentRow<K>;
previousCurrentRow: CurrentRow<K>;
[propName: string]: any;
}> {
}
interface ojBeforeRowEdit<K, D> extends CustomEvent<{
rowContext: {
componentElement: Element;
datasource: DataProvider<K, D> | null;
item: Item<K, D>;
mode: 'edit' | 'navigation';
parentElement: Element;
status: ContextStatus<K>;
};
[propName: string]: any;
}> {
}
interface ojBeforeRowEditEnd<K, D> extends CustomEvent<{
cancelEdit: boolean;
rowContext: {
componentElement: Element;
datasource: DataProvider<K, D> | null;
item: Item<K, D>;
mode: 'edit' | 'navigation';
parentElement: Element;
status: ContextStatus<K>;
};
[propName: string]: any;
}> {
}
interface ojRowAction<K, D> extends CustomEvent<{
context: CommonTypes.ItemContext<K, D>;
originalEvent: Event;
[propName: string]: any;
}> {
}
interface ojSort extends CustomEvent<{
direction: 'ascending' | 'descending';
header: string;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type accessibilityChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["accessibility"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type columnsChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["columns"]>;
// tslint:disable-next-line interface-over-type-literal
type columnsDefaultChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["columnsDefault"]>;
// tslint:disable-next-line interface-over-type-literal
type currentRowChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["currentRow"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type displayChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["display"]>;
// tslint:disable-next-line interface-over-type-literal
type dndChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["dnd"]>;
// tslint:disable-next-line interface-over-type-literal
type editModeChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["editMode"]>;
// tslint:disable-next-line interface-over-type-literal
type editRowChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["editRow"]>;
// tslint:disable-next-line interface-over-type-literal
type firstSelectedRowChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["firstSelectedRow"]>;
// tslint:disable-next-line interface-over-type-literal
type horizontalGridVisibleChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["horizontalGridVisible"]>;
// tslint:disable-next-line interface-over-type-literal
type layoutChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["layout"]>;
// tslint:disable-next-line interface-over-type-literal
type rowRendererChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["rowRenderer"]>;
// tslint:disable-next-line interface-over-type-literal
type scrollPolicyChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["scrollPolicy"]>;
// tslint:disable-next-line interface-over-type-literal
type scrollPolicyOptionsChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["scrollPolicyOptions"]>;
// tslint:disable-next-line interface-over-type-literal
type scrollPositionChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["scrollPosition"]>;
// tslint:disable-next-line interface-over-type-literal
type scrollToKeyChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["scrollToKey"]>;
// tslint:disable-next-line interface-over-type-literal
type selectedChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["selected"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionRequiredChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["selectionRequired"]>;
// tslint:disable-next-line interface-over-type-literal
type verticalGridVisibleChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["verticalGridVisible"]>;
// tslint:disable-next-line interface-over-type-literal
type CellTemplateContext<K, D> = {
columnIndex: number;
columnKey: keyof D;
componentElement: Element;
data: D[keyof D];
datasource: DataProvider<K, D> | null;
index: number;
item: Item<K, D>;
key: any;
mode: 'edit' | 'navigation';
row: any;
};
// tslint:disable-next-line interface-over-type-literal
type Column<K, D> = {
className?: string | null;
field?: string | null;
footerClassName?: string | null;
footerRenderer?: ((context: FooterRendererContext<K, D>) => {
insert: HTMLElement | string;
} | void) | null;
footerStyle?: string | null;
footerTemplate?: string | null;
frozenEdge?: 'start' | 'end' | null;
headerClassName?: string | null;
headerRenderer?: ((context: HeaderRendererContext<K, D>) => {
insert: HTMLElement | string;
} | void) | null;
headerStyle?: string | null;
headerTemplate?: string | null;
headerText?: string | null;
id?: string | null;
maxWidth?: string | number | null;
minWidth?: 'auto' | string | number | null;
renderer?: ((context: ColumnsRendererContext<K, D>) => {
insert: HTMLElement | string;
} | void) | null;
resizable?: 'enabled' | 'disabled';
sortProperty?: string | null;
sortable?: 'auto' | 'enabled' | 'disabled';
style?: string | null;
template?: string | null;
weight?: number | null;
width?: string | number | null;
};
// tslint:disable-next-line interface-over-type-literal
type ColumnDefault<K, D> = {
className?: string | null;
field?: string | null;
footerClassName?: string | null;
footerRenderer?: ((context: FooterRendererContext<K, D>) => {
insert: HTMLElement | string;
} | void) | null;
footerStyle?: string | null;
footerTemplate?: string | null;
headerClassName?: string | null;
headerRenderer?: ((context: HeaderRendererContext<K, D>) => {
insert: HTMLElement | string;
} | void) | null;
headerStyle?: string | null;
headerTemplate?: string | null;
headerText?: string | null;
maxWidth?: string | number | null;
minWidth?: 'auto' | string | number | null;
renderer?: ((context: ColumnsRendererContext<K, D>) => {
insert: HTMLElement | string;
} | void) | null;
resizable?: 'enabled' | 'disabled';
sortProperty?: string | null;
sortable?: 'auto' | 'enabled' | 'disabled';
style?: string | null;
template?: string | null;
weight?: number | null;
width?: string | number | null;
};
// tslint:disable-next-line interface-over-type-literal
type ColumnSelectionEnd<K> = {
endIndex: {
column: number;
};
endKey?: {
column: K;
};
} | {
endIndex?: {
column: number;
};
endKey: {
column: K;
};
};
// tslint:disable-next-line interface-over-type-literal
type ColumnSelectionStart<K> = {
startIndex: {
column: number;
};
startKey?: {
column: K;
};
} | {
startIndex?: {
column: number;
};
startKey: {
column: K;
};
};
// tslint:disable-next-line interface-over-type-literal
type ColumnsRendererContext<K, D> = {
cellContext: {
datasource: DataProvider<K, D> | null;
mode: 'edit' | 'navigation';
status: ContextStatus<K>;
};
columnIndex: number;
componentElement: Element;
data: any;
parentElement: Element;
row: D;
};
// tslint:disable-next-line interface-over-type-literal
type ContextStatus<K> = {
currentRow: CurrentRow<K>;
rowIndex: number;
rowKey: K;
};
// tslint:disable-next-line interface-over-type-literal
type CurrentRow<K> = {
rowIndex: number;
rowKey?: K;
} | {
rowIndex?: number;
rowKey: K;
};
// tslint:disable-next-line interface-over-type-literal
type DragRowContext<K, D> = {
rows: Array<{
data: D;
index: number;
key: K;
}>;
};
// tslint:disable-next-line interface-over-type-literal
type DropColumnContext = {
columnIndex: number;
};
// tslint:disable-next-line interface-over-type-literal
type DropRowContext = {
rowIndex: number;
};
// tslint:disable-next-line interface-over-type-literal
type EditRow<K> = {
rowIndex: number;
rowKey?: K;
} | {
rowIndex?: number;
rowKey: K;
};
// tslint:disable-next-line interface-over-type-literal
type FooterRendererContext<K, D> = {
columnIndex: number;
componentElement: Element;
footerContext: {
datasource: DataProvider<K, D> | null;
};
parentElement: Element;
};
// tslint:disable-next-line interface-over-type-literal
type FooterTemplateContext<D> = {
columnIndex: number;
columnKey: keyof D;
componentElement: Element;
};
// tslint:disable-next-line interface-over-type-literal
type HeaderRendererContext<K, D> = {
columnHeaderDefaultRenderer?: ((param0: object, param1: ((param0: Element) => void)) => void);
columnHeaderSortableIconRenderer?: ((param0: object, param1: ((param0: Element) => void)) => void);
columnIndex: number;
componentElement: Element;
data: string;
headerContext: {
datasource: DataProvider<K, D> | null;
};
parentElement: Element;
};
// tslint:disable-next-line interface-over-type-literal
type HeaderTemplateContext<D> = {
columnIndex: number;
columnKey: keyof D;
componentElement: Element;
data: any;
headerText: string;
};
// tslint:disable-next-line interface-over-type-literal
type RowRendererContext<K, D> = {
componentElement: Element;
data: D;
parentElement: Element;
rowContext: {
datasource: DataProvider<K, D> | null;
mode: 'edit' | 'navigation';
status: ContextStatus<K>;
};
};
// tslint:disable-next-line interface-over-type-literal
type RowSelectionEnd<K> = {
endIndex: {
row: number;
};
endKey?: {
row: K;
};
} | {
endIndex?: {
row: number;
};
endKey: {
row: K;
};
};
// tslint:disable-next-line interface-over-type-literal
type RowSelectionStart<K> = {
startIndex: {
row: number;
};
startKey?: {
row: K;
};
} | {
startIndex?: {
row: number;
};
startKey: {
row: K;
};
};
// tslint:disable-next-line interface-over-type-literal
type RowTemplateContext<K, D> = {
componentElement: Element;
data: any;
datasource: DataProvider<K, D> | null;
index: number;
item: Item<K, D>;
key: any;
mode: 'edit' | 'navigation';
rowContext: object;
};
}
export interface ojTableEventMap<K, D> extends baseComponentEventMap<ojTableSettableProperties<K, D>> {
'ojAnimateEnd': ojTable.ojAnimateEnd;
'ojAnimateStart': ojTable.ojAnimateStart;
'ojBeforeCurrentRow': ojTable.ojBeforeCurrentRow<K>;
'ojBeforeRowEdit': ojTable.ojBeforeRowEdit<K, D>;
'ojBeforeRowEditEnd': ojTable.ojBeforeRowEditEnd<K, D>;
'ojRowAction': ojTable.ojRowAction<K, D>;
'ojSort': ojTable.ojSort;
'accessibilityChanged': JetElementCustomEvent<ojTable<K, D>["accessibility"]>;
'asChanged': JetElementCustomEvent<ojTable<K, D>["as"]>;
'columnsChanged': JetElementCustomEvent<ojTable<K, D>["columns"]>;
'columnsDefaultChanged': JetElementCustomEvent<ojTable<K, D>["columnsDefault"]>;
'currentRowChanged': JetElementCustomEvent<ojTable<K, D>["currentRow"]>;
'dataChanged': JetElementCustomEvent<ojTable<K, D>["data"]>;
'displayChanged': JetElementCustomEvent<ojTable<K, D>["display"]>;
'dndChanged': JetElementCustomEvent<ojTable<K, D>["dnd"]>;
'editModeChanged': JetElementCustomEvent<ojTable<K, D>["editMode"]>;
'editRowChanged': JetElementCustomEvent<ojTable<K, D>["editRow"]>;
'firstSelectedRowChanged': JetElementCustomEvent<ojTable<K, D>["firstSelectedRow"]>;
'horizontalGridVisibleChanged': JetElementCustomEvent<ojTable<K, D>["horizontalGridVisible"]>;
'layoutChanged': JetElementCustomEvent<ojTable<K, D>["layout"]>;
'rowRendererChanged': JetElementCustomEvent<ojTable<K, D>["rowRenderer"]>;
'scrollPolicyChanged': JetElementCustomEvent<ojTable<K, D>["scrollPolicy"]>;
'scrollPolicyOptionsChanged': JetElementCustomEvent<ojTable<K, D>["scrollPolicyOptions"]>;
'scrollPositionChanged': JetElementCustomEvent<ojTable<K, D>["scrollPosition"]>;
'scrollToKeyChanged': JetElementCustomEvent<ojTable<K, D>["scrollToKey"]>;
'selectedChanged': JetElementCustomEvent<ojTable<K, D>["selected"]>;
'selectionChanged': JetElementCustomEvent<ojTable<K, D>["selection"]>;
'selectionModeChanged': JetElementCustomEvent<ojTable<K, D>["selectionMode"]>;
'selectionRequiredChanged': JetElementCustomEvent<ojTable<K, D>["selectionRequired"]>;
'verticalGridVisibleChanged': JetElementCustomEvent<ojTable<K, D>["verticalGridVisible"]>;
}
export interface ojTableSettableProperties<K, D> extends baseComponentSettableProperties {
accessibility: {
rowHeader: string | string[];
};
as: string;
columns: Array<ojTable.Column<K, D>> | null;
columnsDefault: ojTable.ColumnDefault<K, D> | null;
currentRow: ojTable.CurrentRow<K> | null;
data: DataProvider<K, D> | null;
display: 'list' | 'grid';
dnd: {
drag: {
rows: {
dataTypes?: string | string[];
drag?: ((param0: DragEvent) => void);
dragEnd?: ((param0: DragEvent) => void);
dragStart?: ((param0: DragEvent, param1: ojTable.DragRowContext<K, D>) => void);
};
};
drop: {
columns: {
dataTypes: string | string[];
dragEnter?: ((param0: DragEvent, param1: ojTable.DropColumnContext) => void);
dragLeave?: ((param0: DragEvent, param1: ojTable.DropColumnContext) => void);
dragOver?: ((param0: DragEvent, param1: ojTable.DropColumnContext) => void);
drop: ((param0: DragEvent, param1: ojTable.DropColumnContext) => void);
};
rows: {
dataTypes: string | string[];
dragEnter?: ((param0: DragEvent, param1: ojTable.DropRowContext) => void);
dragLeave?: ((param0: DragEvent, param1: ojTable.DropRowContext) => void);
dragOver?: ((param0: DragEvent, param1: ojTable.DropRowContext) => void);
drop: ((param0: DragEvent, param1: ojTable.DropRowContext) => void);
};
};
reorder: {
columns: 'enabled' | 'disabled';
};
};
editMode: 'none' | 'rowEdit';
editRow: ojTable.EditRow<K> | null;
readonly firstSelectedRow: CommonTypes.ItemContext<K, D>;
horizontalGridVisible: 'auto' | 'enabled' | 'disabled';
layout: 'contents' | 'fixed';
rowRenderer: ((context: ojTable.RowRendererContext<K, D>) => string | HTMLElement | void) | null;
scrollPolicy: 'auto' | 'loadAll' | 'loadMoreOnScroll';
scrollPolicyOptions: {
fetchSize: number;
maxCount: number;
scroller?: keyof HTMLElementTagNameMap | keyof SVGElementTagNameMap | string;
scrollerOffsetBottom?: number | null;
scrollerOffsetEnd?: number | null;
scrollerOffsetStart?: number | null;
scrollerOffsetTop?: number | null;
};
scrollPosition: {
columnIndex?: number;
columnKey?: any;
offsetX?: number;
offsetY?: number;
rowIndex?: number;
rowKey?: any;
x?: number;
y?: number;
};
scrollToKey: 'auto' | 'capability' | 'always' | 'never';
selected: {
row: KeySet<K>;
column: KeySet<K>;
};
selection: Array<ojTable.RowSelectionStart<K> & ojTable.RowSelectionEnd<K>> | Array<ojTable.ColumnSelectionStart<K> & ojTable.ColumnSelectionEnd<K>>;
selectionMode: {
column: 'none' | 'single' | 'multiple';
row: 'none' | 'single' | 'multiple';
};
selectionRequired: boolean;
verticalGridVisible: 'auto' | 'enabled' | 'disabled';
translations: {
accessibleColumnContext?: string;
accessibleColumnFooterContext?: string;
accessibleColumnHeaderContext?: string;
accessibleRowContext?: string;
accessibleSortAscending?: string;
accessibleSortDescending?: string;
accessibleSortable?: string;
accessibleStateSelected?: string;
labelAccSelectionAffordanceBottom?: string;
labelAccSelectionAffordanceTop?: string;
labelColumnWidth?: string;
labelDisableNonContiguousSelection?: string;
labelEditRow?: string;
labelEnableNonContiguousSelection?: string;
labelResize?: string;
labelResizeColumn?: string;
labelResizeColumnDialog?: string;
labelResizeDialogApply?: string;
labelResizePopupCancel?: string;
labelResizePopupSpinner?: string;
labelResizePopupSubmit?: string;
labelSelectAndEditRow?: string;
labelSelectColum?: string;
labelSelectRow?: string;
labelSort?: string;
labelSortAsc?: string;
labelSortDsc?: string;
msgColumnResizeWidthValidation?: string;
msgFetchingData?: string;
msgInitializing?: string;
msgNoData?: string;
msgScrollPolicyMaxCountDetail?: string;
msgScrollPolicyMaxCountSummary?: string;
msgStatusSortAscending?: string;
msgStatusSortDescending?: string;
};
}
export interface ojTableSettablePropertiesLenient<K, D> extends Partial<ojTableSettableProperties<K, D>> {
[key: string]: any;
}
export type TableElement<K, D> = ojTable<K, D>;
export namespace TableElement {
interface ojAnimateEnd extends CustomEvent<{
action: 'add' | 'remove' | 'update';
element: Element;
[propName: string]: any;
}> {
}
interface ojAnimateStart extends CustomEvent<{
action: 'add' | 'remove' | 'update';
element: Element;
endCallback: (() => void);
[propName: string]: any;
}> {
}
interface ojBeforeCurrentRow<K> extends CustomEvent<{
currentRow: ojTable.CurrentRow<K>;
previousCurrentRow: ojTable.CurrentRow<K>;
[propName: string]: any;
}> {
}
interface ojBeforeRowEdit<K, D> extends CustomEvent<{
rowContext: {
componentElement: Element;
datasource: DataProvider<K, D> | null;
item: Item<K, D>;
mode: 'edit' | 'navigation';
parentElement: Element;
status: ojTable.ContextStatus<K>;
};
[propName: string]: any;
}> {
}
interface ojBeforeRowEditEnd<K, D> extends CustomEvent<{
cancelEdit: boolean;
rowContext: {
componentElement: Element;
datasource: DataProvider<K, D> | null;
item: Item<K, D>;
mode: 'edit' | 'navigation';
parentElement: Element;
status: ojTable.ContextStatus<K>;
};
[propName: string]: any;
}> {
}
interface ojRowAction<K, D> extends CustomEvent<{
context: CommonTypes.ItemContext<K, D>;
originalEvent: Event;
[propName: string]: any;
}> {
}
interface ojSort extends CustomEvent<{
direction: 'ascending' | 'descending';
header: string;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type accessibilityChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["accessibility"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type columnsChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["columns"]>;
// tslint:disable-next-line interface-over-type-literal
type columnsDefaultChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["columnsDefault"]>;
// tslint:disable-next-line interface-over-type-literal
type currentRowChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["currentRow"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type displayChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["display"]>;
// tslint:disable-next-line interface-over-type-literal
type dndChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["dnd"]>;
// tslint:disable-next-line interface-over-type-literal
type editModeChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["editMode"]>;
// tslint:disable-next-line interface-over-type-literal
type editRowChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["editRow"]>;
// tslint:disable-next-line interface-over-type-literal
type firstSelectedRowChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["firstSelectedRow"]>;
// tslint:disable-next-line interface-over-type-literal
type horizontalGridVisibleChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["horizontalGridVisible"]>;
// tslint:disable-next-line interface-over-type-literal
type layoutChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["layout"]>;
// tslint:disable-next-line interface-over-type-literal
type rowRendererChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["rowRenderer"]>;
// tslint:disable-next-line interface-over-type-literal
type scrollPolicyChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["scrollPolicy"]>;
// tslint:disable-next-line interface-over-type-literal
type scrollPolicyOptionsChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["scrollPolicyOptions"]>;
// tslint:disable-next-line interface-over-type-literal
type scrollPositionChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["scrollPosition"]>;
// tslint:disable-next-line interface-over-type-literal
type scrollToKeyChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["scrollToKey"]>;
// tslint:disable-next-line interface-over-type-literal
type selectedChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["selected"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionRequiredChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["selectionRequired"]>;
// tslint:disable-next-line interface-over-type-literal
type verticalGridVisibleChanged<K, D> = JetElementCustomEvent<ojTable<K, D>["verticalGridVisible"]>;
// tslint:disable-next-line interface-over-type-literal
type CellTemplateContext<K, D> = {
columnIndex: number;
columnKey: keyof D;
componentElement: Element;
data: D[keyof D];
datasource: DataProvider<K, D> | null;
index: number;
item: Item<K, D>;
key: any;
mode: 'edit' | 'navigation';
row: any;
};
// tslint:disable-next-line interface-over-type-literal
type ColumnDefault<K, D> = {
className?: string | null;
field?: string | null;
footerClassName?: string | null;
footerRenderer?: ((context: ojTable.FooterRendererContext<K, D>) => {
insert: HTMLElement | string;
} | void) | null;
footerStyle?: string | null;
footerTemplate?: string | null;
headerClassName?: string | null;
headerRenderer?: ((context: ojTable.HeaderRendererContext<K, D>) => {
insert: HTMLElement | string;
} | void) | null;
headerStyle?: string | null;
headerTemplate?: string | null;
headerText?: string | null;
maxWidth?: string | number | null;
minWidth?: 'auto' | string | number | null;
renderer?: ((context: ojTable.ColumnsRendererContext<K, D>) => {
insert: HTMLElement | string;
} | void) | null;
resizable?: 'enabled' | 'disabled';
sortProperty?: string | null;
sortable?: 'auto' | 'enabled' | 'disabled';
style?: string | null;
template?: string | null;
weight?: number | null;
width?: string | number | null;
};
// tslint:disable-next-line interface-over-type-literal
type ColumnSelectionStart<K> = {
startIndex: {
column: number;
};
startKey?: {
column: K;
};
} | {
startIndex?: {
column: number;
};
startKey: {
column: K;
};
};
// tslint:disable-next-line interface-over-type-literal
type ContextStatus<K> = {
currentRow: ojTable.CurrentRow<K>;
rowIndex: number;
rowKey: K;
};
// tslint:disable-next-line interface-over-type-literal
type DragRowContext<K, D> = {
rows: Array<{
data: D;
index: number;
key: K;
}>;
};
// tslint:disable-next-line interface-over-type-literal
type DropRowContext = {
rowIndex: number;
};
// tslint:disable-next-line interface-over-type-literal
type FooterRendererContext<K, D> = {
columnIndex: number;
componentElement: Element;
footerContext: {
datasource: DataProvider<K, D> | null;
};
parentElement: Element;
};
// tslint:disable-next-line interface-over-type-literal
type HeaderRendererContext<K, D> = {
columnHeaderDefaultRenderer?: ((param0: object, param1: ((param0: Element) => void)) => void);
columnHeaderSortableIconRenderer?: ((param0: object, param1: ((param0: Element) => void)) => void);
columnIndex: number;
componentElement: Element;
data: string;
headerContext: {
datasource: DataProvider<K, D> | null;
};
parentElement: Element;
};
// tslint:disable-next-line interface-over-type-literal
type RowRendererContext<K, D> = {
componentElement: Element;
data: D;
parentElement: Element;
rowContext: {
datasource: DataProvider<K, D> | null;
mode: 'edit' | 'navigation';
status: ojTable.ContextStatus<K>;
};
};
// tslint:disable-next-line interface-over-type-literal
type RowSelectionStart<K> = {
startIndex: {
row: number;
};
startKey?: {
row: K;
};
} | {
startIndex?: {
row: number;
};
startKey: {
row: K;
};
};
}
export interface TableIntrinsicProps extends Partial<Readonly<ojTableSettableProperties<any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onojAnimateEnd?: (value: ojTableEventMap<any, any>['ojAnimateEnd']) => void;
onojAnimateStart?: (value: ojTableEventMap<any, any>['ojAnimateStart']) => void;
onojBeforeCurrentRow?: (value: ojTableEventMap<any, any>['ojBeforeCurrentRow']) => void;
onojBeforeRowEdit?: (value: ojTableEventMap<any, any>['ojBeforeRowEdit']) => void;
onojBeforeRowEditEnd?: (value: ojTableEventMap<any, any>['ojBeforeRowEditEnd']) => void;
onojRowAction?: (value: ojTableEventMap<any, any>['ojRowAction']) => void;
onojSort?: (value: ojTableEventMap<any, any>['ojSort']) => void;
onaccessibilityChanged?: (value: ojTableEventMap<any, any>['accessibilityChanged']) => void;
onasChanged?: (value: ojTableEventMap<any, any>['asChanged']) => void;
oncolumnsChanged?: (value: ojTableEventMap<any, any>['columnsChanged']) => void;
oncolumnsDefaultChanged?: (value: ojTableEventMap<any, any>['columnsDefaultChanged']) => void;
oncurrentRowChanged?: (value: ojTableEventMap<any, any>['currentRowChanged']) => void;
ondataChanged?: (value: ojTableEventMap<any, any>['dataChanged']) => void;
ondisplayChanged?: (value: ojTableEventMap<any, any>['displayChanged']) => void;
ondndChanged?: (value: ojTableEventMap<any, any>['dndChanged']) => void;
oneditModeChanged?: (value: ojTableEventMap<any, any>['editModeChanged']) => void;
oneditRowChanged?: (value: ojTableEventMap<any, any>['editRowChanged']) => void;
onfirstSelectedRowChanged?: (value: ojTableEventMap<any, any>['firstSelectedRowChanged']) => void;
onhorizontalGridVisibleChanged?: (value: ojTableEventMap<any, any>['horizontalGridVisibleChanged']) => void;
onlayoutChanged?: (value: ojTableEventMap<any, any>['layoutChanged']) => void;
onrowRendererChanged?: (value: ojTableEventMap<any, any>['rowRendererChanged']) => void;
onscrollPolicyChanged?: (value: ojTableEventMap<any, any>['scrollPolicyChanged']) => void;
onscrollPolicyOptionsChanged?: (value: ojTableEventMap<any, any>['scrollPolicyOptionsChanged']) => void;
onscrollPositionChanged?: (value: ojTableEventMap<any, any>['scrollPositionChanged']) => void;
onscrollToKeyChanged?: (value: ojTableEventMap<any, any>['scrollToKeyChanged']) => void;
onselectedChanged?: (value: ojTableEventMap<any, any>['selectedChanged']) => void;
onselectionChanged?: (value: ojTableEventMap<any, any>['selectionChanged']) => void;
onselectionModeChanged?: (value: ojTableEventMap<any, any>['selectionModeChanged']) => void;
onselectionRequiredChanged?: (value: ojTableEventMap<any, any>['selectionRequiredChanged']) => void;
onverticalGridVisibleChanged?: (value: ojTableEventMap<any, any>['verticalGridVisibleChanged']) => void;
children?: ComponentChildren;
}
declare global {
namespace preact.JSX {
interface IntrinsicElements {
"oj-table": TableIntrinsicProps;
}
}
} | the_stack |
import * as _ from "lodash";
import * as singleLineString from "single-line-string";
import * as Web3 from "web3";
import { BigNumber } from "../../utils/bignumber";
// Apis
import { ContractsAPI } from "./";
// Utils
import { DISABLED_TOKEN_SYMBOLS } from "../../utils/constants";
import { generateTxOptions } from "../../utils/transaction_utils";
import { Assertions } from "../invariants";
import { TxData } from "../types";
const TRANSFER_GAS_MAXIMUM = 70000;
// We set an allowance to be "unlimited" by setting it to it's maximum possible value: 2^256 - 1.
export const UNLIMITED_ALLOWANCE = new BigNumber(2).pow(256).sub(1);
export interface TokenAttributes {
address: string;
symbol: string;
name: string;
numDecimals: BigNumber;
}
export const TokenAPIErrors = {
INSUFFICIENT_SENDER_BALANCE: (address) =>
singleLineString`SENDER with address ${address} does not have sufficient balance in the specified token
to execute this transfer.`,
INSUFFICIENT_SENDER_ALLOWANCE: (address) =>
singleLineString`SENDER with address ${address} does not have sufficient allowance in the specified token
to execute this transfer.`,
TOKEN_DOES_NOT_EXIST: (tokenSymbol) =>
singleLineString`TOKEN with symbol ${tokenSymbol} does not exist in the token registry.`,
};
export class TokenAPI {
/**
* Determines whether the allowance specified is the unlimited allowance.
*
* @param {BigNumber} allowance
* @returns {boolean}
*/
public static isUnlimitedAllowance(allowance: BigNumber): boolean {
return allowance.greaterThanOrEqualTo(UNLIMITED_ALLOWANCE);
}
private readonly web3: Web3;
private readonly contracts: ContractsAPI;
private assert: Assertions;
constructor(web3: Web3, contracts: ContractsAPI) {
this.web3 = web3;
this.contracts = contracts;
this.assert = new Assertions(this.web3, this.contracts);
}
/**
* Asynchronously transfer value denominated in the specified ERC20 token to
* the address specified.
*
* @param tokenAddress the address of the token being used.
* @param to to whom the transfer is being made.
* @param value the amount being transferred.
* @param options any parameters necessary to modify the transaction.
* @return the hash of the resulting transaction.
*/
public async transferAsync(
tokenAddress: string,
to: string,
value: BigNumber,
options?: TxData,
): Promise<string> {
const txOptions = await generateTxOptions(this.web3, TRANSFER_GAS_MAXIMUM, options);
const tokenContract = await this.contracts.loadERC20TokenAsync(tokenAddress);
await this.assert.token.hasSufficientBalance(
tokenContract,
options.from,
value,
TokenAPIErrors.INSUFFICIENT_SENDER_BALANCE(options.from),
);
return tokenContract.transfer.sendTransactionAsync(to, value, txOptions);
}
/**
* Asynchronously transfer the value amount in the token specified so long
* as the sender of the message has received sufficient allowance on behalf
* of `from` to do so.
*
* @param tokenAddress the address of the token being used.
* @param from from whom are the funds being transferred.
* @param to to whom are the funds being transferred.
* @param value the amount to be transferred.
* @param options any parameters necessary to modify the transaction.
* @return the hash of the resulting transaction.
*/
public async transferFromAsync(
tokenAddress: string,
from: string,
to: string,
value: BigNumber,
options?: TxData,
): Promise<string> {
const txOptions = await generateTxOptions(this.web3, TRANSFER_GAS_MAXIMUM, options);
const tokenContract = await this.contracts.loadERC20TokenAsync(tokenAddress);
await this.assert.token.hasSufficientBalance(
tokenContract,
from,
value,
TokenAPIErrors.INSUFFICIENT_SENDER_BALANCE(from),
);
await this.assert.token.hasSufficientAllowance(
tokenContract,
from,
options.from,
value,
TokenAPIErrors.INSUFFICIENT_SENDER_ALLOWANCE(from),
);
return tokenContract.transferFrom.sendTransactionAsync(from, to, value, txOptions);
}
/**
* Asynchronously retrieve the balance of tokens for the owner specified.
*
* @param tokenAddress address of the ERC20 token.
* @param ownerAddress address of the owner for whom the balance is being requested.
* @return the number of tokens the owner is holding.
*/
public async getBalanceAsync(tokenAddress: string, ownerAddress: string): Promise<BigNumber> {
const tokenContract = await this.contracts.loadERC20TokenAsync(tokenAddress);
await this.assert.token.implementsERC20(tokenContract);
return tokenContract.balanceOf.callAsync(ownerAddress);
}
/**
* Asynchronously set an unlimited proxy allowance to the `creditorProxy`.
*
* @param tokenAddress address of the ERC20 token.
* @param options any parameters necessary to modify the transaction.
* @return the hash of the resulting transaction.
*/
public async setUnlimitedCreditorProxyAllowanceAsync(
tokenAddress: string,
options?: TxData,
): Promise<string> {
const tokenContract = await this.contracts.loadERC20TokenAsync(tokenAddress);
await this.assert.token.implementsERC20(tokenContract);
return this.setCreditorProxyAllowanceAsync(tokenAddress, UNLIMITED_ALLOWANCE, options);
}
/**
* Asynchronously set an allowance to the `creditorProxy`.
*
* @param tokenAddress address of the ERC20 token.
* @param allowance the size of the allowance.
* @param options any parameters necessary to modify the transaction.
* @return the hash of the resulting transaction.
*/
public async setCreditorProxyAllowanceAsync(
tokenAddress: string,
allowance: BigNumber,
options?: TxData,
): Promise<string> {
const txOptions = await generateTxOptions(this.web3, TRANSFER_GAS_MAXIMUM, options);
const tokenContract = await this.contracts.loadERC20TokenAsync(tokenAddress);
await this.assert.token.implementsERC20(tokenContract);
const creditorProxyContract = await this.contracts.loadCreditorProxyContract();
return tokenContract.approve.sendTransactionAsync(
creditorProxyContract.address,
allowance,
txOptions,
);
}
/**
* Asynchronously set an allowance to the `tokenTransferProxy`.
*
* @param tokenAddress address of the ERC20 token.
* @param allowance the size of the allowance.
* @param options any parameters necessary to modify the transaction.
* @return the hash of the resulting transaction.
*/
public async setProxyAllowanceAsync(
tokenAddress: string,
allowance: BigNumber,
options?: TxData,
): Promise<string> {
const txOptions = await generateTxOptions(this.web3, TRANSFER_GAS_MAXIMUM, options);
const tokenContract = await this.contracts.loadERC20TokenAsync(tokenAddress);
await this.assert.token.implementsERC20(tokenContract);
const tokenTransferProxy = await this.contracts.loadTokenTransferProxyAsync();
return tokenContract.approve.sendTransactionAsync(
tokenTransferProxy.address,
allowance,
txOptions,
);
}
/**
* Asynchronously set an unlimited proxy allowance to the `tokenTransferProxy`.
*
* @param tokenAddress address of the ERC20 token.
* @param options any parameters necessary to modify the transaction.
* @return the hash of the resulting transaction.
*/
public async setUnlimitedProxyAllowanceAsync(
tokenAddress: string,
options?: TxData,
): Promise<string> {
const tokenContract = await this.contracts.loadERC20TokenAsync(tokenAddress);
await this.assert.token.implementsERC20(tokenContract);
return this.setProxyAllowanceAsync(tokenAddress, UNLIMITED_ALLOWANCE, options);
}
/**
* Eventually determines whether the allowance for the specified owner is unlimited.
*
* @param tokenAddress address of the ERC20 token.
* @param ownerAddress the owner whose allowance is being queried.
* @returns {Promise<boolean>}
*/
public async hasUnlimitedAllowance(
tokenAddress: string,
ownerAddress: string,
): Promise<boolean> {
const existingAllowance = await this.getProxyAllowanceAsync(tokenAddress, ownerAddress);
return TokenAPI.isUnlimitedAllowance(existingAllowance);
}
/**
* Asynchronously determine the allowance afforded to the
* `tokenTransferProxy` allotted by the specified owner.
*
* @param tokenAddress address of the ERC20 token.
* @param ownerAddress the owner who made the allowance allotment.
* @return the allowance allotted to the `tokenTransferProxy`.
*/
public async getProxyAllowanceAsync(
tokenAddress: string,
ownerAddress: string,
): Promise<BigNumber> {
const tokenContract = await this.contracts.loadERC20TokenAsync(tokenAddress);
await this.assert.token.implementsERC20(tokenContract);
const tokenTransferProxy = await this.contracts.loadTokenTransferProxyAsync();
return tokenContract.allowance.callAsync(ownerAddress, tokenTransferProxy.address);
}
/**
* Asynchronously retrieves the allowance allotted to the `creditorProxy` by the specified owner.
*
* @param tokenAddress address of the ERC20 token.
* @param ownerAddress the owner on whose behalf the allowance is being queried.
* @return the allowance allotted to the `creditorProxy`.
*/
public async getCreditorProxyAllowanceAsync(
tokenAddress: string,
ownerAddress: string,
): Promise<BigNumber> {
const tokenContract = await this.contracts.loadERC20TokenAsync(tokenAddress);
await this.assert.token.implementsERC20(tokenContract);
const creditorProxy = await this.contracts.loadCreditorProxyContract();
return tokenContract.allowance.callAsync(ownerAddress, creditorProxy.address);
}
/**
* Eventually determines whether the creditor proxy allowance for the specified owner is unlimited.
*
* @param tokenAddress address of the ERC20 token.
* @param ownerAddress the owner whose allowance is being queried.
* @returns {Promise<boolean>}
*/
public async hasUnlimitedCreditorProxyAllowance(
tokenAddress: string,
ownerAddress: string,
): Promise<boolean> {
const existingAllowance = await this.getCreditorProxyAllowanceAsync(
tokenAddress,
ownerAddress,
);
return TokenAPI.isUnlimitedAllowance(existingAllowance);
}
/**
* Returns a token attributes object, including symbol and name, for the token with the given
* symbol that is listed in Dharma's token registry.
*
* @returns {Promise<TokenAttributes>}
*/
public async getTokenAttributesBySymbol(symbol: string): Promise<TokenAttributes> {
const tokenRegistry = await this.contracts.loadTokenRegistry();
const [
address,
index,
name,
numDecimals,
] = await tokenRegistry.getTokenAttributesBySymbol.callAsync(symbol);
return {
address,
symbol,
name,
numDecimals,
};
}
public async getTokenSymbolByIndexAsync(index: BigNumber): Promise<string> {
const tokenRegistryContract = await this.contracts.loadTokenRegistry();
// TODO: Throw here if index is out of bounds.
return tokenRegistryContract.getTokenSymbolByIndex.callAsync(index);
}
/**
* Returns an array of token attributes, including symbol and name, for tokens that are
* listed in Dharma's token registry.
*
* @returns {Promise<TokenAttributes[]>}
*/
public async getSupportedTokens(): Promise<TokenAttributes[]> {
const tokenRegistry = await this.contracts.loadTokenRegistry();
const tokenSymbolListLength = await tokenRegistry.tokenSymbolListLength.callAsync();
const allTokens = await Promise.all(
Array.from(Array(tokenSymbolListLength.toNumber()).keys()).map(async (tokenIndex) => {
const [
address,
symbol,
name,
numDecimals,
] = await tokenRegistry.getTokenAttributesByIndex.callAsync(
new BigNumber(tokenIndex),
);
return {
address,
symbol,
name,
numDecimals,
};
}),
);
// Filter out tokens that have been disabled in dharma.js
return _.filter(allTokens, (token) => {
return !DISABLED_TOKEN_SYMBOLS.includes(token.symbol);
});
}
/**
* Asynchronously retrieve the list of symbols of the tokens in the TokenRegistry.
*
* @returns {Promise<String[]>} the list of symbols of the tokens in the TokenRegistry.
*/
public async getTokenSymbolList(): Promise<string[]> {
const tokenRegistry = await this.contracts.loadTokenRegistry();
const tokenSymbolListLength = await tokenRegistry.tokenSymbolListLength.callAsync();
const tokenSymbolList = await Promise.all(
Array.from(Array(tokenSymbolListLength.toNumber()).keys()).map((i) =>
tokenRegistry.tokenSymbolList.callAsync(new BigNumber(i)),
),
);
// Filter out tokens that have been disabled in dharma.js
return _.filter(tokenSymbolList, (tokenSymbol) => {
return !DISABLED_TOKEN_SYMBOLS.includes(tokenSymbol);
});
}
/**
* Asynchronously retrieve the number of decimal points used by the given token.
*
* @param tokenSymbol symbol of the ERC20 token.
* @return the number of decimal points used by the given token.
*/
public async getNumDecimals(tokenSymbol: string): Promise<BigNumber> {
const registry = await this.contracts.loadTokenRegistry();
await this.assert.token.exists(
tokenSymbol,
registry,
TokenAPIErrors.TOKEN_DOES_NOT_EXIST(tokenSymbol),
);
return registry.getNumDecimalsFromSymbol.callAsync(tokenSymbol);
}
} | the_stack |
import React, {RefObject} from 'react';
import {createTileData, Point, Tile, TileData} from '../../pathfinding/core/Components';
import RectGrid, {Grid} from '../../pathfinding/core/Grid';
import TileFg from './TileFg';
import SolidFg from './SolidFg';
import WeightFg from './WeightFg';
interface IProps {
tileSize: number,
width: number,
height: number,
onTilesDragged: () => void,
end: Point
}
interface IState {
grid: Grid,
initial: Point,
goal: Point,
path: Tile[]
}
const INITIAL_COLOR = 'rgb(131, 217, 52)';
const GOAL_COLOR = 'rgb(203, 75, 14)';
const ARROW_PATH_COLOR = 'rgb(73, 79, 250)';
const BASE_WIDTH = 27;
/**
* Represents actual tile contents of the Grid itself
* Will re-render itself when given a new Grid
* Binds listeners to allow user to "draw" on the grid foreground
*/
class GridForeground extends React.Component<IProps,IState>
{
private svg: RefObject<SVGSVGElement> = React.createRef();
private tilePointer: TileData;
private drawing: boolean = false;
private erasing: boolean = false;
private draggingInitial: boolean = false;
private draggingGoal: boolean = false;
private disable: boolean = false;
private doTileAnimation: boolean = true;
private initialKey: number = 0;
private goalKey: number = 0;
/**
* Constructs a GridForeground with immutable height and width
* @param props
*/
constructor(props: IProps) {
super(props);
const end = this.props.end;
this.tilePointer = createTileData(true);
this.state = {
grid: new RectGrid(this.props.width, this.props.height),
path: [],
initial: {
x: ((end.x)/3) >> 0,
y: ((end.y)/3) >> 0
},
goal: {
x: ((2*(end.x)/3) >> 0) - 1,
y: ((2*(end.y)/3) >> 0) - 1
}
}
}
componentDidUpdate(prevProps: IProps) {
if(this.props.width !== prevProps.width
|| this.props.height !== prevProps.height)
{
this.setState(prevState => ({
grid: prevState.grid.cloneNewSize(this.props.width, this.props.height)
}));
}
}
changeTile(data: TileData) {
this.tilePointer = data;
}
toggleDisable() {
this.disable = !this.disable;
}
getBoundingRect() {
return this.svg.current!.getBoundingClientRect();
}
mouseDown(e: MouseEvent) {
e.preventDefault();
const bounds = this.getBoundingRect();
this.onPress(e.clientX - bounds.left, e.clientY - bounds.top, e.button);
}
mouseUp(e: MouseEvent) {
e.preventDefault();
if(isControlKey(e.button)) {
this.draggingGoal = false;
this.draggingInitial = false;
this.drawing = false;
this.erasing = false;
}
}
mouseMove(e: MouseEvent) {
const bounds = this.getBoundingRect();
this.onDrag(e.clientX - bounds.left, e.clientY - bounds.top);
}
touchStart(e: TouchEvent) {
const touch = e.touches[0] || e.changedTouches[0];
const bounds = this.getBoundingRect();
this.onPress(touch.clientX - bounds.left, touch.clientY - bounds.top, 0);
}
touchMove(e: TouchEvent) {
const touch = e.touches[0] || e.changedTouches[0];
const bounds = this.getBoundingRect();
this.onDrag(touch.clientX - bounds.left, touch.clientY - bounds.top);
}
onEndingEvent(e: Event) {
e.preventDefault();
this.draggingGoal = false;
this.draggingInitial = false;
this.drawing = false;
this.erasing = false;
}
/**
* Responds to the event thrown at screen coordinates on press
* @param xCoordinate
* @param yCoordinate
* @param button
*/
onPress(xCoordinate: number, yCoordinate: number, button: number) {
const point = this.calculatePoint(xCoordinate,yCoordinate);
if(isControlKey(button)) {
if(pointsEqual(point, this.state.initial)) {
this.draggingInitial = true;
} else if(pointsEqual(point, this.state.goal)) {
this.draggingGoal = true;
} else if(!this.disable) {
if(this.state.grid.isEmpty(point)) {
this.drawing = true;
this.drawTile(point);
} else {
this.erasing = true;
this.eraseTile(point);
}
}
}
}
/**
* Responds to the event thrown at screen coordinates on drag/move
* @param xCoordinate
* @param yCoordinate
*/
onDrag(xCoordinate: number, yCoordinate: number) {
const point = this.calculatePoint(xCoordinate,yCoordinate);
if(this.draggingInitial) {
this.moveInitial(point);
} else if(this.draggingGoal) {
this.moveGoal(point);
} else if(!pointsEqual(point, this.state.initial)
&& !pointsEqual(point, this.state.goal) && !this.disable)
{
if(this.drawing) {
this.drawTile(point);
} else if(this.erasing) {
this.eraseTile(point);
}
}
}
/**
* Draw an entire new grid on the foreground with disabled animations
* @param grid
*/
drawGrid(grid: Grid) {
this.doTileAnimation = false;
this.setState({
grid: grid
}, () => this.doTileAnimation = true)
}
/**
* Draw tile at point
* @param point
*/
drawTile(point: Point) {
const grid = this.state.grid.clone();
if(grid.inBounds(point)) {
grid.mutateTile({
point: point,
data: this.tilePointer
});
}
this.setState({
grid: grid
});
}
/**
* Checks if a node is visualized, then changes the tile to empty if it isn't
* @param point
*/
eraseTile(point: Point) {
const grid = this.state.grid.clone();
if(grid.inBounds(point)) {
grid.mutateDefault(point, false);
}
this.setState({
grid: grid
});
}
/**
* Clear grid in state
*/
clearTiles() {
const grid = this.state.grid.clone();
for(let y = 0; y < this.state.grid.getHeight(); y++) {
for(let x = 0; x < this.state.grid.getWidth(); x++) {
const point = {
x: x, y: y
}
grid.mutateDefault(point, false);
}
}
this.setState({
grid: grid
});
}
/**
* Moves initial to a new point
* @param point
*/
moveInitial(point: Point) {
if(this.canMoveEndPoint(point)) {
this.initialKey++;
this.setState({
initial: point
}, () => this.props.onTilesDragged());
}
}
/**
* Moves goal to a new point
* @param point
*/
moveGoal(point: Point) {
if(this.canMoveEndPoint(point)) {
this.goalKey++;
this.setState({
goal: point
}, () => this.props.onTilesDragged());
}
}
/**
* Checks if we can move any of the end points (goal or initial) to that point
* @param point
*/
canMoveEndPoint(point: Point) {
return this.state.grid.inBounds(point)
&& this.state.grid.isEmpty(point)
&& !pointsEqual(this.state.initial, point)
&& !pointsEqual(this.state.goal, point)
&& !this.disable;
}
/**
* Draw a path onto the grid
* @param path
*/
drawPath(path: Tile[]) {
this.setState({
path: path.slice()
});
}
/**
* Erase path from the grid
*/
erasePath() {
this.setState({
path: []
});
}
/**
* Converts real screen x,y coordinates into
* a 2d point position on the grid
* @param xCoordinate
* @param yCoordinate
*/
calculatePoint(xCoordinate: number, yCoordinate: number) {
return {
x: Math.floor(xCoordinate/this.props.tileSize),
y: Math.floor(yCoordinate/this.props.tileSize)
}
}
resetPoints() {
this.initialKey++;
this.goalKey++;
const end = this.props.end;
this.setState({
initial: {
x: ((end.x)/3) >> 0,
y: ((end.y)/3) >> 0
},
goal: {
x: ((2*(end.x)/3) >> 0) - 1,
y: ((2*(end.y)/3) >> 0) - 1
}
});
}
/**
* Renders the end tiles (initial and goal) behind
* Path arrows are rendered on an svg canvas above the end tiles
* The tiles Grid containing the rendered tiles from the grid state is displayed on top
* it also is bound to event listeners to allow grid to be drawn/erased on
*/
render() {
return (
<div>
<div
className='endpoint-tiles-table'
>
{this.renderEndTile(this.state.initial, INITIAL_COLOR,'initial' + this.initialKey)}
{this.renderEndTile(this.state.goal, GOAL_COLOR,'goal' + this.goalKey)}
</div>
<svg
ref={this.svg}
xmlns='http://www.w3.org/2000/svg'
className='arrow-grid'
>
<defs>
<marker
id='arrowhead-path'
markerWidth='3'
markerHeight='3'
refX='0'
refY='1.5'
orient='auto'
fill={ARROW_PATH_COLOR}
>
<polygon points='0 0, 3 1.5, 0 3'/>
</marker>
</defs>
{this.renderPath()}
</svg>
<div
className='tiles-table'
onContextMenu={e => e.preventDefault()}
onMouseDown={e => this.mouseDown(e.nativeEvent)}
onMouseUp={e => this.mouseUp(e.nativeEvent)}
onMouseMove={e => this.mouseMove(e.nativeEvent)}
onMouseLeave={e => this.onEndingEvent(e.nativeEvent)}
onTouchStart={e => this.touchStart(e.nativeEvent)}
onTouchMoveCapture={e => this.touchMove(e.nativeEvent)}
onTouchEnd={e => this.onEndingEvent(e.nativeEvent)}
onTouchCancel={e => this.onEndingEvent(e.nativeEvent)}
>
{this.renderTilesGrid()}
</div>
</div>
);
}
/**
* Renders the solved path out of pathArrows between neighboring tile
* Can only be properly displayed in an svg canvas
*/
renderPath() {
const lines: JSX.Element[] = [];
for(let i = 0; i < this.state.path.length-1; i++) {
const first = this.state.path[i].point;
const second = this.state.path[i+1].point;
lines.push(this.renderPathArrow(i, first, second));
}
return lines;
}
/**
* Renders a single blue arrow between two points to make up the
* path that represents the solved path
* Can only be properly displayed in an svg canvas
*/
renderPathArrow(index: number, first: Point, second: Point) {
const width = this.props.tileSize;
const offset = width/2;
const firstX = first.x * width;
const firstY = first.y * width;
const secondX = second.x * width;
const secondY = second.y * width;
const offsetX = (secondX - firstX)/4;
const offsetY = (secondY - firstY)/4;
return (
<line
key={'path ' + index}
x1={firstX + offset + offsetX}
y1={firstY + offset + offsetY}
x2={secondX + offset - offsetX}
y2={secondY + offset - offsetY}
stroke={ARROW_PATH_COLOR}
strokeWidth={2 * this.props.tileSize/BASE_WIDTH}
className='line'
markerEnd='url(#arrowhead-path)'
/>
);
}
/**
* Iterate through the grid stored in the state and render each tile
* Solid tiles are rendered as grey squares
* Empty tiles (non solid tiles with a weight/cost of 1)
* Weighted tiles with a cost of higher than 1 are rendered with a weight png and a label
*/
renderTilesGrid() {
const tiles: JSX.Element[] = [];
for(let y = 0; y < this.state.grid.getHeight(); y++) {
for(let x = 0; x < this.state.grid.getWidth(); x++) {
const point = {
x: x, y: y
}
const cost = this.state.grid.get(point).data.pathCost;
if(this.state.grid.isSolid(point)) {
//render a solid tile div
tiles.push(
<SolidFg
key={x + ',' + y}
point={point}
tileSize={this.props.tileSize}
doTileAnimation={this.doTileAnimation}
/>
);
} else if(cost > 1) {
//render a weight svg
tiles.push(
<WeightFg
key={x + ',' + y}
point={point}
tileSize={this.props.tileSize}
doTileAnimation={this.doTileAnimation}
/>
);
//render a div containing the cost as text
tiles.push(
this.renderWeightText(
point,
cost,
x + ',' + y + ' text'
)
)
}
}
}
return tiles;
}
/**
* Renders the text (cost of the weight) to be overlay on top of the weight
* The point should be the same as the weight the text is for
* @param point
* @param cost
* @param key
*/
renderWeightText(point: Point, cost: number, key: string) {
return (
<div
key={key}
style={{
left: point.x * this.props.tileSize,
top: point.y * this.props.tileSize,
width: this.props.tileSize,
height: this.props.tileSize,
position: 'absolute',
color: 'white',
fontSize: this.props.tileSize / 2.1,
paddingTop: this.props.tileSize / 3.70,
textAlign: 'center',
cursor: 'default'
}}
>
{cost}
</div>
);
}
renderEndTile(point: Point, color: string, key: string) {
return (
<TileFg
key={key}
point={point}
tileWidth={this.props.tileSize}
color={color}
/>
);
}
}
function pointsEqual(point1: Point, point2: Point) {
return point1.x === point2.x && point1.y === point2.y;
}
function isControlKey(button: number) {
//right or left mouse
return button === 0 || button === 2;
}
export default GridForeground; | the_stack |
var selfEasyrtcid:string = "";
function wrapperForCalls():void {
easyrtc._presetMediaConstraints = { audio:true, video:true};
easyrtc.setDebugPrinter( function(message:any[]):void{
});
easyrtc.setSdpFilters(easyrtc.buildLocalSdpFilter({}), easyrtc.buildRemoteSdpFilter({}));
easyrtc.setPeerClosedListener( function(easyrtcid:string):void{
});
easyrtc.setPeerFailingListener(
function(easyrtcid:string):void{
},
function(easyrtcid:string):void{
}
);
easyrtc.setIceCandidateFilter( function(candidate:RTCIceCandidate, remotelyGenerate:boolean):RTCIceCandidate{
return candidate;
});
easyrtc.setIceConnectionStateChangeListener(function(easyrtcid:string, eventTarget:Event):void{
});
easyrtc.setSignalingStateChangeListener(function(easyrtcid:string, eventTarget:Event, signalingState:string):void{
});
let roomOccupants:string[] = easyrtc.getRoomOccupantsAsArray("some_room");
let roomMap:{[peerEasyrtcId:string]:any} = easyrtc.getRoomOccupantsAsMap("some_room");
easyrtc.setAutoInitUserMedia(true);
let formattedString = easyrtc.format("xx{1}", 3);
let eventListener =function(eventName:string, eventData:any):void{
};
easyrtc.addEventListener("roomOccupant", eventListener);
easyrtc.removeEventListener("roomOccupant", eventListener);
easyrtc.emitEvent("roomOccupant", {id:33});
let errCode:string = easyrtc.errCodes.CALL_ERR;
let apiVersion:string = easyrtc.apiVersion;
/** Regular expression pattern for user ids. This will need modification to support non US character sets */
easyrtc.usernameRegExp = /[a..z]+/;
/** Default cookieId name */
easyrtc.cookieId = "smith";
/** Flag to indicate that user is currently logging out */
let loggingOUt:boolean = easyrtc.loggingOut;
easyrtc.enableAudioReceive(true);
easyrtc.enableVideoReceive(true);
easyrtc.setAudioOutput(<HTMLVideoElement>document.getElementById("selfVideo"), "1234");
easyrtc.getAudioSinkList(function(items:MediaDeviceInfo[]):void{
});
easyrtc.getAudioSourceList(function(items:MediaDeviceInfo[]):void{
});
easyrtc.getVideoSourceList(function(items:MediaDeviceInfo[]):void{
});
let width:number = easyrtc.nativeVideoHeight;
let height:number = easyrtc.nativeVideoWidth;
let len:number = easyrtc.maxP2PMessageLength;
let isValid:boolean = easyrtc.isNameValid("some_name");
easyrtc.setCookieId("cookiemonster");
easyrtc.setVideoSource("abc123");
easyrtc.setAudioSource("abc123");
easyrtc.setVideoDims(640,480, undefined);
easyrtc.setApplicationName("roomdemo");
easyrtc.enableDebug(true);
var boolValue;
boolValue = easyrtc.supportsGetUserMedia();
boolValue = easyrtc.supportsPeerConnections();
boolValue = easyrtc.supportsDataChannels();
boolValue = easyrtc.supportsStatistics();
let peerConn:RTCPeerConnection = easyrtc.getPeerConnectionByUserId("abc");
easyrtc.getPeerStatistics("abc", function(easyrtcId:string, values:{[fieldName:string]:any;}):void{
},
easyrtc.standardStatsFilter);
easyrtc.setRoomApiField("myroom", "roomArea", 33);
easyrtc.showError(easyrtc.errCodes.DEVELOPER_ERR, "smurf attack");
let somestring:string = easyrtc.cleanId("&hello");
easyrtc.setRoomEntryListener(function(entering:boolean, roomName:string):void{
});
easyrtc.setRoomOccupantListener( function(roomName:string, occupants:Easyrtc_PerRoomData, isOwner:boolean):void{
});
easyrtc.setDataChannelOpenListener(function(easyrtcid:string):void{
});
easyrtc.setDataChannelCloseListener(function(easyrtcid:string):void{
});
let connectCount:number = easyrtc.getConnectionCount();
easyrtc.setMaxP2PMessageLength(10000);
easyrtc.enableAudio(true);
easyrtc.enableVideo(true);
easyrtc.enableDataChannels(true);
let localMediaIds:string[] = easyrtc.getLocalMediaIds();
let streamPlaceHolder:MediaStream;
easyrtc.register3rdPartyLocalMediaStream(streamPlaceHolder, "someStreamName");
let remoteName:string = easyrtc.getNameOfRemoteStream("abc", streamPlaceHolder);
easyrtc.closeLocalStream("default");
easyrtc.enableCamera(true, "default");
easyrtc.enableMicrophone(true, "default");
easyrtc.muteVideoObject( "selfVideo",true);
easyrtc.muteVideoObject( <HTMLVideoElement>document.getElementById("selfVideo"),true);
let url:string = easyrtc.getLocalStreamAsUrl("default");
streamPlaceHolder = easyrtc.getLocalStream("default");
easyrtc.clearMediaStream(<HTMLVideoElement>document.getElementById("selfvideo"));
easyrtc.setVideoObjectSrc(<HTMLVideoElement>document.getElementById("selfVideo"), streamPlaceHolder);
let trackPlaceHolder: MediaStreamTrack[] = [];
streamPlaceHolder = easyrtc.buildLocalMediaStream("default", trackPlaceHolder, trackPlaceHolder);
easyrtc.loadStylesheet();
easyrtc.initMediaSource(
function(mediaStream:MediaStream):void{},
function(errorCode:string, errorText:string):void{},
"default");
easyrtc.setAcceptChecker(function(callerEasyrtcId:string, acceptor:(acceptTheCall:boolean, mediaStreamNames:string[]) => void):void{
acceptor(true, ["default"]);
});
easyrtc.setStreamAcceptor(function(easyrtcid:string, stream:MediaStream, streamName:string):void{
// do something
});
easyrtc.setOnError(function(errorObject:{
errorCode:string;
errorText:string;
}):void{
// do something
});
easyrtc.setCallCancelled(function(easyrtcid:string, explicitlyCancelled:boolean):void{
// do something
});
easyrtc.setOnStreamClosed(function(easyrtc:string, mediaStream:MediaStream, streamName:string):void{
// do something
});
easyrtc.setPeerListener(function(easyrtcId:string, msgType:string, msgData:any, targetting:Easyrtc_MessageTargeting):void{
}, "ammessage");
easyrtc.setSocketUrl("localhost:8080", { reconnect:true});
easyrtc.setUsername("fred");
let ids:string[] = easyrtc.usernameToIds("fred", "default");
let somefield = easyrtc.getRoomApiField("kitchen", "abc123", "area");
easyrtc.setCredential("itsasecret");
easyrtc.setDisconnectListener(function():void{
});
/**
* Convert an easyrtcid to a user name. This is useful for labeling buttons and messages
* regarding peers.
* @param {String} easyrtcid
* @return {String} the username associated with the easyrtcid, or the easyrtcid if there is
* no associated username.
* @example
* console.log(easyrtcid + " is actually " + easyrtc.idToName(easyrtcid));
*/
let name:string = easyrtc.idToName("abcd");
easyrtc.setUseFreshIceEachPeerConnection(true);
let config:RTCPeerConnectionConfig = easyrtc.getServerIce();
easyrtc.setIceUsedInCalls(config);
boolValue = easyrtc.haveAudioTrack("abcd", "default");
boolValue = easyrtc.haveVideoTrack("abcd", "default");
somefield = easyrtc.getRoomField("default", "area");
easyrtc.disconnect();
easyrtc.sendDataP2P("abcd", "amessage", somefield);
easyrtc.sendDataWS("abcd", "amessage", somefield,
function(ackmsg:Easyrtc_BasicMessage):void{
// do something
});
easyrtc.sendData("abcd", "amessage", {voters:0}, function(ack:any):void{
});
easyrtc.sendPeerMessage("abcd", "amessage", somefield,
function(msgType:string, msgBody:any):void{
// do something with response
}, function(errorCode:string, errorText:string):void{
// do something with error
});
easyrtc.sendServerMessage("amessage", somefield,
function(successMessageType:string, successData:any):void{
// do something on success
}, function(errorCode:string, errText:string):void{
// do something on failure
});
/** Sends the server a request for the list of rooms the user can see.
* You must have already be connected to use this function.
* @param {function(Object)} callback - on success, this function is called with a map of the form { roomName:{"roomName":String, "numberClients": Number}}.
* The roomName appears as both the key to the map, and as the value of the "roomName" field.
* @param {function(String, String)} errorCallback is called on failure. It gets an errorCode and errorText as it's too arguments.
* @example
* easyrtc.getRoomList(
* function(roomList){
* for(roomName in roomList){
* console.log("saw room " + roomName);
* }
* },
* function(errorCode, errorText){
* easyrtc.showError(errorCode, errorText);
* }
* );
*/
easyrtc.getRoomList(function(roomNames:string[]):void{
}, function(errCode:string, errorText:string):void{
});
somestring = easyrtc.NOT_CONNECTED;
somestring = easyrtc.BECOMING_CONNECTED;
somestring = easyrtc.IS_CONNECTED;
somestring = easyrtc.getConnectStatus("abcd");
easyrtc.call("abcd",
function(easyrtcid:string, mediaType:string):void{},
function(errcode:string, errString:string):void{},
function(wasAccepted:boolean, easyrtcid:string):void{},
["default"]);
easyrtc.hangup("abcd");
/**
* Hangs up on all current connections.
* @example
* easyrtc.hangupAll();
*/
easyrtc.hangupAll();
boolValue = easyrtc.doesDataChannelWork("abcd");
streamPlaceHolder = easyrtc.getRemoteStream("abcd", "default");
easyrtc.registerLocalMediaStreamByName(streamPlaceHolder, "somename");
easyrtc.makeLocalStreamFromRemoteStream("abcd", "default", "remoteDefault");
easyrtc.addStreamToCall("abcd", "default",
function(easyrtcid:string, streamName:string):void{
});
boolValue = easyrtc.isPeerInAnyRoom("abcd");
easyrtc.updatePresence("chat", "gone for lunch");
let sessionFields:Easyrtc_RedundantMap = easyrtc.getSessionFields();
let sessionValue:any = easyrtc.getSessionField("default");
boolValue = easyrtc.isTurnServer("192.168.0.99");
boolValue = easyrtc.isStunServer("192.168.0.99");
easyrtc.getFreshIceConfig(function(sawSuccess:boolean):void{});
easyrtc.joinRoom("default", {},
function(roomName:string):void{},
function(errorCode:string, errorText:string, roomName:string):void{});
easyrtc.leaveRoom("default",
function(roomName:string):void{},
function(errorCode:string, errorText:string, roomName:string):void{});
let roomsJoined:{[key:string]:boolean} = easyrtc.getRoomsJoined();
let roomFields:Easyrtc_RedundantMap = easyrtc.getRoomFields("default");
roomFields = easyrtc.getApplicationFields();
roomFields = easyrtc.getConnectionFields();
let alreadyAllocatedSocket:any;
easyrtc.useThisSocketConnection(alreadyAllocatedSocket);
easyrtc.connect("simpleApp",
function(easyrtcid:string, roomOwner:boolean):void{},
function(errorCode:string, errorText:string):void{});
easyrtc.dontAddCloseButtons();
let ithCaller:string = easyrtc.getIthCaller(3);
let i:number = easyrtc.getSlotOfCaller("abcd");
easyrtc.easyApp("simpleApp",
"selfVideo",
["callerVideo1"],
function(easyrtcId:string):void{},
function(errorCode:string, errorText:string):void{});
easyrtc.setGotMedia(function(gotMedia:boolean, errorText:string):void{});
easyrtc.setGotConnection(function(gotConnection:boolean, errorText:string):void{});
} | the_stack |
export interface Const<T> {
readonly _const: T;
}
export interface Generic {
opaque: 'Generic is a token type that is going to be replaced with a real type';
}
export interface Unit {
opaque: 'opaque token for empty payload type';
}
export type Case<T> = Of<T> | Const<T>;
export interface RecordDict {
readonly [key: string]: Case<unknown>;
}
export type SingleDataCase = Of<[Unit]> | Const<unknown> | Of<[unknown]>;
export interface SingleDataRecordDict {
readonly [key: string]: SingleDataCase;
}
export interface ForbidDefault {
default?: never;
}
export type ForbidReservedProps = {
readonly if?: never;
readonly match?: never;
readonly matchWith?: never;
readonly T?: never;
} & ForbidDefault;
export type RequiredRecordType = RecordDict & ForbidReservedProps;
export type SingleDataRecordType = SingleDataRecordDict & ForbidReservedProps;
export interface Of<T> {
_opaque: T;
}
export interface Types {
(unit: null): Of<[Unit]>;
<T = void>(): Of<[T]>;
(g: Generic): Of<[Generic]>;
<T>(val: T): Const<T>;
<T1, T2>(): Of<[T1, T2]>;
<T1, T2, T3>(): Of<[T1, T2, T3]>;
}
export const of: Types = ((val: any) => val) as any;
// --------------------------------------------------------
export interface UnionVal<Record> {
readonly _opaqueToken: Record;
}
export interface UnionValG<P, Record> {
readonly _opaqueToken: Record;
readonly _type: P;
}
export type GenericValType<Type, Val> = Val extends UnionValG<infer _Type, infer Rec>
? UnionValG<Type, Rec>
: never;
// --------------------------------------------------------
export type Constructors<Record> = {
[T in keyof Record]: CreatorFunc<Record[T], UnionVal<Record>>;
};
export type ConstructorsG<Record> = {
[K in keyof Record]: CreatorFuncG<Record[K], Record>;
};
// --------------------------------------------------------
export type Cases<Record, Result> = {
[T in keyof Record]: MatchCaseFunc<Record[T], Result>;
};
export type CasesG<Record, Result, P> = {
[K in keyof Record]: MatchCaseFuncG<Record[K], Result, P>;
};
// --------------------------------------------------------
export type CreatorFunc<K, UVal> = K extends Of<infer A>
? A extends [void]
? () => UVal
: A extends [Unit]
? UVal
: A extends any[]
? (...p: A) => UVal
: never
: K extends Const<unknown>
? () => UVal
: never;
export type CreatorFuncG<K, Rec> = K extends Of<infer A>
? A extends [void]
? <P = never>() => UnionValG<P, Rec>
: A extends [Unit]
? <P = never>() => UnionValG<P, Rec>
: A extends [Generic]
? <P>(val: P) => UnionValG<P, Rec>
: A extends any[]
? <P = never>(...p: A) => UnionValG<P, Rec>
: never
: K extends Const<unknown>
? <P = never>() => UnionValG<P, Rec>
: never;
// --------------------------------------------------------
export type MatchCaseFunc<K, Res> = K extends Of<infer A>
? A extends [void]
? () => Res
: A extends [Unit]
? () => Res
: A extends any[]
? (...p: A) => Res
: never
: K extends Const<infer C>
? (c: C) => Res
: never;
export type MatchCaseFuncG<K, Res, P> = K extends Of<infer A>
? A extends [void]
? () => Res
: A extends [Unit]
? () => Res
: A extends [Generic]
? (val: P) => Res
: A extends any[]
? (...p: A) => Res
: never
: K extends Const<infer C>
? (c: C) => Res
: never;
// --------------------------------------------------------
export type MatchCases<Record, Result> =
| (Cases<Record, Result> & ForbidDefault)
| (Partial<Cases<Record, Result>> & {
default: (val: UnionVal<Record>) => Result;
});
export type MatchCasesG<Rec, Result, P> =
| (CasesG<Rec, Result, P> & ForbidDefault)
| (Partial<CasesG<Rec, Result, P>> & {
default: (val: UnionValG<P, Rec>) => Result;
});
// --------------------------------------------------------
export interface MatchFunc<Record> {
<Result>(cases: MatchCases<Record, Result>): (val: UnionVal<Record>) => Result;
<Result>(val: UnionVal<Record>, cases: MatchCases<Record, Result>): Result;
}
export interface MatchFuncG<Record> {
<Result, P>(cases: MatchCasesG<Record, Result, P>): (val: UnionValG<P, Record>) => Result;
<Result, P>(val: UnionValG<P, Record>, cases: MatchCasesG<Record, Result, P>): Result;
}
// --------------------------------------------------------
export type UnpackFunc<K, Rec> = K extends Of<infer A>
? A extends [void]
? {
<R>(val: UnionVal<Rec>, f: () => R): R | undefined;
<R>(val: UnionVal<Rec>, f: () => R, els: (v: UnionVal<Rec>) => R): R;
}
: A extends [Unit]
? {
<R>(val: UnionVal<Rec>, f: () => R): R | undefined;
<R>(val: UnionVal<Rec>, f: () => R, els: (v: UnionVal<Rec>) => R): R;
}
: A extends any[]
? {
<R>(val: UnionVal<Rec>, f: (...p: A) => R): R | undefined;
<R>(val: UnionVal<Rec>, f: (...p: A) => R, els: (v: UnionVal<Rec>) => R): R;
}
: never
: K extends Const<infer С>
? {
<R>(val: UnionVal<Rec>, f: (с: С) => R): R | undefined;
<R>(val: UnionVal<Rec>, f: (с: С) => R, els: (v: UnionVal<Rec>) => R): R;
}
: never;
export type UnpackFuncG<K, Rec> = K extends Of<infer A>
? A extends [void]
? {
<R, P>(val: UnionValG<P, Rec>, f: () => R): R | undefined;
<R, P>(val: UnionValG<P, Rec>, f: () => R, els: (v: UnionValG<P, Rec>) => R): R;
}
: A extends [Unit]
? {
<R, P>(val: UnionValG<P, Rec>, f: () => R): R | undefined;
<R, P>(val: UnionValG<P, Rec>, f: () => R, els: (v: UnionValG<P, Rec>) => R): R;
}
: A extends [Generic]
? {
<R, P>(val: UnionValG<P, Rec>, f: (val: P) => R): R | undefined;
<R, P>(val: UnionValG<P, Rec>, f: (val: P) => R, els: (v: UnionValG<P, Rec>) => R): R;
}
: A extends any[]
? {
<R, P>(val: UnionValG<P, Rec>, f: (...p: A) => R): R | undefined;
<R, P>(val: UnionValG<P, Rec>, f: (...p: A) => R, els: (v: UnionValG<P, Rec>) => R): R;
}
: never
: K extends Const<infer С>
? {
<R, P>(val: UnionValG<P, Rec>, f: (с: С) => R): R | undefined;
<R, P>(val: UnionValG<P, Rec>, f: (с: С) => R, els: (v: UnionValG<P, Rec>) => R): R;
}
: never;
// --------------------------------------------------------
export type Unpack<Rec> = { [K in keyof Rec]: UnpackFunc<Rec[K], Rec> };
export type UnpackG<Rec> = { [K in keyof Rec]: UnpackFuncG<Rec[K], Rec> };
// --------------------------------------------------------
type UnionDesc<Rec> = {
if: Unpack<Rec>;
T: UnionVal<Rec>;
match: MatchFunc<Rec>;
matchWith: Rec extends SingleDataRecordType
? <Other extends SingleDataRecordType, Result>(
other: UnionDesc<Other>,
matchObj: MatchCasesForTwo<Rec, Other, Result>
) => (a: UnionVal<Rec>, b: UnionVal<Other>) => Result
: never;
} & Constructors<Rec>;
export type UnionObj<Rec> = UnionDesc<Rec>;
// export type GenericUnionObj<Rec> = {
export type GenericUnionDesc<Rec> = {
match: MatchFuncG<Rec>;
if: UnpackG<Rec>;
T: UnionValG<unknown, Rec>;
} & ConstructorsG<Rec>;
// --------------------------------------------------------
// ------------- Match Two -------------
type TypeOfLeg<Leg> = Leg extends Of<infer A>
? A extends [void] | [Unit]
? void
: A extends [infer Value]
? Value
: A extends Const<infer C>
? C
: never
: never;
export type MatchCaseFuncTwo<LegA, LegB, Res> = (a: TypeOfLeg<LegA>, b: TypeOfLeg<LegB>) => Res;
export type CasesTwo<RecordA, RecordB, Result> = {
[KA in keyof RecordA]?: {
[KB in keyof RecordB]?: MatchCaseFuncTwo<RecordA[KA], RecordB[KB], Result>;
};
};
export type MatchCasesForTwo<RecordA, RecordB, Result> = CasesTwo<RecordA, RecordB, Result> & {
default: (a: UnionVal<RecordA>, b: UnionVal<RecordB>) => Result;
};
// --------------------------------------------------------
export interface UnionFunc {
<R extends RequiredRecordType>(record: R): UnionDesc<R>;
<R extends RequiredRecordType>(ctor: (g: Generic) => R): GenericUnionDesc<R>;
}
export const Union: UnionFunc = <R extends RequiredRecordType>(
recOrFunc: ((g: Generic) => R) | R
) => {
const record =
typeof recOrFunc === 'function' ? recOrFunc((undefined as unknown) as Generic) : recOrFunc;
// tslint:disable-next-line:prefer-object-spread
return Object.assign(
{
if: createUnpack(record),
match: (a: any, b?: any) => (b ? evalMatch(a, b) : (val: any) => evalMatch(val, a)),
matchWith: <Other extends SingleDataRecordType, Result>(
_other: UnionDesc<Other>, // yep, it is only used to "remember" type
matchObj: MatchCasesForTwo<R, Other, Result>
) => createMatchTupleFunction(matchObj),
},
createConstructors(record, typeof recOrFunc === 'function')
) as any;
};
const createMatchTupleFunction = <
A extends RequiredRecordType,
B extends RequiredRecordType,
Result
>(
matchObj: MatchCasesForTwo<A, B, Result>
) => {
const { default: def } = matchObj;
return function matchTuple(a: UnionVal<A>, b: UnionVal<B>): Result {
const { p0: valA, k: keyA } = (a as unknown) as Value;
const { p0: valB, k: KeyB } = (b as unknown) as Value;
if (keyA in matchObj) {
const inner = matchObj[keyA];
if (inner !== undefined && KeyB in inner) {
const matchedFunction = inner[KeyB];
if (matchedFunction !== undefined) {
return matchedFunction(valA, valB);
}
}
}
return def(a, b);
};
};
const evalMatch = <Record extends RecordDict>(
val: any,
cases: MatchCases<Record, unknown>
): any => {
// first elem is always the key
const handler = cases[getKey(val)] as any;
return handler ? invoke(val, handler) : cases.default && cases.default(val);
};
const createConstructors = <Record extends RecordDict>(
rec: Record,
isGeneric: boolean
): Constructors<Record> => {
const result: Partial<Constructors<Record>> = {};
// tslint:disable-next-line: forin
for (const key in rec) {
result[key] = createCtor(key, rec, isGeneric);
}
return result as Constructors<Record>;
};
const createCtor = <K extends keyof Record, Record extends RecordDict>(
key: K,
rec: Record,
isGeneric: boolean
): CreatorFunc<Record[K], UnionVal<Record>> => {
const val: Case<unknown> = rec[key];
// it means that it was constructed with of(null)
if (val === null) {
const frozenVal = Object.freeze(makeValue(key, undefined, undefined, undefined)) as any;
return isGeneric ? () => frozenVal : frozenVal;
}
// tslint:disable-next-line:no-if-statement
if (val !== undefined) {
const res = makeValue(key, val, undefined, undefined) as any;
return ((() => res) as any) as any;
}
return ((p0: any, p1: any, p2: any) => makeValue(key, p0, p1, p2)) as any;
};
const createUnpack = <Record extends RecordDict>(rec: Record): Unpack<Record> => {
const result: Partial<Unpack<Record>> = {};
// tslint:disable-next-line:forin
for (const key in rec) {
result[key] = createUnpackFunc(key);
}
return result as Unpack<Record>;
};
const createUnpackFunc = <K extends keyof Record, Record extends RecordDict>(
key: K
): UnpackFunc<Record[K], Record> =>
((val: any, f: (...args: any[]) => any, els?: (v: any) => any) =>
getKey(val) === key ? invoke(val, f) : els && els(val)) as any;
const makeValue = (k: any, p0: any, p1: any, p2: any): Value => ({
k,
p0,
p1,
p2,
a: arity(p0, p1, p2),
});
type Value = {
k: string;
p0: any;
p1: any;
p2: any;
a: 0 | 1 | 2 | 3;
};
const invoke = (val: Value, f: (...args: any[]) => any) => {
switch (val.a) {
case 0:
return f();
case 1:
return f(val.p0);
case 2:
return f(val.p0, val.p1);
case 3:
return f(val.p0, val.p1, val.p2);
}
};
const getKey = (val: Value) => val.k;
// const getParams = (val: any) => val.p;
const arity = (p0: any, p1: any, p2: any): 0 | 1 | 2 | 3 =>
p2 !== undefined ? 3 : p1 !== undefined ? 2 : p0 !== undefined ? 1 : 0; | the_stack |
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as models from '../models';
/**
* @class
* ServiceTopologies
* __NOTE__: An instance of this class is automatically created for an
* instance of the AzureDeploymentManager.
*/
export interface ServiceTopologies {
/**
* @summary Creates or updates a service topology.
*
* Synchronously creates a new service topology or updates an existing service
* topology.
*
* @param {object} serviceTopologyInfo Source topology object defines the
* resource.
*
* @param {string} [serviceTopologyInfo.artifactSourceId] The resource Id of
* the artifact source that contains the artifacts that can be referenced in
* the service units.
*
* @param {object} [serviceTopologyInfo.tags] Resource tags.
*
* @param {string} serviceTopologyInfo.location The geo-location where the
* resource lives
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ServiceTopologyResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(serviceTopologyInfo: models.ServiceTopologyResource, resourceGroupName: string, serviceTopologyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceTopologyResource>>;
/**
* @summary Creates or updates a service topology.
*
* Synchronously creates a new service topology or updates an existing service
* topology.
*
* @param {object} serviceTopologyInfo Source topology object defines the
* resource.
*
* @param {string} [serviceTopologyInfo.artifactSourceId] The resource Id of
* the artifact source that contains the artifacts that can be referenced in
* the service units.
*
* @param {object} [serviceTopologyInfo.tags] Resource tags.
*
* @param {string} serviceTopologyInfo.location The geo-location where the
* resource lives
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ServiceTopologyResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ServiceTopologyResource} [result] - The deserialized result object if an error did not occur.
* See {@link ServiceTopologyResource} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(serviceTopologyInfo: models.ServiceTopologyResource, resourceGroupName: string, serviceTopologyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceTopologyResource>;
createOrUpdate(serviceTopologyInfo: models.ServiceTopologyResource, resourceGroupName: string, serviceTopologyName: string, callback: ServiceCallback<models.ServiceTopologyResource>): void;
createOrUpdate(serviceTopologyInfo: models.ServiceTopologyResource, resourceGroupName: string, serviceTopologyName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceTopologyResource>): void;
/**
* @summary Gets the service topology.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ServiceTopologyResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, serviceTopologyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceTopologyResource>>;
/**
* @summary Gets the service topology.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ServiceTopologyResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ServiceTopologyResource} [result] - The deserialized result object if an error did not occur.
* See {@link ServiceTopologyResource} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, serviceTopologyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceTopologyResource>;
get(resourceGroupName: string, serviceTopologyName: string, callback: ServiceCallback<models.ServiceTopologyResource>): void;
get(resourceGroupName: string, serviceTopologyName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceTopologyResource>): void;
/**
* @summary Deletes the service topology.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, serviceTopologyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* @summary Deletes the service topology.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, serviceTopologyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, serviceTopologyName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, serviceTopologyName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
}
/**
* @class
* Services
* __NOTE__: An instance of this class is automatically created for an
* instance of the AzureDeploymentManager.
*/
export interface Services {
/**
* @summary Creates or updates a service in the service topology.
*
* Synchronously creates a new service or updates an existing service.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {string} serviceName The name of the service resource.
*
* @param {object} serviceInfo The service object
*
* @param {string} serviceInfo.targetLocation The Azure location to which the
* resources in the service belong to or should be deployed to.
*
* @param {string} serviceInfo.targetSubscriptionId The subscription to which
* the resources in the service belong to or should be deployed to.
*
* @param {object} [serviceInfo.tags] Resource tags.
*
* @param {string} serviceInfo.location The geo-location where the resource
* lives
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ServiceResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceInfo: models.ServiceResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceResource>>;
/**
* @summary Creates or updates a service in the service topology.
*
* Synchronously creates a new service or updates an existing service.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {string} serviceName The name of the service resource.
*
* @param {object} serviceInfo The service object
*
* @param {string} serviceInfo.targetLocation The Azure location to which the
* resources in the service belong to or should be deployed to.
*
* @param {string} serviceInfo.targetSubscriptionId The subscription to which
* the resources in the service belong to or should be deployed to.
*
* @param {object} [serviceInfo.tags] Resource tags.
*
* @param {string} serviceInfo.location The geo-location where the resource
* lives
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ServiceResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ServiceResource} [result] - The deserialized result object if an error did not occur.
* See {@link ServiceResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceInfo: models.ServiceResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceResource>;
createOrUpdate(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceInfo: models.ServiceResource, callback: ServiceCallback<models.ServiceResource>): void;
createOrUpdate(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceInfo: models.ServiceResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceResource>): void;
/**
* @summary Gets the service.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {string} serviceName The name of the service resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ServiceResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, serviceTopologyName: string, serviceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceResource>>;
/**
* @summary Gets the service.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {string} serviceName The name of the service resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ServiceResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ServiceResource} [result] - The deserialized result object if an error did not occur.
* See {@link ServiceResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, serviceTopologyName: string, serviceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceResource>;
get(resourceGroupName: string, serviceTopologyName: string, serviceName: string, callback: ServiceCallback<models.ServiceResource>): void;
get(resourceGroupName: string, serviceTopologyName: string, serviceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceResource>): void;
/**
* @summary Deletes the service.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {string} serviceName The name of the service resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, serviceTopologyName: string, serviceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* @summary Deletes the service.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {string} serviceName The name of the service resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, serviceTopologyName: string, serviceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, serviceTopologyName: string, serviceName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, serviceTopologyName: string, serviceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
}
/**
* @class
* ServiceUnits
* __NOTE__: An instance of this class is automatically created for an
* instance of the AzureDeploymentManager.
*/
export interface ServiceUnits {
/**
* @summary Creates or updates a service unit under the service in the service
* topology.
*
* This is an asynchronous operation and can be polled to completion using the
* operation resource returned by this operation.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {string} serviceName The name of the service resource.
*
* @param {string} serviceUnitName The name of the service unit resource.
*
* @param {object} serviceUnitInfo The service unit resource object.
*
* @param {string} serviceUnitInfo.targetResourceGroup The Azure Resource Group
* to which the resources in the service unit belong to or should be deployed
* to.
*
* @param {string} serviceUnitInfo.deploymentMode Describes the type of ARM
* deployment to be performed on the resource. Possible values include:
* 'Incremental', 'Complete'
*
* @param {object} [serviceUnitInfo.artifacts] The artifacts for the service
* unit.
*
* @param {string} [serviceUnitInfo.artifacts.templateUri] The full URI of the
* ARM template file with the SAS token.
*
* @param {string} [serviceUnitInfo.artifacts.parametersUri] The full URI of
* the ARM parameters file with the SAS token.
*
* @param {string}
* [serviceUnitInfo.artifacts.templateArtifactSourceRelativePath] The path to
* the ARM template file relative to the artifact source.
*
* @param {string}
* [serviceUnitInfo.artifacts.parametersArtifactSourceRelativePath] The path to
* the ARM parameters file relative to the artifact source.
*
* @param {object} [serviceUnitInfo.tags] Resource tags.
*
* @param {string} serviceUnitInfo.location The geo-location where the resource
* lives
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ServiceUnitResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, serviceUnitInfo: models.ServiceUnitResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceUnitResource>>;
/**
* @summary Creates or updates a service unit under the service in the service
* topology.
*
* This is an asynchronous operation and can be polled to completion using the
* operation resource returned by this operation.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {string} serviceName The name of the service resource.
*
* @param {string} serviceUnitName The name of the service unit resource.
*
* @param {object} serviceUnitInfo The service unit resource object.
*
* @param {string} serviceUnitInfo.targetResourceGroup The Azure Resource Group
* to which the resources in the service unit belong to or should be deployed
* to.
*
* @param {string} serviceUnitInfo.deploymentMode Describes the type of ARM
* deployment to be performed on the resource. Possible values include:
* 'Incremental', 'Complete'
*
* @param {object} [serviceUnitInfo.artifacts] The artifacts for the service
* unit.
*
* @param {string} [serviceUnitInfo.artifacts.templateUri] The full URI of the
* ARM template file with the SAS token.
*
* @param {string} [serviceUnitInfo.artifacts.parametersUri] The full URI of
* the ARM parameters file with the SAS token.
*
* @param {string}
* [serviceUnitInfo.artifacts.templateArtifactSourceRelativePath] The path to
* the ARM template file relative to the artifact source.
*
* @param {string}
* [serviceUnitInfo.artifacts.parametersArtifactSourceRelativePath] The path to
* the ARM parameters file relative to the artifact source.
*
* @param {object} [serviceUnitInfo.tags] Resource tags.
*
* @param {string} serviceUnitInfo.location The geo-location where the resource
* lives
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ServiceUnitResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ServiceUnitResource} [result] - The deserialized result object if an error did not occur.
* See {@link ServiceUnitResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, serviceUnitInfo: models.ServiceUnitResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceUnitResource>;
createOrUpdate(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, serviceUnitInfo: models.ServiceUnitResource, callback: ServiceCallback<models.ServiceUnitResource>): void;
createOrUpdate(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, serviceUnitInfo: models.ServiceUnitResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceUnitResource>): void;
/**
* @summary Gets the service unit.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {string} serviceName The name of the service resource.
*
* @param {string} serviceUnitName The name of the service unit resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ServiceUnitResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceUnitResource>>;
/**
* @summary Gets the service unit.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {string} serviceName The name of the service resource.
*
* @param {string} serviceUnitName The name of the service unit resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ServiceUnitResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ServiceUnitResource} [result] - The deserialized result object if an error did not occur.
* See {@link ServiceUnitResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceUnitResource>;
get(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, callback: ServiceCallback<models.ServiceUnitResource>): void;
get(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceUnitResource>): void;
/**
* @summary Deletes the service unit.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {string} serviceName The name of the service resource.
*
* @param {string} serviceUnitName The name of the service unit resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* @summary Deletes the service unit.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {string} serviceName The name of the service resource.
*
* @param {string} serviceUnitName The name of the service unit resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* @summary Creates or updates a service unit under the service in the service
* topology.
*
* This is an asynchronous operation and can be polled to completion using the
* operation resource returned by this operation.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {string} serviceName The name of the service resource.
*
* @param {string} serviceUnitName The name of the service unit resource.
*
* @param {object} serviceUnitInfo The service unit resource object.
*
* @param {string} serviceUnitInfo.targetResourceGroup The Azure Resource Group
* to which the resources in the service unit belong to or should be deployed
* to.
*
* @param {string} serviceUnitInfo.deploymentMode Describes the type of ARM
* deployment to be performed on the resource. Possible values include:
* 'Incremental', 'Complete'
*
* @param {object} [serviceUnitInfo.artifacts] The artifacts for the service
* unit.
*
* @param {string} [serviceUnitInfo.artifacts.templateUri] The full URI of the
* ARM template file with the SAS token.
*
* @param {string} [serviceUnitInfo.artifacts.parametersUri] The full URI of
* the ARM parameters file with the SAS token.
*
* @param {string}
* [serviceUnitInfo.artifacts.templateArtifactSourceRelativePath] The path to
* the ARM template file relative to the artifact source.
*
* @param {string}
* [serviceUnitInfo.artifacts.parametersArtifactSourceRelativePath] The path to
* the ARM parameters file relative to the artifact source.
*
* @param {object} [serviceUnitInfo.tags] Resource tags.
*
* @param {string} serviceUnitInfo.location The geo-location where the resource
* lives
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ServiceUnitResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
beginCreateOrUpdateWithHttpOperationResponse(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, serviceUnitInfo: models.ServiceUnitResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceUnitResource>>;
/**
* @summary Creates or updates a service unit under the service in the service
* topology.
*
* This is an asynchronous operation and can be polled to completion using the
* operation resource returned by this operation.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} serviceTopologyName The name of the service topology .
*
* @param {string} serviceName The name of the service resource.
*
* @param {string} serviceUnitName The name of the service unit resource.
*
* @param {object} serviceUnitInfo The service unit resource object.
*
* @param {string} serviceUnitInfo.targetResourceGroup The Azure Resource Group
* to which the resources in the service unit belong to or should be deployed
* to.
*
* @param {string} serviceUnitInfo.deploymentMode Describes the type of ARM
* deployment to be performed on the resource. Possible values include:
* 'Incremental', 'Complete'
*
* @param {object} [serviceUnitInfo.artifacts] The artifacts for the service
* unit.
*
* @param {string} [serviceUnitInfo.artifacts.templateUri] The full URI of the
* ARM template file with the SAS token.
*
* @param {string} [serviceUnitInfo.artifacts.parametersUri] The full URI of
* the ARM parameters file with the SAS token.
*
* @param {string}
* [serviceUnitInfo.artifacts.templateArtifactSourceRelativePath] The path to
* the ARM template file relative to the artifact source.
*
* @param {string}
* [serviceUnitInfo.artifacts.parametersArtifactSourceRelativePath] The path to
* the ARM parameters file relative to the artifact source.
*
* @param {object} [serviceUnitInfo.tags] Resource tags.
*
* @param {string} serviceUnitInfo.location The geo-location where the resource
* lives
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ServiceUnitResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ServiceUnitResource} [result] - The deserialized result object if an error did not occur.
* See {@link ServiceUnitResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
beginCreateOrUpdate(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, serviceUnitInfo: models.ServiceUnitResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceUnitResource>;
beginCreateOrUpdate(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, serviceUnitInfo: models.ServiceUnitResource, callback: ServiceCallback<models.ServiceUnitResource>): void;
beginCreateOrUpdate(resourceGroupName: string, serviceTopologyName: string, serviceName: string, serviceUnitName: string, serviceUnitInfo: models.ServiceUnitResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceUnitResource>): void;
}
/**
* @class
* Steps
* __NOTE__: An instance of this class is automatically created for an
* instance of the AzureDeploymentManager.
*/
export interface Steps {
/**
* @summary Creates or updates a rollout step with the given step properties.
*
* Synchronously creates a new step or updates an existing step.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} stepName The name of the deployment step.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.stepInfo] The step object.
*
* @param {object} options.stepInfo.properties The properties that define the
* step.
*
* @param {string} options.stepInfo.properties.stepType Polymorphic
* Discriminator
*
* @param {object} [options.stepInfo.tags] Resource tags.
*
* @param {string} options.stepInfo.location The geo-location where the
* resource lives
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<StepResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, stepName: string, options?: { stepInfo? : models.StepResource, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StepResource>>;
/**
* @summary Creates or updates a rollout step with the given step properties.
*
* Synchronously creates a new step or updates an existing step.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} stepName The name of the deployment step.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.stepInfo] The step object.
*
* @param {object} options.stepInfo.properties The properties that define the
* step.
*
* @param {string} options.stepInfo.properties.stepType Polymorphic
* Discriminator
*
* @param {object} [options.stepInfo.tags] Resource tags.
*
* @param {string} options.stepInfo.location The geo-location where the
* resource lives
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {StepResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {StepResource} [result] - The deserialized result object if an error did not occur.
* See {@link StepResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, stepName: string, options?: { stepInfo? : models.StepResource, customHeaders? : { [headerName: string]: string; } }): Promise<models.StepResource>;
createOrUpdate(resourceGroupName: string, stepName: string, callback: ServiceCallback<models.StepResource>): void;
createOrUpdate(resourceGroupName: string, stepName: string, options: { stepInfo? : models.StepResource, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StepResource>): void;
/**
* @summary Gets the step.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} stepName The name of the deployment step.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<StepResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, stepName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.StepResource>>;
/**
* @summary Gets the step.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} stepName The name of the deployment step.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {StepResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {StepResource} [result] - The deserialized result object if an error did not occur.
* See {@link StepResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, stepName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.StepResource>;
get(resourceGroupName: string, stepName: string, callback: ServiceCallback<models.StepResource>): void;
get(resourceGroupName: string, stepName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.StepResource>): void;
/**
* @summary Deletes the step.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} stepName The name of the deployment step.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, stepName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* @summary Deletes the step.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} stepName The name of the deployment step.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, stepName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, stepName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, stepName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
}
/**
* @class
* Rollouts
* __NOTE__: An instance of this class is automatically created for an
* instance of the AzureDeploymentManager.
*/
export interface Rollouts {
/**
* @summary Creates or updates a rollout.
*
* This is an asynchronous operation and can be polled to completion using the
* location header returned by this operation.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} rolloutName The rollout name.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.rolloutRequest] Source rollout request object that
* defines the rollout.
*
* @param {object} options.rolloutRequest.identity Identity for the resource.
*
* @param {string} options.rolloutRequest.identity.type The identity type.
*
* @param {array} options.rolloutRequest.identity.identityIds The list of
* identities.
*
* @param {string} options.rolloutRequest.buildVersion The version of the build
* being deployed.
*
* @param {string} [options.rolloutRequest.artifactSourceId] The reference to
* the artifact source resource Id where the payload is located.
*
* @param {string} options.rolloutRequest.targetServiceTopologyId The resource
* Id of the service topology from which service units are being referenced in
* step groups to be deployed.
*
* @param {array} options.rolloutRequest.stepGroups The list of step groups
* that define the orchestration.
*
* @param {object} [options.rolloutRequest.tags] Resource tags.
*
* @param {string} options.rolloutRequest.location The geo-location where the
* resource lives
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<RolloutRequest>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, rolloutName: string, options?: { rolloutRequest? : models.RolloutRequest, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RolloutRequest>>;
/**
* @summary Creates or updates a rollout.
*
* This is an asynchronous operation and can be polled to completion using the
* location header returned by this operation.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} rolloutName The rollout name.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.rolloutRequest] Source rollout request object that
* defines the rollout.
*
* @param {object} options.rolloutRequest.identity Identity for the resource.
*
* @param {string} options.rolloutRequest.identity.type The identity type.
*
* @param {array} options.rolloutRequest.identity.identityIds The list of
* identities.
*
* @param {string} options.rolloutRequest.buildVersion The version of the build
* being deployed.
*
* @param {string} [options.rolloutRequest.artifactSourceId] The reference to
* the artifact source resource Id where the payload is located.
*
* @param {string} options.rolloutRequest.targetServiceTopologyId The resource
* Id of the service topology from which service units are being referenced in
* step groups to be deployed.
*
* @param {array} options.rolloutRequest.stepGroups The list of step groups
* that define the orchestration.
*
* @param {object} [options.rolloutRequest.tags] Resource tags.
*
* @param {string} options.rolloutRequest.location The geo-location where the
* resource lives
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {RolloutRequest} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {RolloutRequest} [result] - The deserialized result object if an error did not occur.
* See {@link RolloutRequest} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, rolloutName: string, options?: { rolloutRequest? : models.RolloutRequest, customHeaders? : { [headerName: string]: string; } }): Promise<models.RolloutRequest>;
createOrUpdate(resourceGroupName: string, rolloutName: string, callback: ServiceCallback<models.RolloutRequest>): void;
createOrUpdate(resourceGroupName: string, rolloutName: string, options: { rolloutRequest? : models.RolloutRequest, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RolloutRequest>): void;
/**
* @summary Gets detailed information of a rollout.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} rolloutName The rollout name.
*
* @param {object} [options] Optional Parameters.
*
* @param {number} [options.retryAttempt] Rollout retry attempt ordinal to get
* the result of. If not specified, result of the latest attempt will be
* returned.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Rollout>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, rolloutName: string, options?: { retryAttempt? : number, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Rollout>>;
/**
* @summary Gets detailed information of a rollout.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} rolloutName The rollout name.
*
* @param {object} [options] Optional Parameters.
*
* @param {number} [options.retryAttempt] Rollout retry attempt ordinal to get
* the result of. If not specified, result of the latest attempt will be
* returned.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Rollout} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Rollout} [result] - The deserialized result object if an error did not occur.
* See {@link Rollout} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, rolloutName: string, options?: { retryAttempt? : number, customHeaders? : { [headerName: string]: string; } }): Promise<models.Rollout>;
get(resourceGroupName: string, rolloutName: string, callback: ServiceCallback<models.Rollout>): void;
get(resourceGroupName: string, rolloutName: string, options: { retryAttempt? : number, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Rollout>): void;
/**
* @summary Deletes a rollout resource.
*
* Only rollouts in terminal state can be deleted.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} rolloutName The rollout name.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, rolloutName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* @summary Deletes a rollout resource.
*
* Only rollouts in terminal state can be deleted.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} rolloutName The rollout name.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, rolloutName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, rolloutName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, rolloutName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* @summary Stops a running rollout.
*
* Only running rollouts can be canceled.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} rolloutName The rollout name.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Rollout>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
cancelWithHttpOperationResponse(resourceGroupName: string, rolloutName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Rollout>>;
/**
* @summary Stops a running rollout.
*
* Only running rollouts can be canceled.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} rolloutName The rollout name.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Rollout} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Rollout} [result] - The deserialized result object if an error did not occur.
* See {@link Rollout} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
cancel(resourceGroupName: string, rolloutName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Rollout>;
cancel(resourceGroupName: string, rolloutName: string, callback: ServiceCallback<models.Rollout>): void;
cancel(resourceGroupName: string, rolloutName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Rollout>): void;
/**
* @summary Restarts a failed rollout and optionally skips all succeeded steps.
*
* Only failed rollouts can be restarted.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} rolloutName The rollout name.
*
* @param {object} [options] Optional Parameters.
*
* @param {boolean} [options.skipSucceeded] If true, will skip all succeeded
* steps so far in the rollout. If false, will execute the entire rollout again
* regardless of the current state of individual resources. Defaults to false
* if not specified.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Rollout>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
restartWithHttpOperationResponse(resourceGroupName: string, rolloutName: string, options?: { skipSucceeded? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Rollout>>;
/**
* @summary Restarts a failed rollout and optionally skips all succeeded steps.
*
* Only failed rollouts can be restarted.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} rolloutName The rollout name.
*
* @param {object} [options] Optional Parameters.
*
* @param {boolean} [options.skipSucceeded] If true, will skip all succeeded
* steps so far in the rollout. If false, will execute the entire rollout again
* regardless of the current state of individual resources. Defaults to false
* if not specified.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Rollout} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Rollout} [result] - The deserialized result object if an error did not occur.
* See {@link Rollout} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
restart(resourceGroupName: string, rolloutName: string, options?: { skipSucceeded? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.Rollout>;
restart(resourceGroupName: string, rolloutName: string, callback: ServiceCallback<models.Rollout>): void;
restart(resourceGroupName: string, rolloutName: string, options: { skipSucceeded? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Rollout>): void;
/**
* @summary Creates or updates a rollout.
*
* This is an asynchronous operation and can be polled to completion using the
* location header returned by this operation.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} rolloutName The rollout name.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.rolloutRequest] Source rollout request object that
* defines the rollout.
*
* @param {object} options.rolloutRequest.identity Identity for the resource.
*
* @param {string} options.rolloutRequest.identity.type The identity type.
*
* @param {array} options.rolloutRequest.identity.identityIds The list of
* identities.
*
* @param {string} options.rolloutRequest.buildVersion The version of the build
* being deployed.
*
* @param {string} [options.rolloutRequest.artifactSourceId] The reference to
* the artifact source resource Id where the payload is located.
*
* @param {string} options.rolloutRequest.targetServiceTopologyId The resource
* Id of the service topology from which service units are being referenced in
* step groups to be deployed.
*
* @param {array} options.rolloutRequest.stepGroups The list of step groups
* that define the orchestration.
*
* @param {object} [options.rolloutRequest.tags] Resource tags.
*
* @param {string} options.rolloutRequest.location The geo-location where the
* resource lives
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<RolloutRequest>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
beginCreateOrUpdateWithHttpOperationResponse(resourceGroupName: string, rolloutName: string, options?: { rolloutRequest? : models.RolloutRequest, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RolloutRequest>>;
/**
* @summary Creates or updates a rollout.
*
* This is an asynchronous operation and can be polled to completion using the
* location header returned by this operation.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} rolloutName The rollout name.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.rolloutRequest] Source rollout request object that
* defines the rollout.
*
* @param {object} options.rolloutRequest.identity Identity for the resource.
*
* @param {string} options.rolloutRequest.identity.type The identity type.
*
* @param {array} options.rolloutRequest.identity.identityIds The list of
* identities.
*
* @param {string} options.rolloutRequest.buildVersion The version of the build
* being deployed.
*
* @param {string} [options.rolloutRequest.artifactSourceId] The reference to
* the artifact source resource Id where the payload is located.
*
* @param {string} options.rolloutRequest.targetServiceTopologyId The resource
* Id of the service topology from which service units are being referenced in
* step groups to be deployed.
*
* @param {array} options.rolloutRequest.stepGroups The list of step groups
* that define the orchestration.
*
* @param {object} [options.rolloutRequest.tags] Resource tags.
*
* @param {string} options.rolloutRequest.location The geo-location where the
* resource lives
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {RolloutRequest} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {RolloutRequest} [result] - The deserialized result object if an error did not occur.
* See {@link RolloutRequest} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
beginCreateOrUpdate(resourceGroupName: string, rolloutName: string, options?: { rolloutRequest? : models.RolloutRequest, customHeaders? : { [headerName: string]: string; } }): Promise<models.RolloutRequest>;
beginCreateOrUpdate(resourceGroupName: string, rolloutName: string, callback: ServiceCallback<models.RolloutRequest>): void;
beginCreateOrUpdate(resourceGroupName: string, rolloutName: string, options: { rolloutRequest? : models.RolloutRequest, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RolloutRequest>): void;
}
/**
* @class
* ArtifactSources
* __NOTE__: An instance of this class is automatically created for an
* instance of the AzureDeploymentManager.
*/
export interface ArtifactSources {
/**
* @summary Creates or updates an artifact source.
*
* Synchronously creates a new artifact source or updates an existing artifact
* source.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} artifactSourceName The name of the artifact source.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.artifactSourceInfo] Source object that defines the
* resource.
*
* @param {string} options.artifactSourceInfo.sourceType The type of artifact
* source used.
*
* @param {string} [options.artifactSourceInfo.artifactRoot] The path from the
* location that the 'authentication' property [say, a SAS URI to the blob
* container] refers to, to the location of the artifacts. This can be used to
* differentiate different versions of the artifacts. Or, different types of
* artifacts like binaries or templates. The location referenced by the
* authentication property concatenated with this optional artifactRoot path
* forms the artifact source location where the artifacts are expected to be
* found.
*
* @param {object} options.artifactSourceInfo.authentication The authentication
* method to use to access the artifact source.
*
* @param {string} options.artifactSourceInfo.authentication.type Polymorphic
* Discriminator
*
* @param {object} [options.artifactSourceInfo.tags] Resource tags.
*
* @param {string} options.artifactSourceInfo.location The geo-location where
* the resource lives
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ArtifactSource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, artifactSourceName: string, options?: { artifactSourceInfo? : models.ArtifactSource, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ArtifactSource>>;
/**
* @summary Creates or updates an artifact source.
*
* Synchronously creates a new artifact source or updates an existing artifact
* source.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} artifactSourceName The name of the artifact source.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.artifactSourceInfo] Source object that defines the
* resource.
*
* @param {string} options.artifactSourceInfo.sourceType The type of artifact
* source used.
*
* @param {string} [options.artifactSourceInfo.artifactRoot] The path from the
* location that the 'authentication' property [say, a SAS URI to the blob
* container] refers to, to the location of the artifacts. This can be used to
* differentiate different versions of the artifacts. Or, different types of
* artifacts like binaries or templates. The location referenced by the
* authentication property concatenated with this optional artifactRoot path
* forms the artifact source location where the artifacts are expected to be
* found.
*
* @param {object} options.artifactSourceInfo.authentication The authentication
* method to use to access the artifact source.
*
* @param {string} options.artifactSourceInfo.authentication.type Polymorphic
* Discriminator
*
* @param {object} [options.artifactSourceInfo.tags] Resource tags.
*
* @param {string} options.artifactSourceInfo.location The geo-location where
* the resource lives
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ArtifactSource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ArtifactSource} [result] - The deserialized result object if an error did not occur.
* See {@link ArtifactSource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, artifactSourceName: string, options?: { artifactSourceInfo? : models.ArtifactSource, customHeaders? : { [headerName: string]: string; } }): Promise<models.ArtifactSource>;
createOrUpdate(resourceGroupName: string, artifactSourceName: string, callback: ServiceCallback<models.ArtifactSource>): void;
createOrUpdate(resourceGroupName: string, artifactSourceName: string, options: { artifactSourceInfo? : models.ArtifactSource, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ArtifactSource>): void;
/**
* @summary Gets an artifact source.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} artifactSourceName The name of the artifact source.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ArtifactSource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, artifactSourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ArtifactSource>>;
/**
* @summary Gets an artifact source.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} artifactSourceName The name of the artifact source.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ArtifactSource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ArtifactSource} [result] - The deserialized result object if an error did not occur.
* See {@link ArtifactSource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, artifactSourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ArtifactSource>;
get(resourceGroupName: string, artifactSourceName: string, callback: ServiceCallback<models.ArtifactSource>): void;
get(resourceGroupName: string, artifactSourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ArtifactSource>): void;
/**
* @summary Deletes an artifact source.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} artifactSourceName The name of the artifact source.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, artifactSourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* @summary Deletes an artifact source.
*
* @param {string} resourceGroupName The name of the resource group. The name
* is case insensitive.
*
* @param {string} artifactSourceName The name of the artifact source.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, artifactSourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, artifactSourceName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, artifactSourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
}
/**
* @class
* Operations
* __NOTE__: An instance of this class is automatically created for an
* instance of the AzureDeploymentManager.
*/
export interface Operations {
/**
* @summary Gets an operation resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Array>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Operation[]>>;
/**
* @summary Gets an operation resource.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Array} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Array} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Operation[]>;
get(callback: ServiceCallback<models.Operation[]>): void;
get(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Operation[]>): void;
} | the_stack |
import * as assert from 'assert';
import { color, hsl, hsla, rgb, rgba } from '../src/color';
const cyan = rgb(0, 255, 255);
const blue = rgb(0, 0, 255);
const green = rgb(0, 128, 0);
const maroon = rgb(128, 0, 0);
const black = rgb(0, 0, 0);
const white = rgb(255, 255, 255);
const red = rgb(255, 0, 0);
const transparent = rgba(0, 0, 0, 0);
const purple = rgb(128, 0, 128);
describe('color', () => {
describe('toString()', () => {
it('handles named colors', () => {
const c1 = red.toString();
assert.equal(c1, 'rgb(255, 0, 0)');
});
it('handles transparency', () => {
const c1 = transparent.toString();
assert.equal(c1, 'rgba(0, 0, 0, 0)');
});
it('truncates alpha channel values to the 5th decimal', () => {
const c1 = rgba(255, 242, 216, 0.49);
assert.equal(c1.toString(), 'rgba(255, 242, 216, 0.49)');
});
it('truncates alpha channel repeating values to the 5th decimal', () => {
const c1 = rgba(255, 242, 216, 1 / 3);
assert.equal(c1.toString(), 'rgba(255, 242, 216, 0.33333)');
});
});
describe('rgb()', () => {
it('handles rgb with numbers', () => {
const color = rgb(255, 0, 0).toString();
assert.equal(color, 'rgb(255, 0, 0)');
});
it('rounds channels to the nearest integer', () => {
const color = rgb(100.5, 100.3, -1).toString();
assert.equal(color, 'rgb(101, 100, 0)');
});
it('uses the alpha channel if specified.', () => {
const color = rgb(255, 0, 0, 0.5).toString();
assert.equal(color, 'rgba(255, 0, 0, 0.5)');
});
});
describe('rgba()', () => {
it('handles rgba with numbers', () => {
const color = rgba(255, 0, 0, 1).toString();
assert.equal(color, 'rgba(255, 0, 0, 1)');
});
it('handles rgba with percent string', () => {
const color = rgba(255, 0, 0, '80%').toString();
assert.equal(color, 'rgba(255, 0, 0, 0.8)');
});
it('rounds channels to the nearest integer', () => {
const color = rgba(100.5, 100.3, -1, 0.5).toString();
assert.equal(color, 'rgba(101, 100, 0, 0.5)');
});
});
describe('hsl()', () => {
it('handles negative hues', () => {
const color1 = hsl(-180, 1, 0.5).toString();
const color2 = hsl(180, 1, 0.5).toString();
assert.equal(color1, color2);
});
it('handles out of range hues', () => {
const color1 = hsl(90, 1, 0.5).toString();
const color2 = hsl(360 + 90, 1, 0.5).toString();
const color3 = hsl(-360 - 270, 1, 0.5).toString();
assert.equal(color1, color2);
assert.equal(color1, color3);
});
it('handles hsl with percent strings', () => {
const color = hsl(0, '100%', '50%').toString();
assert.equal(color, 'hsl(0, 100%, 50%)');
});
it('handles hsl with percent numbers', () => {
const color = hsl(0, 1, 0.5).toString();
assert.equal(color, 'hsl(0, 100%, 50%)');
});
it('rounds hue to the nearest integer', () => {
const color = hsl(100.5, 0.5, 0.5).toString();
assert.equal(color, 'hsl(101, 50%, 50%)');
});
it('uses the alpha channel if specified.', () => {
const color = hsl(100.5, 0.5, 0.5, 0.5).toString();
assert.equal(color, 'hsla(101, 50%, 50%, 0.5)');
});
});
describe('hsla()', () => {
it('handles hsla with percent numbers', () => {
const color = hsla(0, 1, 0.5, 0.1).toString();
assert.equal(color, 'hsla(0, 100%, 50%, 0.1)');
});
it('handles hsla with percent strings', () => {
const color = hsla(0, '100%', '50%', 0.1).toString();
assert.equal(color, 'hsla(0, 100%, 50%, 0.1)');
});
it('rounds hue to the nearest integer', () => {
const color = hsla(100.5, 0.5, 0.5, 0).toString();
assert.equal(color, 'hsla(101, 50%, 50%, 0)');
});
});
it('converts from a named color to rgb', () => {
const color1 = red.toString();
const color2 = rgb(255, 0, 0).toString();
assert.equal(color1, color2);
});
describe('color()', () => {
it('converts from a hex color (3 digit) to rgb', () => {
const color1 = color('#FF0000').toString();
const color2 = rgb(255, 0, 0).toString();
assert.equal(color1, color2);
});
it('converts from a hex color (6 digit) to rgb', () => {
const color1 = color('#F00').toString();
const color2 = rgb(255, 0, 0).toString();
assert.equal(color1, color2);
});
it('converts from a rgb color', () => {
const color1 = color('rgb(255,0,0)').toString();
const color2 = rgb(255, 0, 0).toString();
assert.equal(color1, color2);
});
it('converts from a rgba color', () => {
const color1 = color('rgba(0,0,255,.1)').toString();
const color2 = rgba(0, 0, 255, 0.1).toString();
assert.equal(color1, color2);
});
it('converts from a hsl color', () => {
const color1 = color('hsl(345,100%,5%)').toString();
const color2 = hsl(345, 1, 0.05).toString();
assert.equal(color1, color2);
});
it('converts from a hsla color', () => {
const color1 = color('hsla(10, 10%, 60%, .85)').toString();
const color2 = hsla(10, 0.1, 0.6, 0.85).toString();
assert.equal(color1, color2);
});
});
describe('toHexString()', () => {
it('converts white to #FFFFFF', () => {
const color = white.toHexString();
assert.equal(color, '#FFFFFF');
});
it('converts black to #000000', () => {
const color = black.toHexString();
assert.equal(color, '#000000');
});
it('converts red to #FF0000', () => {
const color = red.toHexString();
assert.equal(color, '#FF0000');
});
it('converts green to #008000', () => {
const color = green.toHexString();
assert.equal(color, '#008000');
});
it('converts blue to #0000FF', () => {
const color = blue.toHexString();
assert.equal(color, '#0000FF');
});
it('converts rgb(0, 127.5, 0) to #009900', () => {
const color = rgb(0, 127.5, 0).toHexString();
assert.equal(color, '#008000');
});
it('converts to a # and a six digit hex code', () => {
const c = color('#16A085')
.darken('10%')
.toHexString();
assert.equal(c.length, 7);
});
});
describe('toHSL()', () => {
it('converts from a named color to hsl', () => {
const color1 = red.toHSL().toString();
const color2 = hsl(0, 1, 0.5).toString();
assert.equal(color1, color2);
});
it('converts from rgb to hsl', () => {
const color1 = rgb(255, 0, 0)
.toHSL()
.toString();
const color2 = hsl(0, 1, 0.5).toString();
assert.equal(color1, color2);
});
});
describe('toHSLA()', () => {
it('converts from a named color to hsla', () => {
const color1 = red.toHSLA().toString();
const color2 = hsla(0, 1, 0.5, 1).toString();
assert.equal(color1, color2);
});
it('converts from rgb to hsla', () => {
const color1 = rgb(255, 0, 0)
.toHSLA()
.toString();
const color2 = hsla(0, 1, 0.5, 1).toString();
assert.equal(color1, color2);
});
it('converts from rgba to hsla', () => {
const color1 = rgba(255, 0, 0, 0.5)
.toHSLA()
.toString();
const color2 = hsla(0, 1, 0.5, 0.5).toString();
assert.equal(color1, color2);
});
});
describe('toRGB()', () => {
it('converts from a named color to rgba', () => {
const color1 = red.toRGBA().toString();
const color2 = rgba(255, 0, 0, 1).toString();
assert.equal(color1, color2);
});
it('converts from hsl to rgb', () => {
const color1 = hsl(0, 1, 0.5)
.toRGB()
.toString();
const color2 = rgb(255, 0, 0).toString();
assert.equal(color1, color2);
});
it('converts from hsla to rgb', () => {
const color1 = hsla(0, 1, 0.5, 0.5)
.toRGB()
.toString();
const color2 = rgb(255, 0, 0).toString();
assert.equal(color1, color2);
});
});
describe('toRGBA()', () => {
it('converts from hsla to rgba', () => {
const color1 = hsla(0, 1, 0.5, 0.5)
.toRGBA()
.toString();
const color2 = rgba(255, 0, 0, 0.5).toString();
assert.equal(color1, color2);
});
});
describe('red()', () => {
it('returns the red channel from rgb', () => {
const color1 = rgb(255, 0, 0);
assert.equal(255, color1.red());
});
it('returns the red channel from rgba', () => {
const color1 = rgba(255, 0, 0, 0.5);
assert.equal(255, color1.red());
});
});
describe('green()', () => {
it('returns the green channel from rgb', () => {
const color1 = rgb(0, 255, 0);
assert.equal(255, color1.green());
});
it('returns the green channel from rgba', () => {
const color1 = rgba(0, 255, 0, 0.5);
assert.equal(255, color1.green());
});
});
describe('blue()', () => {
it('returns the blue channel from rgb', () => {
const color1 = rgb(0, 0, 255);
assert.equal(255, color1.blue());
});
it('returns the blue channel from rgba', () => {
const color1 = rgba(0, 0, 255, 0.5);
assert.equal(255, color1.blue());
});
});
describe('opacity()', () => {
it('returns the alpha channel from rgb', () => {
const color1 = rgb(0, 0, 0);
assert.equal(1, color1.alpha());
assert.equal(1, color1.opacity());
});
it('returns the alpha channel from rgba', () => {
const color1 = rgba(0, 0, 0, 0.5);
assert.equal(0.5, color1.alpha());
assert.equal(0.5, color1.opacity());
});
});
describe('invert()', () => {
it('inverts rgb', () => {
const color1 = rgb(255, 0, 0)
.invert()
.toString();
const color2 = cyan.toString();
assert.equal(color1, color2);
});
it('inverts rgba', () => {
const color1 = rgba(255, 0, 0, 0.5)
.invert()
.toString();
const color2 = cyan.fade(0.5).toString();
assert.equal(color1, color2);
});
it('inverts hsl', () => {
const color1 = hsl(0, 1, 0.5)
.invert()
.toString();
const color2 = cyan.toHSL().toString();
assert.equal(color1, color2);
});
it('inverts hsla', () => {
const color1 = hsla(0, 1, 0.5, 1)
.invert()
.toString();
const color2 = cyan.toHSLA().toString();
assert.equal(color1, color2);
});
});
describe('lighten()', () => {
it('lightens black to white', () => {
const color1 = black.lighten(1).toString();
const color2 = white.toString();
assert.equal(color1, color2);
});
it('lightens black to gray', () => {
const color1 = black.lighten(0.5).toString();
const color2 = rgb(128, 128, 128).toString();
assert.equal(color1, color2);
});
it('lightens from the absolute max', () => {
const color1 = hsl(25, 1, 0.2)
.lighten(0.3)
.toString();
const color2 = hsl(25, 1, 0.5).toString();
assert.equal(color1, color2);
});
it('lightens from the current color', () => {
const color1 = hsl(25, 1, 0.2).lighten(0.3, true);
const color2 = hsl(25, 1, 0.44);
assert.equal(color1.lightness(), color2.lightness());
});
});
describe('darken()', () => {
it('changes white to black', () => {
const color1 = white.darken(1).toString();
const color2 = black.toString();
assert.equal(color1, color2);
});
it('changes black to gray', () => {
const color1 = white
.darken(0.5)
.toHSL()
.toString();
const color2 = hsl(0, 0, 0.5).toString();
assert.equal(color1, color2);
});
it('keeps the color format it started with', () => {
const color1 = rgb(255, 0, 0)
.darken(0.5)
.toString();
const color2 = rgb(0, 0, 0).toString();
assert.equal(color1, color2);
});
it('keeps its alpha channel', () => {
const color1 = rgba(69, 86, 100, '70%').darken(0.3);
assert.equal(color1.opacity() - 0.7 < 0.0001, true);
});
it('darkens from the absolute max', () => {
const color1 = hsl(25, 1, 0.8)
.darken(0.3)
.toString();
const color2 = hsl(25, 1, 0.5).toString();
assert.equal(color1, color2);
});
it('darkens from the current color', () => {
const color1 = hsl(25, 1, 0.8)
.darken(0.3, true)
.toString();
const color2 = hsl(25, 1, 0.56).toString();
assert.equal(color1, color2);
});
});
describe('saturate()', () => {
it('changes white to midred', () => {
const color1 = hsl(0, 0, 1)
.saturate(0.5)
.toString();
const color2 = hsl(0, 0.5, 1).toString();
assert.equal(color1, color2);
});
it('changes white to red', () => {
const color1 = hsl(0, 0, 1)
.saturate(1)
.toString();
const color2 = hsl(0, 1, 1).toString();
assert.equal(color1, color2);
});
it('saturates from the absolute max', () => {
const color1 = hsl(25, 0.2, 0.5)
.saturate(0.3)
.toString();
const color2 = hsl(25, 0.5, 0.5).toString();
assert.equal(color1, color2);
});
it('saturates from the current color', () => {
const color1 = hsl(25, 0.2, 0.5)
.saturate(0.3, true)
.toString();
const color2 = hsl(25, 0.44, 0.5).toString();
assert.equal(color1, color2);
});
});
describe('desaturate()', () => {
it('changes red to midred', () => {
const color1 = hsl(0, 1, 1)
.desaturate(0.5)
.toString();
const color2 = hsl(0, 0.5, 1).toString();
assert.equal(color1, color2);
});
it('changes red to white', () => {
const color1 = red.desaturate(1).toString();
const color2 = rgb(128, 128, 128).toString();
assert.equal(color1, color2);
});
it('desaturates from the absolute max', () => {
const color1 = hsl(25, 0.8, 0.5)
.desaturate(0.3)
.toString();
const color2 = hsl(25, 0.5, 0.5).toString();
assert.equal(color1, color2);
});
it('desaturates from the current color', () => {
const color1 = hsl(25, 0.8, 0.5)
.desaturate(0.3, true)
.toString();
const color2 = hsl(25, 0.56, 0.5).toString();
assert.equal(color1, color2);
});
});
describe('grayscale()', () => {
it('handles red', () => {
const color1 = red.grayscale().toHSL();
assert.equal(color1.hue(), 0);
assert.equal(color1.saturation(), 0);
assert.equal(Math.round(color1.lightness() * 100), 50);
});
it('handles green', () => {
const color1 = green.grayscale().toHSL();
assert.equal(color1.hue(), 0);
assert.equal(color1.saturation(), 0);
assert.equal(Math.round(color1.lightness() * 100), 25);
});
it('handles blue', () => {
const color1 = blue.grayscale().toHSL();
assert.equal(color1.hue(), 0);
assert.equal(color1.saturation(), 0);
assert.equal(Math.round(color1.lightness() * 100), 50);
});
it('handles white', () => {
const color1 = white.grayscale().toString();
const color2 = white.toString();
assert.equal(color1, color2);
});
it('handles black', () => {
const color1 = black.grayscale().toString();
const color2 = rgb(0, 0, 0).toString();
assert.equal(color1, color2);
});
});
describe('fade()', () => {
it('changes rgb to rgba', () => {
const color1 = rgb(255, 255, 255)
.fade(1)
.toString();
const color2 = rgba(255, 255, 255, 1).toString();
assert.equal(color1, color2);
});
it('changes hsl to hsla', () => {
const color1 = hsl(0, 0, 1)
.fade(1)
.toString();
const color2 = hsla(0, 0, 1, 1).toString();
assert.equal(color1, color2);
});
it('clamps < 0 at 0% opacity', () => {
const color1 = rgba(255, 0, 0, 0)
.fade(-0.5)
.toString();
const color2 = rgba(255, 0, 0, 0).toString();
assert.equal(color1, color2);
});
it('sets 0 to 0% opacity', () => {
const color1 = rgba(255, 0, 0, 0)
.fade(0)
.toString();
const color2 = rgba(255, 0, 0, 0).toString();
assert.equal(color1, color2);
});
it('sets .5 to 50% opacity', () => {
const color1 = rgba(255, 0, 0, 0)
.fade(0.5)
.toString();
const color2 = rgba(255, 0, 0, 0.5).toString();
assert.equal(color1, color2);
});
it('sets 1 to 100% opacity', () => {
const color1 = rgba(255, 0, 0, 0)
.fade(1)
.toString();
const color2 = rgba(255, 0, 0, 1).toString();
assert.equal(color1, color2);
});
it('clamps > 1 to 100% opacity', () => {
const color1 = rgba(255, 0, 0, 0)
.fade(1.5)
.toString();
const color2 = rgba(255, 0, 0, 1).toString();
assert.equal(color1, color2);
});
});
describe('fadeOut', () => {
it('clamps at 0%', () => {
const color1 = rgba(255, 0, 0, 0)
.fadeOut(0.25)
.toString();
const color2 = rgba(255, 0, 0, 0).toString();
assert.equal(color1, color2);
});
it('.75 = 1 - .25', () => {
const color1 = rgba(255, 0, 0, 1)
.fadeOut(0.25)
.toString();
const color2 = rgba(255, 0, 0, 0.75).toString();
assert.equal(color1, color2);
});
it('.5 = .75 - .25', () => {
const color1 = rgba(255, 0, 0, 0.75)
.fadeOut(0.25)
.toString();
const color2 = rgba(255, 0, 0, 0.5).toString();
assert.equal(color1, color2);
});
it('.25 = .5 - .25', () => {
const color1 = rgba(255, 0, 0, 0.5)
.fadeOut(0.25)
.toString();
const color2 = rgba(255, 0, 0, 0.25).toString();
assert.equal(color1, color2);
});
it('0 = .25 - .25', () => {
const color1 = rgba(255, 0, 0, 0.25)
.fadeOut(0.25)
.toString();
const color2 = rgba(255, 0, 0, 0).toString();
assert.equal(color1, color2);
});
it('fades out from the absolute max', () => {
const color1 = rgba(255, 0, 0, 0.8)
.fadeOut(0.3)
.toString();
const color2 = rgba(255, 0, 0, 0.5).toString();
assert.equal(color1, color2);
});
it('fades out from the current opacity', () => {
const color1 = rgba(255, 0, 0, 0.8)
.fadeOut(0.3, true)
.toString();
const color2 = rgba(255, 0, 0, 0.56).toString();
assert.equal(color1, color2);
});
});
describe('fadeIn', () => {
it('.25 = 0 - .25', () => {
const color1 = rgba(255, 0, 0, 0)
.fadeIn(0.25)
.toString();
const color2 = rgba(255, 0, 0, 0.25).toString();
assert.equal(color1, color2);
});
it('.5 = .25 - .25', () => {
const color1 = rgba(255, 0, 0, 0.25)
.fadeIn(0.25)
.toString();
const color2 = rgba(255, 0, 0, 0.5).toString();
assert.equal(color1, color2);
});
it('.75 = .5 - .25', () => {
const color1 = rgba(255, 0, 0, 0.5)
.fadeIn(0.25)
.toString();
const color2 = rgba(255, 0, 0, 0.75).toString();
assert.equal(color1, color2);
});
it('1 = .75 - .25', () => {
const color1 = rgba(255, 0, 0, 0.75)
.fadeIn(0.25)
.toString();
const color2 = rgba(255, 0, 0, 1).toString();
assert.equal(color1, color2);
});
it('clamps at 100%', () => {
const color1 = rgba(255, 0, 0, 1)
.fadeIn(0.25)
.toString();
const color2 = rgba(255, 0, 0, 1).toString();
assert.equal(color1, color2);
});
it('fades in from the absolute max', () => {
const color1 = rgba(255, 0, 0, 0.2)
.fadeIn(0.3)
.toString();
const color2 = rgba(255, 0, 0, 0.5).toString();
assert.equal(color1, color2);
});
it('fades in from the current opacity', () => {
const color1 = rgba(255, 0, 0, 0.2).fadeIn(0.3, true);
const color2 = rgba(255, 0, 0, 0.44);
assert.equal(color1.lightness(), color2.lightness());
});
});
describe('mix()', () => {
// $c0: mix(red, green);
// $c1: mix(red, blue);
// $c2: mix(red, white);
// $c3: mix(red, transparent);
// $c4: mix(red, black);
it('red + green', () => {
// sass converts rgb to hex, so the actual result should be
// rgb(127.5, 64, 0) if the numbers were preserved
const color1 = red.mix(green).toString();
const color2 = rgb(128, 64, 0).toString();
assert.equal(color1, color2);
});
it('red + blue', () => {
const color1 = red.mix(blue).toString();
const color2 = purple.toString();
assert.equal(color1, color2);
});
it('red + white', () => {
const color1 = red.mix(white).toString();
const color2 = rgb(255, 128, 128).toString();
assert.equal(color1, color2);
});
it('red + transparent', () => {
const color1 = red.mix(transparent).toString();
const color2 = rgba(255, 0, 0, 0.5).toString();
assert.equal(color1, color2);
});
it('red + black', () => {
const color1 = red.mix(black).toString();
const color2 = maroon.toString();
assert.equal(color1, color2);
});
});
describe('tint()', () => {
it('changed red to a lighter red', () => {
const color1 = red.tint(0.3).toString();
// color2 was tested on the SASS compiler with mix(white, red, 30%)
const color2 = rgb(255, 77, 77).toString();
assert.equal(color1, color2);
});
});
describe('shade()', () => {
it('changed red to a darker red', () => {
const color1 = red.shade(0.3).toString();
// color2 was tested on the SASS compiler with mix(black, red, 30%)
const color2 = rgb(179, 0, 0).toString();
assert.equal(color1, color2);
});
});
describe('spin()', () => {
it('spinning 360 degrees returns same color', () => {
const color1 = red.toString();
const color2 = red.spin(360).toString();
assert.equal(color1, color2);
});
it('spinning -360 degrees returns same color', () => {
const color1 = red.toString();
const color2 = red.spin(-360).toString();
assert.equal(color1, color2);
});
it('spinning -120 degrees from red returns blue', () => {
const color1 = red.spin(-120).toHexString();
assert.equal('#0000FF', color1);
});
it('spinning 120 degrees from red returns yellow', () => {
const color1 = red.spin(120).toHexString();
assert.equal('#00FF00', color1);
});
});
}); | the_stack |
import { Trans } from "@lingui/macro";
import { i18nMark } from "@lingui/react";
import { Link } from "react-router";
import mixin from "reactjs-mixin";
import * as React from "react";
import { Icon } from "@dcos/ui-kit";
import {
greyDark,
iconSizeXs,
} from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens";
import { ProductIcons } from "@dcos/ui-kit/dist/packages/icons/dist/product-icons-enum";
import { SystemIcons } from "@dcos/ui-kit/dist/packages/icons/dist/system-icons-enum";
import AlertPanel from "#SRC/js/components/AlertPanel";
import AlertPanelHeader from "#SRC/js/components/AlertPanelHeader";
import Breadcrumb from "#SRC/js/components/Breadcrumb";
import BreadcrumbTextContent from "#SRC/js/components/BreadcrumbTextContent";
import ConfigurationMap from "#SRC/js/components/ConfigurationMap";
import ConfigurationMapHeading from "#SRC/js/components/ConfigurationMapHeading";
import ConfigurationMapLabel from "#SRC/js/components/ConfigurationMapLabel";
import ConfigurationMapRow from "#SRC/js/components/ConfigurationMapRow";
import ConfigurationMapSection from "#SRC/js/components/ConfigurationMapSection";
import ConfigurationMapValue from "#SRC/js/components/ConfigurationMapValue";
import Page from "#SRC/js/components/Page";
import StoreMixin from "#SRC/js/mixins/StoreMixin";
import ACLDirectoriesStore from "../stores/ACLDirectoriesStore";
import DirectoryActionButtons from "../components/DirectoryActionButtons";
import DirectoryFormModal from "../components/DirectoryFormModal";
import FieldDefinitions from "../constants/FieldDefinitions";
const DirectoriesBreadcrumbs = () => {
const crumbs = [
<Breadcrumb key={-1} title="Directory">
<BreadcrumbTextContent>
<Trans render={<Link to="/settings/directory" key={-1} />}>
LDAP Directory
</Trans>
</BreadcrumbTextContent>
</Breadcrumb>,
];
return (
<Page.Header.Breadcrumbs iconID={ProductIcons.Users} breadcrumbs={crumbs} />
);
};
class DirectoriesPage extends mixin(StoreMixin) {
state = {
modalEditMode: false,
modalDisabled: false,
modalOpen: false,
showValue: {},
};
// prettier-ignore
store_listeners = [
{name: "aclDirectories", events: ["fetchSuccess", "addSuccess", "addError", "deleteSuccess"]}
];
componentDidMount(...args) {
super.componentDidMount(...args);
ACLDirectoriesStore.fetchDirectories();
}
onAclDirectoriesStoreAddSuccess() {
this.changeModalOpenState(false);
ACLDirectoriesStore.fetchDirectories();
}
onAclDirectoriesStoreAddError() {
this.setState({ modalDisabled: false });
}
handleConfigurationEditClick = () => {
this.setState({ modalEditMode: true });
this.changeModalOpenState(true);
};
handleDirectoryDelete() {
ACLDirectoriesStore.deleteDirectory();
}
handleDirectoryTestConnection() {
ACLDirectoriesStore.testDirectoryConnection();
}
handleFormSubmit = () => {
this.setState({ modalDisabled: true });
};
handleSecretToggle = (fieldName) => {
const { showValue } = this.state;
this.setState({ ...showValue, [fieldName]: !showValue[fieldName] });
};
changeModalOpenState = (open) => {
this.setState({ modalOpen: open, modalDisabled: false });
};
getDirectoryFormModal(directoryConfig) {
return (
<DirectoryFormModal
editMode={this.state.modalEditMode}
model={directoryConfig}
modalDisabled={this.state.modalDisabled}
modalOpen={this.state.modalOpen}
onFormSubmit={this.handleFormSubmit}
changeModalOpenState={this.changeModalOpenState}
/>
);
}
getDirectoryDetails(directoryConfig) {
// Ordering mirrors that of `DirectoryFormModal`,
// omitting `lookup-password`.
// See: DirectoryFormModal.getModalFormDefinition()
let clientCertRow = null;
let caCertRow = null;
let sslTLSValue =
FieldDefinitions["ssl-tls-configuration-default-value"].displayName;
let groupSearchSection = null;
let userSearchSection = null;
const clientCertValue = this.getSecretValue("client-cert");
const caCertValue = this.getSecretValue("ca-certs");
if (directoryConfig["use-ldaps"]) {
sslTLSValue = FieldDefinitions["use-ldaps"].displayName;
} else if (directoryConfig["enforce-starttls"]) {
sslTLSValue = FieldDefinitions["enforce-starttls"].displayName;
}
if (directoryConfig["user-search"]) {
userSearchSection = (
<ConfigurationMapSection key="user-search">
<ConfigurationMapHeading>
<Trans render="span">User Search</Trans>
</ConfigurationMapHeading>
<ConfigurationMapRow>
<ConfigurationMapLabel>
<Trans
render="span"
id={FieldDefinitions["user-search.search-base"].displayName}
/>
</ConfigurationMapLabel>
<ConfigurationMapValue>
{directoryConfig["user-search"]["search-base"]}
</ConfigurationMapValue>
</ConfigurationMapRow>
<ConfigurationMapRow>
<ConfigurationMapLabel>
<Trans
render="span"
id={
FieldDefinitions["user-search.search-filter-template"]
.displayName
}
/>
</ConfigurationMapLabel>
<ConfigurationMapValue>
{directoryConfig["user-search"]["search-filter-template"]}
</ConfigurationMapValue>
</ConfigurationMapRow>
</ConfigurationMapSection>
);
}
if (directoryConfig["group-search"]) {
groupSearchSection = (
<ConfigurationMapSection key="group-search">
<ConfigurationMapHeading>
<Trans render="span">Group Search</Trans>
</ConfigurationMapHeading>
<ConfigurationMapRow>
<ConfigurationMapLabel>
<Trans
render="span"
id={FieldDefinitions["group-search.search-base"].displayName}
/>
</ConfigurationMapLabel>
<ConfigurationMapValue>
{directoryConfig["group-search"]["search-base"]}
</ConfigurationMapValue>
</ConfigurationMapRow>
<ConfigurationMapRow>
<ConfigurationMapLabel>
<Trans
render="span"
id={
FieldDefinitions["group-search.search-filter-template"]
.displayName
}
/>
</ConfigurationMapLabel>
<ConfigurationMapValue>
{directoryConfig["group-search"]["search-filter-template"]}
</ConfigurationMapValue>
</ConfigurationMapRow>
</ConfigurationMapSection>
);
}
if (clientCertValue != null) {
clientCertRow = (
<ConfigurationMapRow>
<ConfigurationMapLabel>
<Trans render="span">Client Secret</Trans>{" "}
{this.getSecretIcon("client-cert")}
</ConfigurationMapLabel>
<ConfigurationMapValue>{clientCertValue}</ConfigurationMapValue>
</ConfigurationMapRow>
);
}
if (caCertValue != null) {
caCertRow = (
<ConfigurationMapRow>
<ConfigurationMapLabel>
<Trans render="span">CA Certificate</Trans>{" "}
{this.getSecretIcon("ca-certs")}
</ConfigurationMapLabel>
<ConfigurationMapValue>{caCertValue}</ConfigurationMapValue>
</ConfigurationMapRow>
);
}
return [
<ConfigurationMapSection key="general-section">
<ConfigurationMapRow>
<ConfigurationMapLabel>
<Trans render="span">{FieldDefinitions.host.displayName}</Trans>
</ConfigurationMapLabel>
<ConfigurationMapValue>{directoryConfig.host}</ConfigurationMapValue>
</ConfigurationMapRow>
<ConfigurationMapRow>
<ConfigurationMapLabel>
<Trans render="span">{FieldDefinitions.port.displayName}</Trans>
</ConfigurationMapLabel>
<ConfigurationMapValue>{directoryConfig.port}</ConfigurationMapValue>
</ConfigurationMapRow>
<ConfigurationMapRow>
<ConfigurationMapLabel>
<Trans render="span">SSL/TLS Setting</Trans>
</ConfigurationMapLabel>
<ConfigurationMapValue>
<Trans render="span" id={sslTLSValue} />
</ConfigurationMapValue>
</ConfigurationMapRow>
{clientCertRow}
{caCertRow}
<ConfigurationMapRow>
<ConfigurationMapLabel>
<Trans
render="span"
id={FieldDefinitions["lookup-dn"].displayName}
/>
</ConfigurationMapLabel>
<ConfigurationMapValue>
{directoryConfig["lookup-dn"]}
</ConfigurationMapValue>
</ConfigurationMapRow>
<ConfigurationMapRow>
<ConfigurationMapLabel>
<Trans render="span" id={FieldDefinitions.dntemplate.displayName} />
</ConfigurationMapLabel>
<ConfigurationMapValue>
{directoryConfig.dntemplate}
</ConfigurationMapValue>
</ConfigurationMapRow>
</ConfigurationMapSection>,
userSearchSection,
groupSearchSection,
];
}
getSecretIcon(fieldName) {
const iconID = this.state.showValue[fieldName]
? SystemIcons.EyeSlash
: SystemIcons.Eye;
return (
<span
className="secret-toggle clickable"
onClick={this.handleSecretToggle.bind(this, fieldName)}
>
<Icon color={greyDark} shape={iconID} size={iconSizeXs} />
</span>
);
}
getSecretValue(fieldName) {
const secretValue = ACLDirectoriesStore.getDirectories().getItems()[0][
fieldName
];
if (this.state.showValue[fieldName]) {
return <pre>{secretValue}</pre>;
}
if (secretValue) {
return "••••••••";
}
}
renderDirectory(directoryConfig) {
return (
<div className="container">
<DirectoryActionButtons
onConfigurationEditClick={this.handleConfigurationEditClick}
/>
<ConfigurationMap>
<ConfigurationMapHeading>
<Trans render="span">External LDAP Configuration</Trans>
</ConfigurationMapHeading>
{this.getDirectoryDetails(directoryConfig)}
</ConfigurationMap>
</div>
);
}
renderAddDirectory(directoryConfig) {
return (
<Page>
<Page.Header breadcrumbs={<DirectoriesBreadcrumbs />} />
<AlertPanel>
<AlertPanelHeader>
<Trans render="span">No directory configured</Trans>
</AlertPanelHeader>
<Trans render="p" className="tall">
Set up an LDAP connection to avoid having to recreate your user
accounts within DC/OS.
</Trans>
<div className="button-collection flush-bottom">
<button
className="button button-primary"
onClick={this.changeModalOpenState.bind(null, true)}
>
<Trans render="span">Add Directory</Trans>
</button>
</div>
</AlertPanel>
{this.getDirectoryFormModal(directoryConfig)}
</Page>
);
}
render() {
const directories = ACLDirectoriesStore.getDirectories().getItems();
const directoryConfig = directories[0];
if (!directories.length) {
return this.renderAddDirectory(directoryConfig);
}
return (
<Page>
<Page.Header breadcrumbs={<DirectoriesBreadcrumbs />} />
{this.renderDirectory(directoryConfig)}
{this.getDirectoryFormModal(directoryConfig)}
</Page>
);
}
}
DirectoriesPage.routeConfig = {
label: i18nMark("LDAP Directory"),
matches: /^\/settings\/directory/,
};
export default DirectoriesPage; | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormProcessSession_Information {
interface tab__474B8A52_CB22_4194_A5A6_F21FD40B7417_Sections {
Details: DevKit.Controls.Section;
}
interface tab_Comments_Sections {
Comments: DevKit.Controls.Section;
}
interface tab_Details_Sections {
Details_2: DevKit.Controls.Section;
}
interface tab_Linked_Sessions_Sections {
Linked_Sessions: DevKit.Controls.Section;
}
interface tab_Summary_Sections {
Summary: DevKit.Controls.Section;
}
interface tab__474B8A52_CB22_4194_A5A6_F21FD40B7417 extends DevKit.Controls.ITab {
Section: tab__474B8A52_CB22_4194_A5A6_F21FD40B7417_Sections;
}
interface tab_Comments extends DevKit.Controls.ITab {
Section: tab_Comments_Sections;
}
interface tab_Details extends DevKit.Controls.ITab {
Section: tab_Details_Sections;
}
interface tab_Linked_Sessions extends DevKit.Controls.ITab {
Section: tab_Linked_Sessions_Sections;
}
interface tab_Summary extends DevKit.Controls.ITab {
Section: tab_Summary_Sections;
}
interface Tabs {
_474B8A52_CB22_4194_A5A6_F21FD40B7417: tab__474B8A52_CB22_4194_A5A6_F21FD40B7417;
Comments: tab_Comments;
Details: tab_Details;
Linked_Sessions: tab_Linked_Sessions;
Summary: tab_Summary;
}
interface Body {
Tab: Tabs;
/** Unique identifier of the user who canceled the dialog session. */
CanceledBy: DevKit.Controls.Lookup;
/** Date and time when the dialog session was canceled. */
CanceledOn: DevKit.Controls.DateTime;
/** User comments. */
Comments: DevKit.Controls.String;
/** Unique identifier of the user who completed the dialog session. */
CompletedBy: DevKit.Controls.Lookup;
/** Date and time when the dialog session was completed. */
CompletedOn: DevKit.Controls.DateTime;
/** Date and time when the dialog session was created. */
CreatedOn: DevKit.Controls.DateTime;
/** Name of the dialog session. */
Name: DevKit.Controls.String;
/** Unique identifier of the succeeding linked dialog session. */
NextLinkedSessionId: DevKit.Controls.Lookup;
/** Unique identifier of the originating dialog session. */
OriginatingSessionId: DevKit.Controls.Lookup;
/** Unique identifier of the user or team who owns the dialog session. */
OwnerId: DevKit.Controls.Lookup;
/** Unique identifier of the preceding linked dialog session. */
PreviousLinkedSessionId: DevKit.Controls.Lookup;
/** Select the process activation record that is related to the dialog session. */
ProcessId: DevKit.Controls.Lookup;
/** Unique identifier of the object with which the dialog session is associated. */
RegardingObjectId: DevKit.Controls.Lookup;
/** Unique identifier of the user who started the dialog session. */
StartedBy: DevKit.Controls.Lookup;
/** Date and time when the dialog session was started. */
StartedOn: DevKit.Controls.DateTime;
/** Reason for the status of the dialog session. */
StatusCode: DevKit.Controls.OptionSet;
}
interface Footer extends DevKit.Controls.IFooter {
/** Status of the dialog session. */
StateCode: DevKit.Controls.OptionSet;
}
}
class FormProcessSession_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form ProcessSession_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 ProcessSession_Information */
Body: DevKit.FormProcessSession_Information.Body;
/** The Footer section of form ProcessSession_Information */
Footer: DevKit.FormProcessSession_Information.Footer;
}
class ProcessSessionApi {
/**
* DynamicsCrm.DevKit ProcessSessionApi
* @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;
/** Name of the activity that is being executed. */
ActivityName: DevKit.WebApi.StringValue;
/** Unique identifier of the user who canceled the dialog session. */
CanceledBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the dialog session was canceled. */
CanceledOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** User comments. */
Comments: DevKit.WebApi.StringValue;
/** Unique identifier of the user who completed the dialog session. */
CompletedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the dialog session was completed. */
CompletedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Unique identifier of the user who started the dialog session. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the dialog session was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the dialog session. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Error code related to the dialog session. */
ErrorCode: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who ran the dialog process. */
ExecutedBy: DevKit.WebApi.LookupValue;
/** Date and time when the dialog process was run. */
ExecutedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Input arguments for the child dialog process. */
InputArguments: DevKit.WebApi.StringValue;
/** Unique identifier of the user who last modified the dialog session. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the dialog session was last modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the dialog session. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Name of the dialog session. */
Name: DevKit.WebApi.StringValue;
/** Unique identifier of the succeeding linked dialog session. */
NextLinkedSessionId: DevKit.WebApi.LookupValue;
/** Unique identifier of the originating dialog session. */
OriginatingSessionId: DevKit.WebApi.LookupValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier of the business unit that owns the dialog session. */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the team who owns the dialog session. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the user who owns the dialog session. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the preceding linked dialog session. */
PreviousLinkedSessionId: DevKit.WebApi.LookupValue;
/** Select the process activation record that is related to the dialog session. */
ProcessId: DevKit.WebApi.LookupValue;
/** Unique identifier of the dialog session. */
ProcessSessionId: DevKit.WebApi.GuidValue;
/** Name of the dialog stage. */
ProcessStageName: DevKit.WebApi.StringValue;
/** State of the dialog process. */
ProcessState: DevKit.WebApi.StringValue;
/** For internal use only. */
ProtectionKey: DevKit.WebApi.StringValueReadonly;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_account: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_activityfileattachment: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_annotation: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_appelement: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_applicationuser: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_appmodulecomponentedge: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_appmodulecomponentnode: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_appnotification: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_appointment: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_appsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_appusersetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_bot: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_botcomponent: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_businessunit: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_businessunitnewsarticle: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_canvasappextendedmetadata: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_cascadegrantrevokeaccessrecordstracker: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_cascadegrantrevokeaccessversiontracker: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_catalog: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_catalogassignment: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
channelaccessprofile_processsession: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
profileid: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_connection: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_connectionreference: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_connectionrole: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_connector: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_contact: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_conversationtranscript: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_convertrule: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_customapi: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_customapirequestparameter: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_customapiresponseproperty: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_customeraddress: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_customerrelationship: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_datalakefolder: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_datalakefolderpermission: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_datalakeworkspace: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_datalakeworkspacepermission: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_devkit_bpfaccount: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_email: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_environmentvariabledefinition: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_environmentvariablevalue: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_expiredprocess: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_exportsolutionupload: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
externalparty_processsession: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
externalpartyitem_processsession: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_fax: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_featurecontrolsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_flowmachine: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_flowmachinegroup: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_goal: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_goalrollupquery: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_holidaywrapper: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_internalcatalogassignment: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_kbarticle: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_kbarticlecomment: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_kbarticletemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_keyvaultreference: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_knowledgearticle: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_knowledgebaserecord: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_letter: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_mailbox: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_mailmergetemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_managedidentity: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_metric: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdynce_botcontent: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_aibdataset: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_aibdatasetfile: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_aibdatasetrecord: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_aibdatasetscontainer: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_aibfile: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_aibfileattacheddata: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_aiconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_aifptrainingdocument: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_aimodel: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_aiodimage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_aiodlabel: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_aiodtrainingboundingbox: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_aiodtrainingimage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_aitemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_dataflow: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_federatedarticle: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_federatedarticleincident: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_helppage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_kalanguagesetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_kmfederatedsearchconfig: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_kmpersonalizationsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_knowledgearticleimage: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_knowledgearticletemplate: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_knowledgeinteractioninsight: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_knowledgepersonalfilter: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_knowledgesearchfilter: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_knowledgesearchinsight: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_pminferredtask: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_pmrecording: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_richtextfile: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_serviceconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_slakpi: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_msdyn_tour: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_newprocess: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_organizationdatasyncsubscription: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_organizationdatasyncsubscriptionentity: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_organizationsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_package: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_pdfsetting: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_phonecall: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_position: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_processstageparameter: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_provisionlanguageforuser: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_queue: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_queueitem: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_recurringappointmentmaster: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_relationshiprole: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_report: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_revokeinheritedaccessrecordstracker: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_rollupfield: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_routingrule: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_routingruleitem: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_serviceplan: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_serviceplanmapping: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_settingdefinition: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_sharepointdocumentlocation: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_sharepointsite: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_sla: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_socialactivity: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_socialprofile: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_solutioncomponentattributeconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_solutioncomponentbatchconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_solutioncomponentconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_solutioncomponentrelationshipconfiguration: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_stagesolutionupload: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_subject: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_systemuser: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_systemuserauthorizationchangetracker: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_task: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_team: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_teammobileofflineprofilemembership: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_template: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_territory: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_theme: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_transactioncurrency: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_translationprocess: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_usermapping: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_usermobileofflineprofilemembership: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_virtualentitymetadata: DevKit.WebApi.LookupValue;
/** Unique identifier of the object with which the dialog session is associated. */
regardingobjectid_workflowbinary: DevKit.WebApi.LookupValue;
RegardingObjectIdYomiName: DevKit.WebApi.StringValue;
/** Unique identifier of the user who started the dialog session. */
StartedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the dialog session was started. */
StartedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Status of the dialog session. */
StateCode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the dialog session. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** Name of the dialog step. */
StepName: DevKit.WebApi.StringValue;
}
}
declare namespace OptionSet {
namespace ProcessSession {
enum StateCode {
/** 1 */
Complete,
/** 0 */
Incomplete
}
enum StatusCode {
/** 5 */
Canceled,
/** 4 */
Completed,
/** 6 */
Failed,
/** 2 */
In_Progress,
/** 1 */
Not_Started,
/** 3 */
Paused
}
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 * as Meta from 'meta';
import * as Shell from 'shell';
import {
buildMetaWindowIdentifier,
MsWindow,
MsWindowMatchingInfo,
} from 'src/layout/msWorkspace/msWindow';
import { MsWorkspace } from 'src/layout/msWorkspace/msWorkspace';
import { MsDndManager } from 'src/manager/msDndManager';
import { MsFocusManager } from 'src/manager/msFocusManager';
import { MsManager } from 'src/manager/msManager';
import { MsResizeManager } from 'src/manager/msResizeManager';
import { Rectangular } from 'src/types/mod';
import { assert } from 'src/utils/assert';
import { AsyncDebounce } from 'src/utils/async';
import { groupBy } from 'src/utils/group_by';
import { getSettings } from 'src/utils/settings';
import { weighted_matching } from 'src/utils/weighted_matching';
const Signals = imports.signals;
const Me = imports.misc.extensionUtils.getCurrentExtension();
export type MetaWindowWithMsProperties = Meta.Window & {
createdAt?: number;
firstFrameDrawn?: boolean;
firstFrameDrawnPromise?: Promise<void>;
handledByMaterialShell?: boolean;
msWindow?: MsWindow;
titleBarVisible?: boolean;
};
export type MetaWindowActorWithMsProperties = Meta.WindowActor & {
lastResize: number;
};
/** Checks if `found` is equal to `desired` and returns the appropriate cost.
* If desired is not given (undefined) then `skipCost` is returned.
* If `found` is equal to `desired` then `0` is returned, otherwise `mismatchCost`.
*/
function matchingCost<T>(
desired: T | undefined,
found: T,
mismatchCost: number,
skipCost: number
) {
if (desired !== undefined) {
return found === desired ? 0 : mismatchCost;
} else {
return skipCost;
}
}
const INF_COST = 100000;
/** After a meta window has been associated with an MsWindow, we allow this association to change
* for a small amount of time.
*
* This is to allow for the case where the window title changes and another association becomes much
* more desirable. This happens often when opening text editors that restore the previously opened documents.
* In those cases multiple windows may open with initially identical window titles, but once the documents
* have loaded the window titles change and we might be able to make better associations.
*/
const MAX_WINDOW_REASSOCIATION_TIME_MS = 3000;
/** Cost for associating the the given metaWindow to the msWindow.
*
* windowInfo are the matching details for the meta window, for example its window title.
*
* A higher returned cost means the match is less desirable.
*/
function windowMatchingCost(
windowInfo: MsWindowMatchingInfo,
metaWindow: Meta.Window,
msWindow: MsWindow
) {
assert(
msWindow.lifecycleState.type === 'window' ||
msWindow.lifecycleState.type === 'app-placeholder',
'MsWindow has no matching info'
);
const matchingInfo = msWindow.lifecycleState.matchingInfo;
let cost = 0;
// The wmClass *must* match if specified
cost += matchingCost(matchingInfo.wmClass, windowInfo.wmClass, INF_COST, 1);
cost += matchingCost(matchingInfo.pid, windowInfo.pid, 100, 1);
cost += matchingCost(matchingInfo.title, windowInfo.title, 50, 1);
cost += matchingCost(matchingInfo.stableSeq, windowInfo.stableSeq, 10, 1);
if (msWindow.lifecycleState.type === 'window') {
// Prefer to keep existing matchings
cost += msWindow.lifecycleState.metaWindow === metaWindow ? 0 : 5;
} else {
cost += 5;
}
if (msWindow.lifecycleState.type === 'app-placeholder') {
// Prefer matching to MsWindows which are waiting for an app to open
cost +=
msWindow.lifecycleState.waitingForAppSince !== undefined ? 0 : 1;
} else {
cost += 2;
}
return cost;
}
export type MsWindowManagerType = InstanceType<typeof MsWindowManager>;
export class MsWindowManager extends MsManager {
private windowTracker: Shell.WindowTracker;
msWindowList: MsWindow[];
msDndManager: MsDndManager;
msResizeManager: MsResizeManager;
msFocusManager: MsFocusManager;
private checkWindowsForAssignationsDebounce: AsyncDebounce;
constructor() {
super();
this.checkWindowsForAssignationsDebounce = new AsyncDebounce(
50,
this.checkWindowsForAssignations.bind(this)
);
this.windowTracker = Shell.WindowTracker.get_default();
this.msWindowList = [];
this.msDndManager = new MsDndManager(this);
this.msResizeManager = new MsResizeManager(this);
this.msFocusManager = new MsFocusManager(this);
this.observe(
global.display,
'window-created',
(_, metaWindow: MetaWindowWithMsProperties) => {
const actor =
metaWindow.get_compositor_private<Meta.WindowActor>();
metaWindow.firstFrameDrawn = false;
metaWindow.firstFrameDrawnPromise = new Promise((resolve) => {
actor.connect('first-frame', (_params) => {
metaWindow.firstFrameDrawn = true;
resolve();
});
});
this.onNewMetaWindow(metaWindow);
}
);
this.observe(
global.window_manager,
'size-changed',
(wm, actor: MetaWindowActorWithMsProperties) => {
actor.lastResize = Date.now();
}
);
}
/** All meta windows that are currently managed by Material Shell.
* This includes app windows and their dialogs.
*/
get managedMetaWindows(): MetaWindowWithMsProperties[] {
return new Array<MetaWindowWithMsProperties>().concat(
...this.msWindowList.map((w) => w.metaWindows)
);
}
private async assignWindows() {
// We capture the list of all actors at the beginning and don't care about any new ones until the
// next time we start assigning windows.
const actors = global
.get_window_actors()
.filter(
(x) =>
(x.metaWindow as MetaWindowWithMsProperties)
.handledByMaterialShell
);
// Assign all non-dialog windows first
const windowsDone = this.assignNonDialogWindows(actors);
// Assign the dialog windows to previously existing MsWindows that fits them.
const dialogsDone = this.assignDialogWindows(actors);
await Promise.all([windowsDone, dialogsDone]);
}
/** Assign non-dialog windows to either existing empty MsWindows or determine that new MsWindows should be created for them.
*
* This is done by first grouping meta windows and MsWindows by their app id.
* Then for each app, the meta windows are matched to existing MsWindows or to new MsWindows using a cost function.
* The matching is done such that the total sum of all costs are minimized.
*
* The cost function is particularly important when restoring from a persisted state.
* In the persisted state there is information about the windows' wmClass, title, process id, etc. and this is
* used in the cost function to try to restore windows to their correct locations as accurately as possible.
*
* Returns a promise which resolves when the first frames of all assigned and newly created windows have been drawn.
* Before this, it is not safe to try to reassign windows because some async functions are still in progress.
*/
private assignNonDialogWindows(
actors: Meta.WindowActor[]
): Promise<void[]> {
const assignedMetaWindows = new Set(this.managedMetaWindows);
// We allow meta windows to be re-assigned for a short amount of time after they have first been assigned.
// See docs for `MAX_WINDOW_REASSOCIATION_TIME_MS` for more details.
// Essentially this loop makes those already assigned windows available to be re-assigned.
const now = new Date().getTime();
for (const msWindow of this.msWindowList) {
if (
msWindow.lifecycleState.type === 'window' &&
now - msWindow.lifecycleState.matchedAtTime.getTime() <
MAX_WINDOW_REASSOCIATION_TIME_MS &&
msWindow.lifecycleState.metaWindow !== null
) {
assignedMetaWindows.delete(msWindow.lifecycleState.metaWindow);
}
}
// Handle all non-dialog windows that haven't been associated with an MsWindow yet. Dialog windows are handled by assignDialogWindows
const windowActors = actors.filter(
(w) =>
!assignedMetaWindows.has(w.metaWindow) &&
!this.isMetaWindowDialog(w.metaWindow)
);
const candidateMsWindows = this.msWindowList.filter(
(x) =>
x.lifecycleState.type === 'app-placeholder' ||
(x.lifecycleState.type === 'window' &&
now - x.lifecycleState.matchedAtTime.getTime() <
MAX_WINDOW_REASSOCIATION_TIME_MS)
);
const groupedMsWindowsByApp = groupBy(candidateMsWindows, (window) => {
assert(
window.lifecycleState.type === 'app-placeholder' ||
window.lifecycleState.type === 'window',
'unreachable'
);
return window.lifecycleState.matchingInfo.appId;
});
const groupedMetaWindowsByApp = groupBy(
windowActors,
(window) => this.windowTracker.get_window_app(window.metaWindow).id
);
const promises = [];
let logged = false;
const logInfoOnce = () => {
if (logged) return;
logged = true;
for (const windowActor of actors) {
Me.log(
`Meta window: ${buildMetaWindowIdentifier(
windowActor.metaWindow
)} title='${
windowActor.metaWindow.title
}' dialog=${this.isMetaWindowDialog(
windowActor.metaWindow
)}`
);
}
for (const msWindow of this.msWindowList) {
if (msWindow.lifecycleState.type === 'app-placeholder') {
Me.log(
`MSWindow: ${JSON.stringify(
msWindow.lifecycleState.matchingInfo
)}`
);
}
}
};
for (const [
groupKey,
windowActorGroup,
] of groupedMetaWindowsByApp.entries()) {
const candidateMsWindows =
groupedMsWindowsByApp.get(groupKey) || [];
const costMatrix: number[][] = [];
for (const windowActor of windowActorGroup) {
const metaWindow = windowActor.metaWindow;
const windowInfo: MsWindowMatchingInfo = {
appId: groupKey,
wmClass: metaWindow.get_wm_class_instance(),
pid: metaWindow.get_pid(),
stableSeq: metaWindow.get_stable_sequence(),
title: metaWindow.title,
};
const costs = candidateMsWindows.map((msWindow) =>
windowMatchingCost(windowInfo, metaWindow, msWindow)
);
// Add N items representing potential new windows at the end.
// In case there are no existing MsWindows, we want to be able to create new ones
for (let i = 0; i < windowActorGroup.length; i++) {
costs.push(INF_COST - 1);
}
costMatrix.push(costs);
}
const { cost, assignments } = weighted_matching(costMatrix);
// The meta window to be assigned to each MsWindow
const msWindowAssignments = new Array<Meta.Window | null>(
candidateMsWindows.length
).fill(null);
for (let i = 0; i < assignments.length; i++) {
const idx = assignments[i];
if (idx < candidateMsWindows.length) {
// Found a good match
msWindowAssignments[idx] = windowActorGroup[i].metaWindow;
}
}
for (let i = 0; i < candidateMsWindows.length; i++) {
const msWindow = candidateMsWindows[i];
if (
msWindow.lifecycleState.type === 'window' &&
msWindow.lifecycleState.metaWindow !==
msWindowAssignments[i]
) {
// The contents of this MsWindow will be replaced.
// This can happen if an application starts and opens multiple windows at the same time (e.g. VSCode restoring several workspaces)
// initially these windows might be associated incorrectly, but once the workspaces have loaded and the window titles get updated
// we can associate them more accurately. This might necessitate swapping some already associated MsWindows.
// For all MsWindows which will need to be changed we first unassign their windows.
logInfoOnce();
// These dialogs will be re-assigned later in the assignDialogWindows function.
msWindow.removeAllDialogs();
msWindow.unsetWindow();
}
}
for (let i = 0; i < assignments.length; i++) {
const idx = assignments[i];
const windowActor = windowActorGroup[i];
if (idx < candidateMsWindows.length) {
// Found a good match
const msWindow = candidateMsWindows[idx];
// If it's still in the 'window' state that means the meta window was already associated correctly
// and we can skip associating it again.
if (msWindow.lifecycleState.type === 'app-placeholder') {
logInfoOnce();
Me.log(
`Associating ${buildMetaWindowIdentifier(
windowActor.metaWindow
)} with ${msWindow.windowIdentifier}`
);
promises.push(
msWindow.setWindow(windowActor.metaWindow)
);
}
} else {
logInfoOnce();
Me.log(
`Creating a new window for ${buildMetaWindowIdentifier(
windowActor.metaWindow
)}`
);
// Did not find a good match, create a new window instead
const { done } = this.createNewMsWindow(
windowActor.metaWindow,
{
msWorkspace:
Me.msWorkspaceManager.determineAppropriateMsWorkspace(
windowActor.metaWindow
),
focus: true,
insert: true,
}
);
promises.push(done);
}
}
}
return Promise.all(promises);
}
/** Assigns dialog windows to existing MsWindows, or creates new MsWindows for them.
*
* Returns a promise which resolves when the first frames of all assigned and newly created windows have been drawn.
* Before this, it is not safe to try to reassign windows because some async functions are still in progress.
*/
private assignDialogWindows(actors: Meta.WindowActor[]): Promise<void[]> {
const assignedMetaWindows = new Set(this.managedMetaWindows);
const promises = [];
for (const windowActor of actors) {
if (windowActor.is_destroyed()) continue;
if (assignedMetaWindows.has(windowActor.metaWindow)) continue;
if (!this.isMetaWindowDialog(windowActor.metaWindow)) continue;
const metaWindow = windowActor.metaWindow;
const app = this.windowTracker.get_window_app(
metaWindow
) as Shell.App | null;
if (app === null) {
// Note: Contrary to what the type definitions say, the get_window_app function can in fact return null.
// This can for example happen with the "gnome-shell" pseudo-window which always seems to exist (but doesn't correspond to anything visible).
continue;
}
// If window is dialog try to find its parent
// The best way to find its parent is with the root ancestor.
let root: MetaWindowWithMsProperties | undefined;
metaWindow.foreach_ancestor((ancestor) => {
if (
!root &&
(ancestor as MetaWindowWithMsProperties).msWindow
) {
root = ancestor;
}
return true;
});
let msWindowFound = root?.msWindow ?? null;
// TODO: It's unclear if this is necessary or if the foreach_ancestor will work for the same cases.
if (msWindowFound === null) {
// Dialogs can specify the window they belong to using the `transient for` property.
// So we check to see if it is specified and it is an msWindow
const transientMetaWindow =
metaWindow.get_transient_for() as MetaWindowWithMsProperties | null;
if (
transientMetaWindow?.msWindow?.lifecycleState.type ===
'window'
) {
msWindowFound = transientMetaWindow.msWindow;
}
}
if (msWindowFound === null) {
// If we still haven't found a window we try to find a regular window with the same PID
const pid = metaWindow.get_pid();
const samePidMsWindowList = this.msWindowList.filter(
(msWindow) => {
return (
msWindow.lifecycleState.type === 'window' &&
msWindow.lifecycleState.metaWindow?.get_pid() ===
pid
);
}
);
// We take the most recently focused msWindow
for (const msWindow of samePidMsWindowList) {
if (
!msWindowFound ||
(msWindow.metaWindow &&
msWindowFound.metaWindow!.get_user_time() <
msWindow.metaWindow.get_user_time())
) {
msWindowFound = msWindow;
}
}
}
if (msWindowFound == null && app) {
// If we still haven't found a window we try to find a window with the same app
const sameAppMsWindowList = this.msWindowList.filter(
(msWindow) => {
return (
(msWindow.lifecycleState.type === 'window' ||
msWindow.lifecycleState.type ===
'app-placeholder') &&
msWindow.app.get_id() == app.get_id()
);
}
);
// We take the most recently focused msWindow, prioritizing regular windows over app placeholders
let bestScore: [number, number] = [0, 0];
for (const msWindow of sameAppMsWindowList) {
const score: [number, number] = [
msWindow.lifecycleState.type === 'window' ? 1 : 0,
msWindow.metaWindow!.get_user_time(),
];
if (
!msWindowFound ||
score[0] > bestScore[0] ||
(score[0] == bestScore[0] && score[1] > bestScore[1])
) {
msWindowFound = msWindow;
bestScore = score;
}
}
}
if (msWindowFound) {
msWindowFound.addDialog(metaWindow);
} else {
// No good existing MsWindow was found, instead we create a new MsWindow just for this dialog.
const { done } = this.createNewMsWindow(
windowActor.metaWindow,
{
msWorkspace:
Me.msWorkspaceManager.determineAppropriateMsWorkspace(
windowActor.metaWindow
),
focus: true,
insert: true,
}
);
promises.push(done);
}
}
return Promise.all(promises);
}
handleExistingMetaWindows() {
if (this.managedMetaWindows.length > 0) {
throw new Error(
'You should only call this function before any windows have been associated'
);
}
for (const windowActor of global.get_window_actors()) {
const metaWindow =
windowActor.metaWindow as MetaWindowWithMsProperties;
// Initialize and reset fields to well defined states.
metaWindow.firstFrameDrawn = true;
metaWindow.firstFrameDrawnPromise = Promise.resolve();
metaWindow.createdAt = metaWindow.user_time;
metaWindow.handledByMaterialShell = false;
metaWindow.msWindow = undefined;
this.onNewMetaWindow(metaWindow);
}
}
onNewMetaWindow(metaWindow: MetaWindowWithMsProperties) {
if (Me.disableInProgress) return;
metaWindow.createdAt = metaWindow.user_time;
const actor = metaWindow.get_compositor_private<Meta.WindowActor>();
if (!this.handleWindow(metaWindow)) {
/* return Me.layout.setActorAbove(metaWindow.get_compositor_private<
Meta.WindowActor
>()); */
const parent = actor.get_parent();
if (parent != global.top_window_group) {
if (parent !== null) parent.remove_child(actor);
global.top_window_group.add_child(actor);
}
return;
}
if (metaWindow.handledByMaterialShell) return;
// This flags if we handle this window or not for the session
metaWindow.handledByMaterialShell = true;
metaWindow.connect('unmanaged', () => {
this.onMetaWindowUnManaged(metaWindow);
});
// Assign windows in the next GLib micro task
this.checkWindowsForAssignationsDebounce.schedule();
}
onMetaWindowUnManaged(metaWindow: MetaWindowWithMsProperties) {
if (Me.disableInProgress || Me.closing) return;
if (metaWindow.msWindow) {
const msWindow = metaWindow.msWindow;
msWindow.metaWindowUnManaged(metaWindow);
}
}
/** Creates a new MsWindow
*
* Returns both the created window and a promise.
* The promise resolves when the first frame of the window has been drawn.
*/
createNewMsWindow(
source: Shell.App | MetaWindowWithMsProperties,
msWorkspace: {
msWorkspace: MsWorkspace;
focus: boolean;
insert: boolean;
},
persistent?: boolean,
initialAllocation?: Rectangular,
matchingInfo?: MsWindowMatchingInfo
) {
// Note: Contrary to what the type definitions say, the get_window_app function can in fact return null.
// This can for example happen with the "gnome-shell" pseudo-window which always seems to exist (but doesn't correspond to anything visible).
const app =
source instanceof Meta.Window
? (this.windowTracker.get_window_app(
source
) as Shell.App | null)
: source;
if (app === null) {
throw new Error(
'The meta window has no associated app. Cannot create window for an unknown app.'
);
}
if (matchingInfo === undefined) {
matchingInfo = {
appId: app.id,
title: undefined,
pid: undefined,
wmClass: undefined,
stableSeq: undefined,
};
} else {
assert(matchingInfo.appId === app.id, 'AppIds do not match');
}
const msWindow = new MsWindow({
app,
persistent,
initialAllocation,
msWorkspace: msWorkspace.msWorkspace,
lifecycleState: {
type: 'app-placeholder',
matchingInfo,
waitingForAppSince: undefined,
},
});
let donePromise;
if (source instanceof Meta.Window) {
donePromise = msWindow.setWindow(source);
} else {
donePromise = Promise.resolve();
}
msWorkspace.msWorkspace.addMsWindowUnchecked(
msWindow,
msWorkspace.focus,
msWorkspace.insert
);
msWindow.connect('request-new-meta-window', () => {
this.openAppForMsWindow(msWindow);
});
msWindow.connect('destroy', () => {
this.msWindowList.splice(this.msWindowList.indexOf(msWindow), 1);
});
this.msWindowList.push(msWindow);
this.emit('ms-window-created', msWindow);
return {
msWindow: msWindow,
done: donePromise,
};
}
async checkWindowsForAssignations() {
await this.assignWindows();
let anyWaiting = false;
const now = new Date();
for (const msWindow of this.msWindowList) {
if (
msWindow.lifecycleState.type === 'app-placeholder' &&
msWindow.lifecycleState.waitingForAppSince !== undefined
) {
if (
now.getTime() -
msWindow.lifecycleState.waitingForAppSince.getTime() >
5000
) {
// This window has been waiting too long for the app to launch. Possibly the window opened and closed very quickly or the app crashed.
msWindow.lifecycleState.waitingForAppSince = undefined;
msWindow.kill();
} else {
anyWaiting = true;
}
}
if (
msWindow.lifecycleState.type === 'window' &&
now.getTime() -
msWindow.lifecycleState.matchedAtTime.getTime() <
MAX_WINDOW_REASSOCIATION_TIME_MS
) {
anyWaiting = true;
}
}
if (anyWaiting) {
// Check again after a small duration
this.checkWindowsForAssignationsDebounce.schedule();
}
}
openAppForMsWindow(msWindow: MsWindow) {
if (msWindow.lifecycleState.type !== 'app-placeholder') {
throw new Error(
'MsWindow must be in the app-placeholder state to be able to open a new app in it.'
);
}
if (msWindow.lifecycleState.matchingInfo === undefined) {
msWindow.lifecycleState.matchingInfo = {
appId: msWindow.app.id,
title: undefined,
pid: undefined,
wmClass: undefined,
stableSeq: undefined,
};
}
msWindow.lifecycleState.waitingForAppSince = new Date();
this.checkWindowsForAssignationsDebounce.schedule();
const workspaceIndex =
Me.msWorkspaceManager.primaryMsWorkspaces.indexOf(
msWindow.msWorkspace
);
msWindow.app.launch(0, workspaceIndex, Shell.AppLaunchGpu.APP_PREF);
}
private handleWindow(metaWindow: MetaWindowWithMsProperties) {
if (
metaWindow.wm_class !== '' &&
getSettings('layouts')
.get_string('windows-excluded')
.split(',')
.map((item) => item.trim())
.indexOf(metaWindow.wm_class) > -1
) {
return false;
}
if (metaWindow.above) {
metaWindow.stick();
return false;
}
const meta = Meta.WindowType;
const types = [
meta.NORMAL,
meta.DIALOG,
meta.MODAL_DIALOG,
meta.UTILITY,
];
return types.includes(metaWindow.window_type);
}
isMetaWindowDialog(metaWindow: Meta.Window) {
const dialogTypes = [
Meta.WindowType.DIALOG,
Meta.WindowType.MODAL_DIALOG,
Meta.WindowType.UTILITY,
];
const isFrozen = !(
metaWindow.allows_resize() && metaWindow.allows_move()
);
const isMaximizedAny =
metaWindow.maximized_horizontally ||
metaWindow.maximized_vertically;
return (
dialogTypes.includes(metaWindow.window_type) ||
(metaWindow.get_transient_for() != null &&
metaWindow.skip_taskbar) ||
!metaWindow.resizeable ||
(isFrozen && !isMaximizedAny)
);
}
destroy() {
super.destroy();
this.msDndManager.destroy();
this.msResizeManager.destroy();
global.get_window_actors().forEach((windowActor) => {
const metaWindow =
windowActor.metaWindow as MetaWindowWithMsProperties;
if (metaWindow.handledByMaterialShell)
delete metaWindow.handledByMaterialShell;
});
}
}
Signals.addSignalMethods(MsWindowManager.prototype); | the_stack |
import React from 'react';
import styled from 'styled-components';
import { Utilities, HostType } from '@microsoft/office-js-helpers';
import queryString from 'query-string';
import cloneDeep from 'lodash/cloneDeep';
import Theme from 'common/lib/components/Theme';
import Console from 'common/lib/components/Console';
import HeaderFooterLayout from 'common/lib/components/HeaderFooterLayout';
import { SCRIPT_URLS, IEditorHeartbeatToRunnerResponse } from 'common/lib/constants';
import { OFFICE_JS_URL_QUERY_PARAMETER_KEY } from 'common/lib/utilities/script-loader/constants';
import Heartbeat from './Heartbeat';
import Header from './Header';
import Footer from './Footer';
import Only from 'common/lib/components/Only';
import SnippetContainer from '../SnippetContainer';
import { currentEditorUrl } from 'common/lib/environment';
import processLibraries from 'common/lib/utilities/process.libraries';
import { showSplashScreen, hideSplashScreen } from 'common/lib/utilities/splash.screen';
import { openPopoutCodeEditor } from 'common/lib/utilities/popout.control';
import { SILENT_SNIPPET_SWITCHING } from '../../../../constants';
const AppWrapper = styled.div`
height: 100vh;
min-height: 100vh;
display: flex;
flex-direction: column;
`;
let logCount = 0;
interface IState {
solution?: ISolution | null;
lastRendered: number | null;
logs: ILogData[];
isConsoleOpen: boolean;
}
export class App extends React.Component<{}, IState> {
private officeJsPageUrlLowerCased: string | null;
private hasRenderedContent = false;
private isTransitioningAwayFromPage = false;
private heartbeatRef: React.RefObject<Heartbeat> = React.createRef();
private snippetContainerRef: React.RefObject<SnippetContainer> = React.createRef();
constructor(props: {}) {
super(props);
this.state = {
solution: undefined,
logs: [],
isConsoleOpen: false,
lastRendered: null,
};
const params = queryString.parse(window.location.search) as {
[OFFICE_JS_URL_QUERY_PARAMETER_KEY]: string;
};
this.officeJsPageUrlLowerCased =
Utilities.host === HostType.WEB
? null
: (
params[OFFICE_JS_URL_QUERY_PARAMETER_KEY] || SCRIPT_URLS.DEFAULT_OFFICE_JS
).toLowerCase();
}
componentDidMount() {
this.monkeypatchConsole();
}
monkeypatchConsole = () => {
['info', 'warn', 'error', 'log'].forEach(method => {
const oldMethod = window.console[method];
window.console[method] = (...args: any[]) => {
try {
// For some reason, in IE, calling the old method results in an error:
// "JavaScript runtime error: Invalid calling object". Hence putting it into the try/catch as well.
oldMethod(...args);
} catch (e) {
// Silently ignore. We'll still get notified via the UI anyway!
}
args.forEach(object =>
/* Note, the setTimeout is critical to make sure the UI doesn't freeze! */
setTimeout(
() =>
this.addLog({
severity: method as ConsoleLogTypes,
object,
}),
0,
),
);
};
});
};
addLog = ({
severity,
object,
}: {
severity: ConsoleLogTypes;
object: string | { [key: string]: any };
}) => {
object = possiblyMassageObject(object);
this.setState({
logs: [...this.state.logs, { id: logCount.toString(), message: object, severity }],
isConsoleOpen: true,
});
logCount++;
};
clearLogs = () => this.setState({ logs: [] });
openConsole = () => this.setState({ isConsoleOpen: true });
closeConsole = () => this.setState({ isConsoleOpen: false });
openCode = () => openPopoutCodeEditor();
onReceiveNewActiveSolution = (solution: ISolution | null) => {
if (solution !== null) {
this.respondToOfficeJsMismatchIfAny(solution);
if (!this.state.solution) {
informSnippetSwitch(`Your snippet "${solution.name}" has been loaded.`);
} else {
informSnippetSwitch(`Switching to snippet "${solution.name}".`);
}
}
this.setState({ solution, logs: [] });
};
onReceivedMessageToPassToUserSnippet = (
message: IEditorHeartbeatToRunnerResponse,
): void => {
this.snippetContainerRef.current.passMessageThroughToIframe(message);
};
softRefresh = () => {
if (this.state.solution) {
this.setState({
solution: { ...this.state.solution, dateLastModified: Date.now() },
logs: [],
});
informSnippetSwitch(
`Your snippet '${this.state.solution.name}' has been reloaded.`,
);
}
};
reloadPage = () => {
this.reloadPageWithDifferentOfficeJsUrl(null);
};
onSnippetRender = ({
lastRendered,
hasContent,
}: {
lastRendered: number;
hasContent: boolean;
}) => {
// If staying on this page (rather than being in the process of reloading)
if (!this.isTransitioningAwayFromPage) {
this.setState({ lastRendered });
if (hasContent) {
this.hasRenderedContent = true;
// Also, hide the loading indicators, if they were still up
hideSplashScreen();
}
}
};
sendMessageFromRunnerToEditor = (message: string) =>
this.heartbeatRef.current.sendMessage(message);
render() {
return (
<Theme host={this.state.solution ? this.state.solution.host : Utilities.host}>
<AppWrapper>
<HeaderFooterLayout
wrapperStyle={{ flex: '6', minHeight: '30rem' }}
header={
<Header
solution={this.state.solution}
refresh={this.softRefresh}
hardRefresh={this.reloadPage}
goBack={
!!queryString.parse(window.location.search).backButton
? () => (window.location.href = currentEditorUrl)
: undefined
}
openCode={this.openCode}
/>
}
footer={
<Footer
isConsoleOpen={this.state.isConsoleOpen}
openConsole={this.openConsole}
closeConsole={this.closeConsole}
isSolutionLoaded={!!this.state.solution}
lastRendered={this.state.lastRendered}
refresh={this.softRefresh}
/>
}
>
<SnippetContainer
ref={this.snippetContainerRef}
solution={this.state.solution}
onRender={this.onSnippetRender}
sendMessageFromRunnerToEditor={this.sendMessageFromRunnerToEditor}
/>
</HeaderFooterLayout>
<Only when={this.state.isConsoleOpen}>
<Console
style={{ flex: '4', minHeight: '5rem' }}
logs={this.state.logs}
clearLogs={this.clearLogs}
/>
</Only>
</AppWrapper>
<Heartbeat
ref={this.heartbeatRef}
host={Utilities.host}
onReceiveNewActiveSolution={this.onReceiveNewActiveSolution}
onReceivedMessageToPassToUserSnippet={this.onReceivedMessageToPassToUserSnippet}
/>
</Theme>
);
}
/////////////////////////
// Note: need a separate helper function rather than re-using
// the "reloadPage", because that one is used by a click handler --
// and thus will get invoked with an object-based click-event parameter
// rather than a string, messing up the reload.
private reloadPageWithDifferentOfficeJsUrl(newOfficeJsUrl: string | null) {
const currentQueryParams: { [key: string]: any } = queryString.parse(
window.location.search,
);
const isDifferentOfficeJs =
newOfficeJsUrl &&
newOfficeJsUrl !== currentQueryParams[OFFICE_JS_URL_QUERY_PARAMETER_KEY];
if (isDifferentOfficeJs) {
const newParams = {
...currentQueryParams,
[OFFICE_JS_URL_QUERY_PARAMETER_KEY]: newOfficeJsUrl,
};
// Set the search, which will force a reload
window.location.search = queryString.stringify(newParams);
} else {
window.location.reload();
}
}
private respondToOfficeJsMismatchIfAny(solution: ISolution) {
const librariesFile = solution.files.find(file => file.name === 'libraries.txt');
if (!librariesFile || !librariesFile.content) {
return;
}
const newOfficeJsUrl = processLibraries(
librariesFile.content,
Utilities.host !== HostType.WEB /*isInsideOffice*/,
).officeJs;
const isMismatched = (() => {
if (this.officeJsPageUrlLowerCased && newOfficeJsUrl) {
return this.officeJsPageUrlLowerCased !== newOfficeJsUrl.toLowerCase();
}
return false;
})();
if (isMismatched) {
// On reloading Office.js (and if had already shown a snippet before),
// show a visual indication to explain the reload.
// Otherwise, if hasn't rendered any snippet before (i.e., it's a first navigation,
// straight to an office.js beta snippet, don't change out the title, keep as is
// so that the load appears continuous).
if (this.hasRenderedContent) {
showSplashScreen('Re-loading office.js, please wait...');
}
this.isTransitioningAwayFromPage = true;
this.reloadPageWithDifferentOfficeJsUrl(newOfficeJsUrl!);
}
}
}
function informSnippetSwitch(message: string) {
if (!SILENT_SNIPPET_SWITCHING) {
console.log(message);
}
}
function possiblyMassageObject(object: any): any {
// For ClientResult objects, create a snapshot, so that the console output doesn't get modified later
// when the object resolves itself (both in UI and in copy-to-clipboard)
// Arguably, this should be the case with the other objects as well, but it gets harder to do
// (circular references and etc.)
// Whereas fixing it for ClientResult is easy-to-fix, and has more visible results:
if (
typeof OfficeExtension !== 'undefined' &&
object instanceof OfficeExtension.ClientResult
) {
return getDataForClientResult(object);
}
return object;
}
function getDataForClientResult(
result: OfficeExtension.ClientResult<any>,
): { value: any } {
let value: any;
try {
value = cloneDeep(result.value);
} catch (e) {
value = '<Could not read the value. You must first call `context.sync()`.';
}
return { value: value };
}
export default App; | the_stack |
declare module com {
export module couchbase {
export module lite {
export abstract class AbstractDatabase {
public static class: java.lang.Class<com.couchbase.lite.AbstractDatabase>;
public static TAG: string;
public static DB_EXTENSION: string;
public static MAX_CHANGES: number;
public static DEFAULT_DATABASE_FLAGS: number;
public name: string;
public config: com.couchbase.lite.DatabaseConfiguration;
public c4db: com.couchbase.litecore.C4Database;
public postExecutor: java.util.concurrent.ScheduledExecutorService;
public queryExecutor: java.util.concurrent.ScheduledExecutorService;
public dbChangeNotifier: com.couchbase.lite.ChangeNotifier<com.couchbase.lite.DatabaseChange>;
public c4DBObserver: com.couchbase.litecore.C4DatabaseObserver;
public docChangeNotifiers: java.util.Map<string,com.couchbase.lite.DocumentChangeNotifier>;
public sharedKeys: com.couchbase.litecore.SharedKeys;
public activeReplications: java.util.Set<com.couchbase.lite.Replicator>;
public activeLiveQueries: java.util.Set<com.couchbase.lite.LiveQuery>;
public lock: any;
public constructor(param0: string, param1: com.couchbase.lite.DatabaseConfiguration);
public addDocumentChangeListener(param0: string, param1: com.couchbase.lite.DocumentChangeListener): com.couchbase.lite.ListenerToken;
public finalize(): void;
public save(param0: com.couchbase.lite.MutableDocument, param1: com.couchbase.lite.ConcurrencyControl): boolean;
public static exists(param0: string, param1: java.io.File): boolean;
public compact(): void;
public createIndex(param0: string, param1: com.couchbase.lite.Index): void;
public inBatch(param0: java.lang.Runnable): void;
public delete(): void;
public save(param0: com.couchbase.lite.MutableDocument): void;
public delete(param0: com.couchbase.lite.Document): void;
public close(): void;
public removeChangeListener(param0: com.couchbase.lite.ListenerToken): void;
public static setLogLevel(param0: com.couchbase.lite.LogDomain, param1: com.couchbase.lite.LogLevel): void;
public getName(): string;
public getCount(): number;
public getDocument(param0: string): com.couchbase.lite.Document;
public getPath(): string;
public addChangeListener(param0: com.couchbase.lite.DatabaseChangeListener): com.couchbase.lite.ListenerToken;
public toString(): string;
public addDocumentChangeListener(param0: string, param1: java.util.concurrent.Executor, param2: com.couchbase.lite.DocumentChangeListener): com.couchbase.lite.ListenerToken;
public getConfig(): com.couchbase.lite.DatabaseConfiguration;
public purge(param0: com.couchbase.lite.Document): void;
public getIndexes(): java.util.List<string>;
public delete(param0: com.couchbase.lite.Document, param1: com.couchbase.lite.ConcurrencyControl): boolean;
public static delete(param0: string, param1: java.io.File): void;
public deleteIndex(param0: string): void;
public static copy(param0: java.io.File, param1: string, param2: com.couchbase.lite.DatabaseConfiguration): void;
public addChangeListener(param0: java.util.concurrent.Executor, param1: com.couchbase.lite.DatabaseChangeListener): com.couchbase.lite.ListenerToken;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export abstract class AbstractIndex extends com.couchbase.lite.Index {
public static class: java.lang.Class<com.couchbase.lite.AbstractIndex>;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export abstract class AbstractQuery extends com.couchbase.lite.Query {
public static class: java.lang.Class<com.couchbase.lite.AbstractQuery>;
public execute(): com.couchbase.lite.ResultSet;
public addChangeListener(param0: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public removeChangeListener(param0: com.couchbase.lite.ListenerToken): void;
public getParameters(): com.couchbase.lite.Parameters;
public finalize(): void;
public setParameters(param0: com.couchbase.lite.Parameters): void;
public toString(): string;
public addChangeListener(param0: java.util.concurrent.Executor, param1: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public explain(): string;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export abstract class AbstractReplicator extends com.couchbase.lite.NetworkReachabilityListener {
public static class: java.lang.Class<com.couchbase.lite.AbstractReplicator>;
public static TAG: string;
public config: com.couchbase.lite.ReplicatorConfiguration;
public stop(): void;
public getConfig(): com.couchbase.lite.ReplicatorConfiguration;
public removeChangeListener(param0: com.couchbase.lite.ListenerToken): void;
public start(): void;
public addChangeListener(param0: com.couchbase.lite.ReplicatorChangeListener): com.couchbase.lite.ListenerToken;
public getStatus(): com.couchbase.lite.AbstractReplicator.Status;
public constructor(param0: com.couchbase.lite.ReplicatorConfiguration);
public finalize(): void;
public resetCheckpoint(): void;
public toString(): string;
public addChangeListener(param0: java.util.concurrent.Executor, param1: com.couchbase.lite.ReplicatorChangeListener): com.couchbase.lite.ListenerToken;
}
export module AbstractReplicator {
export class ActivityLevel {
public static class: java.lang.Class<com.couchbase.lite.AbstractReplicator.ActivityLevel>;
public static STOPPED: com.couchbase.lite.AbstractReplicator.ActivityLevel;
public static OFFLINE: com.couchbase.lite.AbstractReplicator.ActivityLevel;
public static CONNECTING: com.couchbase.lite.AbstractReplicator.ActivityLevel;
public static IDLE: com.couchbase.lite.AbstractReplicator.ActivityLevel;
public static BUSY: com.couchbase.lite.AbstractReplicator.ActivityLevel;
public static values(): native.Array<com.couchbase.lite.AbstractReplicator.ActivityLevel>;
public static valueOf(param0: string): com.couchbase.lite.AbstractReplicator.ActivityLevel;
}
export class Progress {
public static class: java.lang.Class<com.couchbase.lite.AbstractReplicator.Progress>;
public getTotal(): number;
public toString(): string;
public getCompleted(): number;
}
export class Status {
public static class: java.lang.Class<com.couchbase.lite.AbstractReplicator.Status>;
public getActivityLevel(): com.couchbase.lite.AbstractReplicator.ActivityLevel;
public toString(): string;
public getProgress(): com.couchbase.lite.AbstractReplicator.Progress;
public constructor(param0: com.couchbase.litecore.C4ReplicatorStatus);
public getError(): com.couchbase.lite.CouchbaseLiteException;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class AndroidNetworkReachabilityManager extends com.couchbase.lite.NetworkReachabilityManager {
public static class: java.lang.Class<com.couchbase.lite.AndroidNetworkReachabilityManager>;
}
export module AndroidNetworkReachabilityManager {
export class NetworkReceiver {
public static class: java.lang.Class<com.couchbase.lite.AndroidNetworkReachabilityManager.NetworkReceiver>;
public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Array extends java.lang.Object {
public static class: java.lang.Class<com.couchbase.lite.Array>;
public _sharedLock: any;
public getDouble(param0: number): number;
public getString(param0: number): string;
public getDictionary(param0: number): com.couchbase.lite.DictionaryInterface;
public getNumber(param0: number): java.lang.Number;
public iterator(): java.util.Iterator<any>;
public getDate(param0: number): java.util.Date;
public toMutable(): com.couchbase.lite.MutableArray;
public getBoolean(param0: number): boolean;
public getDictionary(param0: number): com.couchbase.lite.Dictionary;
public getBlob(param0: number): com.couchbase.lite.Blob;
public toList(): java.util.List<any>;
public hashCode(): number;
public getLong(param0: number): number;
public equals(param0: any): boolean;
public getValue(param0: number): any;
public count(): number;
public getInt(param0: number): number;
public encodeTo(param0: com.couchbase.litecore.fleece.FLEncoder): void;
public getArray(param0: number): com.couchbase.lite.ArrayInterface;
public getFloat(param0: number): number;
public getArray(param0: number): com.couchbase.lite.Array;
}
export module Array {
export class ArrayIterator extends java.util.Iterator<any> {
public static class: java.lang.Class<com.couchbase.lite.Array.ArrayIterator>;
public next(): any;
public hasNext(): boolean;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ArrayExpression {
public static class: java.lang.Class<com.couchbase.lite.ArrayExpression>;
public static anyAndEvery(param0: com.couchbase.lite.VariableExpression): com.couchbase.lite.ArrayExpressionIn;
public static variable(param0: string): com.couchbase.lite.VariableExpression;
public static every(param0: com.couchbase.lite.VariableExpression): com.couchbase.lite.ArrayExpressionIn;
public static any(param0: com.couchbase.lite.VariableExpression): com.couchbase.lite.ArrayExpressionIn;
}
export module ArrayExpression {
export class QuantifiesType {
public static class: java.lang.Class<com.couchbase.lite.ArrayExpression.QuantifiesType>;
public static ANY: com.couchbase.lite.ArrayExpression.QuantifiesType;
public static ANY_AND_EVERY: com.couchbase.lite.ArrayExpression.QuantifiesType;
public static EVERY: com.couchbase.lite.ArrayExpression.QuantifiesType;
public static values(): native.Array<com.couchbase.lite.ArrayExpression.QuantifiesType>;
public static valueOf(param0: string): com.couchbase.lite.ArrayExpression.QuantifiesType;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ArrayExpressionIn {
public static class: java.lang.Class<com.couchbase.lite.ArrayExpressionIn>;
public in(param0: com.couchbase.lite.Expression): com.couchbase.lite.ArrayExpressionSatisfies;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ArrayExpressionSatisfies {
public static class: java.lang.Class<com.couchbase.lite.ArrayExpressionSatisfies>;
public satisfies(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
}
export module ArrayExpressionSatisfies {
export class QuantifiedExpression extends com.couchbase.lite.Expression {
public static class: java.lang.Class<com.couchbase.lite.ArrayExpressionSatisfies.QuantifiedExpression>;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ArrayFunction {
public static class: java.lang.Class<com.couchbase.lite.ArrayFunction>;
public static contains(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static length(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ArrayInterface {
public static class: java.lang.Class<com.couchbase.lite.ArrayInterface>;
/**
* Constructs a new instance of the com.couchbase.lite.ArrayInterface interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
count(): number;
getValue(param0: number): any;
getString(param0: number): string;
getNumber(param0: number): java.lang.Number;
getInt(param0: number): number;
getLong(param0: number): number;
getFloat(param0: number): number;
getDouble(param0: number): number;
getBoolean(param0: number): boolean;
getBlob(param0: number): com.couchbase.lite.Blob;
getDate(param0: number): java.util.Date;
getArray(param0: number): com.couchbase.lite.ArrayInterface;
getDictionary(param0: number): com.couchbase.lite.DictionaryInterface;
toList(): java.util.List<any>;
});
public constructor();
public getDouble(param0: number): number;
public getString(param0: number): string;
public getDictionary(param0: number): com.couchbase.lite.DictionaryInterface;
public getNumber(param0: number): java.lang.Number;
public getDate(param0: number): java.util.Date;
public getBoolean(param0: number): boolean;
public getBlob(param0: number): com.couchbase.lite.Blob;
public toList(): java.util.List<any>;
public getLong(param0: number): number;
public getValue(param0: number): any;
public count(): number;
public getInt(param0: number): number;
public getArray(param0: number): com.couchbase.lite.ArrayInterface;
public getFloat(param0: number): number;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export abstract class Authenticator {
public static class: java.lang.Class<com.couchbase.lite.Authenticator>;
public constructor();
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class BasicAuthenticator extends com.couchbase.lite.Authenticator {
public static class: java.lang.Class<com.couchbase.lite.BasicAuthenticator>;
public getUsername(): string;
public getPassword(): string;
public constructor(param0: string, param1: string);
public constructor();
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Blob extends com.couchbase.litecore.fleece.FLEncodable {
public static class: java.lang.Class<com.couchbase.lite.Blob>;
public getContentType(): string;
public digest(): string;
public constructor(param0: string, param1: java.net.URL);
public length(): number;
public getContent(): native.Array<number>;
public toString(): string;
public getContentStream(): java.io.InputStream;
public getProperties(): java.util.Map<string,any>;
public hashCode(): number;
public equals(param0: any): boolean;
public constructor(param0: string, param1: native.Array<number>);
public encodeTo(param0: com.couchbase.litecore.fleece.FLEncoder): void;
public constructor(param0: string, param1: java.io.InputStream);
}
export module Blob {
export class BlobInputStream {
public static class: java.lang.Class<com.couchbase.lite.Blob.BlobInputStream>;
public read(): number;
public read(param0: native.Array<number>, param1: number, param2: number): number;
public read(param0: native.Array<number>): number;
public skip(param0: number): number;
public close(): void;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class BuildConfig {
public static class: java.lang.Class<com.couchbase.lite.BuildConfig>;
public static DEBUG: boolean;
public static APPLICATION_ID: string;
public static BUILD_TYPE: string;
public static FLAVOR: string;
public static VERSION_CODE: number;
public static VERSION_NAME: string;
public static BUILD_NO: number;
public static GitHash: string;
public constructor();
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class CBLConverter {
public static class: java.lang.Class<com.couchbase.lite.CBLConverter>;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class CBLError {
public static class: java.lang.Class<com.couchbase.lite.CBLError>;
/**
* Constructs a new instance of the com.couchbase.lite.CBLError interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
export module CBLError {
export class Code {
public static class: java.lang.Class<com.couchbase.lite.CBLError.Code>;
/**
* Constructs a new instance of the com.couchbase.lite.CBLError$Code interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static CBLErrorTransactionNotClosed: number;
public static CBLErrorTLSCertUntrusted: number;
public static CBLErrorTLSCertExpired: number;
public static CBLErrorNotWriteable: number;
public static CBLErrorNotADatabaseFile: number;
public static CBLErrorWebSocketAbnormalClose: number;
public static CBLErrorInvalidParameter: number;
public static CBLErrorHTTPBase: number;
public static CBLErrorUnsupported: number;
public static CBLErrorWebSocketPolicyError: number;
public static CBLErrorConflict: number;
public static CBLErrorTLSClientCertRequired: number;
public static CBLErrorNotFound: number;
public static CBLErrorWrongFormat: number;
public static CBLErrorAssertionFailed: number;
public static CBLErrorWebSocketProtocolError: number;
public static CBLErrorUnimplemented: number;
public static CBLErrorInvalidRedirect: number;
public static CBLErrorWebSocketGoingAway: number;
public static CBLErrorNetworkBase: number;
public static CBLErrorUnexpectedError: number;
public static CBLErrorInvalidQuery: number;
public static CBLErrorTimeout: number;
public static CBLErrorTLSHandshakeFailed: number;
public static CBLErrorHTTPEntityTooLarge: number;
public static CBLErrorHTTPConflict: number;
public static CBLErrorDatabaseTooNew: number;
public static CBLErrorNotOpen: number;
public static CBLErrorWebSocketCloseUserPermanent: number;
public static CBLErrorCorruptRevisionData: number;
public static CBLErrorDatabaseTooOld: number;
public static CBLErrorTooManyRedirects: number;
public static CBLErrorHTTPProxyAuthRequired: number;
public static CBLErrorInvalidQueryParam: number;
public static CBLErrorCantOpenFile: number;
public static CBLErrorWebSocketBadMessageFormat: number;
public static CBLErrorCrypto: number;
public static CBLErrorBusy: number;
public static CBLErrorDNSFailure: number;
public static CBLErrorHTTPInternalServerError: number;
public static CBLErrorNotInTransaction: number;
public static CBLErrorHTTPImATeapot: number;
public static CBLErrorTLSCertUnknownRoot: number;
public static CBLErrorHTTPAuthRequired: number;
public static CBLErrorUnknownHost: number;
public static CBLErrorInvalidURL: number;
public static CBLErrorTLSClientCertRejected: number;
public static CBLErrorWebSocketDataError: number;
public static CBLErrorWebSocketMessageTooBig: number;
public static CBLErrorHTTPNotFound: number;
public static CBLErrorHTTPNotImplemented: number;
public static CBLErrorHTTPForbidden: number;
public static CBLErrorBadRevisionID: number;
public static CBLErrorMemoryError: number;
public static CBLErrorMissingIndex: number;
public static CBLErrorRemoteError: number;
public static CBLErrorBadDocID: number;
public static CBLErrorWebSocketBase: number;
public static CBLErrorWebSocketMissingExtension: number;
public static CBLErrorUnsupportedEncryption: number;
public static CBLErrorWebSocketCloseUserTransient: number;
public static CBLErrorCorruptData: number;
public static CBLErrorHTTPServiceUnavailable: number;
public static CBLErrorIOError: number;
public static CBLErrorWebSocketCantFulfill: number;
public static CBLErrorCantUpgradeDatabase: number;
}
export class Domain {
public static class: java.lang.Class<com.couchbase.lite.CBLError.Domain>;
/**
* Constructs a new instance of the com.couchbase.lite.CBLError$Domain interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static FleeceErrorDomain: string;
public static CBLErrorDomain: string;
public static SQLiteErrorDomain: string;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class CBLStatus {
public static class: java.lang.Class<com.couchbase.lite.CBLStatus>;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class CBLVersion {
public static class: java.lang.Class<com.couchbase.lite.CBLVersion>;
public constructor();
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ChangeListener<ChangeType> extends java.lang.Object {
public static class: java.lang.Class<com.couchbase.lite.ChangeListener<any>>;
/**
* Constructs a new instance of the com.couchbase.lite.ChangeListener<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
changed(param0: ChangeType): void;
});
public constructor();
public changed(param0: ChangeType): void;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ChangeListenerToken<ChangeType> extends com.couchbase.lite.ListenerToken {
public static class: java.lang.Class<com.couchbase.lite.ChangeListenerToken<any>>;
public getKey(): any;
public setKey(param0: any): void;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ChangeNotifier<ChangeType> extends java.lang.Object {
public static class: java.lang.Class<com.couchbase.lite.ChangeNotifier<any>>;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Collation {
public static class: java.lang.Class<com.couchbase.lite.Collation>;
public static ascii(): com.couchbase.lite.Collation.ASCII;
public static unicode(): com.couchbase.lite.Collation.Unicode;
public toString(): string;
}
export module Collation {
export class ASCII extends com.couchbase.lite.Collation {
public static class: java.lang.Class<com.couchbase.lite.Collation.ASCII>;
public ignoreCase(param0: boolean): com.couchbase.lite.Collation.ASCII;
}
export class Unicode extends com.couchbase.lite.Collation {
public static class: java.lang.Class<com.couchbase.lite.Collation.Unicode>;
public locale(param0: string): com.couchbase.lite.Collation.Unicode;
public ignoreCase(param0: boolean): com.couchbase.lite.Collation.Unicode;
public ignoreAccents(param0: boolean): com.couchbase.lite.Collation.Unicode;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ConcurrencyControl {
public static class: java.lang.Class<com.couchbase.lite.ConcurrencyControl>;
public static LAST_WRITE_WINS: com.couchbase.lite.ConcurrencyControl;
public static FAIL_ON_CONFLICT: com.couchbase.lite.ConcurrencyControl;
public static values(): native.Array<com.couchbase.lite.ConcurrencyControl>;
public static valueOf(param0: string): com.couchbase.lite.ConcurrencyControl;
public getValue(): number;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class CouchbaseLiteException implements com.couchbase.lite.CBLError.Domain {
public static class: java.lang.Class<com.couchbase.lite.CouchbaseLiteException>;
public constructor(param0: string, param1: string, param2: number);
public constructor(param0: string, param1: number, param2: java.lang.Throwable);
public getInfo(): java.util.Map<string,any>;
public constructor(param0: string, param1: java.lang.Throwable, param2: string, param3: number);
public constructor(param0: string, param1: number);
public getCode(): number;
public getDomain(): string;
public constructor(param0: string, param1: number, param2: java.util.Map<string,any>);
public toString(): string;
public constructor(param0: java.lang.Throwable);
public constructor(param0: string);
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class DataSource {
public static class: java.lang.Class<com.couchbase.lite.DataSource>;
public static database(param0: com.couchbase.lite.Database): com.couchbase.lite.DataSource.As;
}
export module DataSource {
export class As extends com.couchbase.lite.DataSource {
public static class: java.lang.Class<com.couchbase.lite.DataSource.As>;
public as(param0: string): com.couchbase.lite.DataSource;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Database extends com.couchbase.lite.AbstractDatabase {
public static class: java.lang.Class<com.couchbase.lite.Database>;
public constructor(param0: string, param1: com.couchbase.lite.DatabaseConfiguration);
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class DatabaseChange {
public static class: java.lang.Class<com.couchbase.lite.DatabaseChange>;
public getDocumentIDs(): java.util.List<string>;
public toString(): string;
public getDatabase(): com.couchbase.lite.Database;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class DatabaseChangeListener extends com.couchbase.lite.ChangeListener<com.couchbase.lite.DatabaseChange> {
public static class: java.lang.Class<com.couchbase.lite.DatabaseChangeListener>;
/**
* Constructs a new instance of the com.couchbase.lite.DatabaseChangeListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
changed(param0: com.couchbase.lite.DatabaseChange): void;
changed(param0: any): void;
});
public constructor();
public changed(param0: com.couchbase.lite.DatabaseChange): void;
public changed(param0: any): void;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class DatabaseConfiguration {
public static class: java.lang.Class<com.couchbase.lite.DatabaseConfiguration>;
public constructor(param0: globalAndroid.content.Context);
public setDirectory(param0: string): com.couchbase.lite.DatabaseConfiguration;
public constructor(param0: com.couchbase.lite.DatabaseConfiguration);
public getDirectory(): string;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class DefaultExecutor {
public static class: java.lang.Class<com.couchbase.lite.DefaultExecutor>;
public static instance(): com.couchbase.lite.DefaultExecutor;
public execute(param0: java.lang.Runnable): void;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Dictionary extends java.lang.Object {
public static class: java.lang.Class<com.couchbase.lite.Dictionary>;
public _sharedLock: any;
public finalize(): void;
public getKeys(): java.util.List<string>;
public getValue(param0: string): any;
public getDictionary(param0: string): com.couchbase.lite.DictionaryInterface;
public getNumber(param0: string): java.lang.Number;
public toMutable(): com.couchbase.lite.MutableDictionary;
public contains(param0: string): boolean;
public hashCode(): number;
public getBoolean(param0: string): boolean;
public getDictionary(param0: string): com.couchbase.lite.Dictionary;
public equals(param0: any): boolean;
public getString(param0: string): string;
public getFloat(param0: string): number;
public getBlob(param0: string): com.couchbase.lite.Blob;
public isEmpty(): boolean;
public getLong(param0: string): number;
public getDouble(param0: string): number;
public getArray(param0: string): com.couchbase.lite.ArrayInterface;
public getDate(param0: string): java.util.Date;
public iterator(): java.util.Iterator<string>;
public count(): number;
public encodeTo(param0: com.couchbase.litecore.fleece.FLEncoder): void;
public toMap(): java.util.Map<string,any>;
public getInt(param0: string): number;
public getArray(param0: string): com.couchbase.lite.Array;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class DictionaryInterface {
public static class: java.lang.Class<com.couchbase.lite.DictionaryInterface>;
/**
* Constructs a new instance of the com.couchbase.lite.DictionaryInterface interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
count(): number;
getKeys(): java.util.List<string>;
getValue(param0: string): any;
getString(param0: string): string;
getNumber(param0: string): java.lang.Number;
getInt(param0: string): number;
getLong(param0: string): number;
getFloat(param0: string): number;
getDouble(param0: string): number;
getBoolean(param0: string): boolean;
getBlob(param0: string): com.couchbase.lite.Blob;
getDate(param0: string): java.util.Date;
getArray(param0: string): com.couchbase.lite.ArrayInterface;
getDictionary(param0: string): com.couchbase.lite.DictionaryInterface;
toMap(): java.util.Map<string,any>;
contains(param0: string): boolean;
});
public constructor();
public getLong(param0: string): number;
public getKeys(): java.util.List<string>;
public getValue(param0: string): any;
public getDictionary(param0: string): com.couchbase.lite.DictionaryInterface;
public getNumber(param0: string): java.lang.Number;
public getDouble(param0: string): number;
public getArray(param0: string): com.couchbase.lite.ArrayInterface;
public contains(param0: string): boolean;
public getDate(param0: string): java.util.Date;
public getBoolean(param0: string): boolean;
public getString(param0: string): string;
public getFloat(param0: string): number;
public count(): number;
public getBlob(param0: string): com.couchbase.lite.Blob;
public toMap(): java.util.Map<string,any>;
public getInt(param0: string): number;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class DocContext extends com.couchbase.litecore.fleece.MContext {
public static class: java.lang.Class<com.couchbase.lite.DocContext>;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Document extends java.lang.Object {
public static class: java.lang.Class<com.couchbase.lite.Document>;
public getId(): string;
public getSequence(): number;
public finalize(): void;
public getKeys(): java.util.List<string>;
public toMutable(): com.couchbase.lite.MutableDocument;
public getValue(param0: string): any;
public getDictionary(param0: string): com.couchbase.lite.DictionaryInterface;
public getNumber(param0: string): java.lang.Number;
public contains(param0: string): boolean;
public hashCode(): number;
public getBoolean(param0: string): boolean;
public getDictionary(param0: string): com.couchbase.lite.Dictionary;
public equals(param0: any): boolean;
public getString(param0: string): string;
public getFloat(param0: string): number;
public getBlob(param0: string): com.couchbase.lite.Blob;
public getLong(param0: string): number;
public getDouble(param0: string): number;
public getArray(param0: string): com.couchbase.lite.ArrayInterface;
public getDate(param0: string): java.util.Date;
public iterator(): java.util.Iterator<string>;
public count(): number;
public toMap(): java.util.Map<string,any>;
public getInt(param0: string): number;
public getArray(param0: string): com.couchbase.lite.Array;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class DocumentChange {
public static class: java.lang.Class<com.couchbase.lite.DocumentChange>;
public getDocumentID(): string;
public toString(): string;
public getDatabase(): com.couchbase.lite.Database;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class DocumentChangeListener extends com.couchbase.lite.ChangeListener<com.couchbase.lite.DocumentChange> {
public static class: java.lang.Class<com.couchbase.lite.DocumentChangeListener>;
/**
* Constructs a new instance of the com.couchbase.lite.DocumentChangeListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
changed(param0: com.couchbase.lite.DocumentChange): void;
changed(param0: any): void;
});
public constructor();
public changed(param0: com.couchbase.lite.DocumentChange): void;
public changed(param0: any): void;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class DocumentChangeNotifier extends com.couchbase.lite.ChangeNotifier<com.couchbase.lite.DocumentChange> {
public static class: java.lang.Class<com.couchbase.lite.DocumentChangeNotifier>;
public finalize(): void;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Endpoint {
public static class: java.lang.Class<com.couchbase.lite.Endpoint>;
/**
* Constructs a new instance of the com.couchbase.lite.Endpoint interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export abstract class Expression {
public static class: java.lang.Class<com.couchbase.lite.Expression>;
public static parameter(param0: string): com.couchbase.lite.Expression;
public static negated(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public modulo(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public is(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public between(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static string(param0: string): com.couchbase.lite.Expression;
public isNot(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public collate(param0: com.couchbase.lite.Collation): com.couchbase.lite.Expression;
public in(param0: native.Array<com.couchbase.lite.Expression>): com.couchbase.lite.Expression;
public add(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static booleanValue(param0: boolean): com.couchbase.lite.Expression;
public static property(param0: string): com.couchbase.lite.PropertyExpression;
public static number(param0: java.lang.Number): com.couchbase.lite.Expression;
public static doubleValue(param0: number): com.couchbase.lite.Expression;
public isNullOrMissing(): com.couchbase.lite.Expression;
public static all(): com.couchbase.lite.PropertyExpression;
public greaterThan(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static date(param0: java.util.Date): com.couchbase.lite.Expression;
public divide(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public notEqualTo(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public greaterThanOrEqualTo(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public like(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public subtract(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static not(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static floatValue(param0: number): com.couchbase.lite.Expression;
public and(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public or(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public lessThanOrEqualTo(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public toString(): string;
public lessThan(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static value(param0: any): com.couchbase.lite.Expression;
public static longValue(param0: number): com.couchbase.lite.Expression;
public notNullOrMissing(): com.couchbase.lite.Expression;
public regex(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public equalTo(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static intValue(param0: number): com.couchbase.lite.Expression;
public multiply(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
}
export module Expression {
export class AggregateExpression extends com.couchbase.lite.Expression {
public static class: java.lang.Class<com.couchbase.lite.Expression.AggregateExpression>;
public getExpressions(): java.util.List<com.couchbase.lite.Expression>;
}
export class BinaryExpression extends com.couchbase.lite.Expression {
public static class: java.lang.Class<com.couchbase.lite.Expression.BinaryExpression>;
}
export module BinaryExpression {
export class OpType {
public static class: java.lang.Class<com.couchbase.lite.Expression.BinaryExpression.OpType>;
public static Add: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static Between: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static Divide: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static EqualTo: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static GreaterThan: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static GreaterThanOrEqualTo: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static In: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static Is: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static IsNot: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static LessThan: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static LessThanOrEqualTo: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static Like: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static Modulus: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static Multiply: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static NotEqualTo: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static Subtract: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static RegexLike: com.couchbase.lite.Expression.BinaryExpression.OpType;
public static values(): native.Array<com.couchbase.lite.Expression.BinaryExpression.OpType>;
public static valueOf(param0: string): com.couchbase.lite.Expression.BinaryExpression.OpType;
}
}
export class CollationExpression extends com.couchbase.lite.Expression {
public static class: java.lang.Class<com.couchbase.lite.Expression.CollationExpression>;
}
export class CompoundExpression extends com.couchbase.lite.Expression {
public static class: java.lang.Class<com.couchbase.lite.Expression.CompoundExpression>;
}
export module CompoundExpression {
export class OpType {
public static class: java.lang.Class<com.couchbase.lite.Expression.CompoundExpression.OpType>;
public static And: com.couchbase.lite.Expression.CompoundExpression.OpType;
public static Or: com.couchbase.lite.Expression.CompoundExpression.OpType;
public static Not: com.couchbase.lite.Expression.CompoundExpression.OpType;
public static valueOf(param0: string): com.couchbase.lite.Expression.CompoundExpression.OpType;
public static values(): native.Array<com.couchbase.lite.Expression.CompoundExpression.OpType>;
}
}
export class FunctionExpresson extends com.couchbase.lite.Expression {
public static class: java.lang.Class<com.couchbase.lite.Expression.FunctionExpresson>;
}
export class ParameterExpression extends com.couchbase.lite.Expression {
public static class: java.lang.Class<com.couchbase.lite.Expression.ParameterExpression>;
}
export class UnaryExpression extends com.couchbase.lite.Expression {
public static class: java.lang.Class<com.couchbase.lite.Expression.UnaryExpression>;
}
export module UnaryExpression {
export class OpType {
public static class: java.lang.Class<com.couchbase.lite.Expression.UnaryExpression.OpType>;
public static Missing: com.couchbase.lite.Expression.UnaryExpression.OpType;
public static NotMissing: com.couchbase.lite.Expression.UnaryExpression.OpType;
public static NotNull: com.couchbase.lite.Expression.UnaryExpression.OpType;
public static Null: com.couchbase.lite.Expression.UnaryExpression.OpType;
public static valueOf(param0: string): com.couchbase.lite.Expression.UnaryExpression.OpType;
public static values(): native.Array<com.couchbase.lite.Expression.UnaryExpression.OpType>;
}
}
export class ValueExpression extends com.couchbase.lite.Expression {
public static class: java.lang.Class<com.couchbase.lite.Expression.ValueExpression>;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Fleece extends com.couchbase.litecore.fleece.FLConstants.FLValueType {
public static class: java.lang.Class<com.couchbase.lite.Fleece>;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class From extends com.couchbase.lite.AbstractQuery implements com.couchbase.lite.JoinRouter, com.couchbase.lite.WhereRouter, com.couchbase.lite.GroupByRouter, com.couchbase.lite.OrderByRouter, com.couchbase.lite.LimitRouter {
public static class: java.lang.Class<com.couchbase.lite.From>;
public addChangeListener(param0: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public removeChangeListener(param0: com.couchbase.lite.ListenerToken): void;
public setParameters(param0: com.couchbase.lite.Parameters): void;
public addChangeListener(param0: java.util.concurrent.Executor, param1: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public explain(): string;
public execute(): com.couchbase.lite.ResultSet;
public limit(param0: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
public limit(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
public getParameters(): com.couchbase.lite.Parameters;
public join(param0: native.Array<com.couchbase.lite.Join>): com.couchbase.lite.Joins;
public where(param0: com.couchbase.lite.Expression): com.couchbase.lite.Where;
public orderBy(param0: native.Array<com.couchbase.lite.Ordering>): com.couchbase.lite.OrderBy;
public groupBy(param0: native.Array<com.couchbase.lite.Expression>): com.couchbase.lite.GroupBy;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class FromRouter {
public static class: java.lang.Class<com.couchbase.lite.FromRouter>;
/**
* Constructs a new instance of the com.couchbase.lite.FromRouter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
from(param0: com.couchbase.lite.DataSource): com.couchbase.lite.From;
});
public constructor();
public from(param0: com.couchbase.lite.DataSource): com.couchbase.lite.From;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class FullTextExpression {
public static class: java.lang.Class<com.couchbase.lite.FullTextExpression>;
public match(param0: string): com.couchbase.lite.Expression;
public static index(param0: string): com.couchbase.lite.FullTextExpression;
}
export module FullTextExpression {
export class FullTextMatchExpression extends com.couchbase.lite.Expression {
public static class: java.lang.Class<com.couchbase.lite.FullTextExpression.FullTextMatchExpression>;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class FullTextFunction {
public static class: java.lang.Class<com.couchbase.lite.FullTextFunction>;
public static rank(param0: string): com.couchbase.lite.Expression;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class FullTextIndex extends com.couchbase.lite.AbstractIndex {
public static class: java.lang.Class<com.couchbase.lite.FullTextIndex>;
public setLanguage(param0: string): com.couchbase.lite.FullTextIndex;
public ignoreAccents(param0: boolean): com.couchbase.lite.FullTextIndex;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class FullTextIndexItem {
public static class: java.lang.Class<com.couchbase.lite.FullTextIndexItem>;
public static property(param0: string): com.couchbase.lite.FullTextIndexItem;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Function {
public static class: java.lang.Class<com.couchbase.lite.Function>;
public static abs(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static contains(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static length(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static trunc(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static ln(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static trim(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static e(): com.couchbase.lite.Expression;
public static rtrim(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static sum(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static upper(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static sign(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static tan(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static degrees(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static avg(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static round(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static min(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static max(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static atan2(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static cos(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static pi(): com.couchbase.lite.Expression;
public static ltrim(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static atan(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static acos(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static power(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static trunc(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static asin(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static sqrt(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static floor(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static radians(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static ceil(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static lower(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static exp(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static round(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static count(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static log(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
public static sin(param0: com.couchbase.lite.Expression): com.couchbase.lite.Expression;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class GroupBy extends com.couchbase.lite.AbstractQuery implements com.couchbase.lite.HavingRouter, com.couchbase.lite.OrderByRouter, com.couchbase.lite.LimitRouter {
public static class: java.lang.Class<com.couchbase.lite.GroupBy>;
public having(param0: com.couchbase.lite.Expression): com.couchbase.lite.Having;
public execute(): com.couchbase.lite.ResultSet;
public limit(param0: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
public addChangeListener(param0: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public removeChangeListener(param0: com.couchbase.lite.ListenerToken): void;
public limit(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
public getParameters(): com.couchbase.lite.Parameters;
public setParameters(param0: com.couchbase.lite.Parameters): void;
public orderBy(param0: native.Array<com.couchbase.lite.Ordering>): com.couchbase.lite.OrderBy;
public addChangeListener(param0: java.util.concurrent.Executor, param1: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public explain(): string;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class GroupByRouter {
public static class: java.lang.Class<com.couchbase.lite.GroupByRouter>;
/**
* Constructs a new instance of the com.couchbase.lite.GroupByRouter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
groupBy(param0: native.Array<com.couchbase.lite.Expression>): com.couchbase.lite.GroupBy;
});
public constructor();
public groupBy(param0: native.Array<com.couchbase.lite.Expression>): com.couchbase.lite.GroupBy;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Having extends com.couchbase.lite.AbstractQuery implements com.couchbase.lite.OrderByRouter, com.couchbase.lite.LimitRouter {
public static class: java.lang.Class<com.couchbase.lite.Having>;
public execute(): com.couchbase.lite.ResultSet;
public limit(param0: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
public addChangeListener(param0: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public removeChangeListener(param0: com.couchbase.lite.ListenerToken): void;
public limit(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
public getParameters(): com.couchbase.lite.Parameters;
public setParameters(param0: com.couchbase.lite.Parameters): void;
public orderBy(param0: native.Array<com.couchbase.lite.Ordering>): com.couchbase.lite.OrderBy;
public addChangeListener(param0: java.util.concurrent.Executor, param1: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public explain(): string;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class HavingRouter {
public static class: java.lang.Class<com.couchbase.lite.HavingRouter>;
/**
* Constructs a new instance of the com.couchbase.lite.HavingRouter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
having(param0: com.couchbase.lite.Expression): com.couchbase.lite.Having;
});
public constructor();
public having(param0: com.couchbase.lite.Expression): com.couchbase.lite.Having;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Index {
public static class: java.lang.Class<com.couchbase.lite.Index>;
/**
* Constructs a new instance of the com.couchbase.lite.Index interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class IndexBuilder {
public static class: java.lang.Class<com.couchbase.lite.IndexBuilder>;
public static fullTextIndex(param0: native.Array<com.couchbase.lite.FullTextIndexItem>): com.couchbase.lite.FullTextIndex;
public static valueIndex(param0: native.Array<com.couchbase.lite.ValueIndexItem>): com.couchbase.lite.ValueIndex;
public constructor();
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class IndexType {
public static class: java.lang.Class<com.couchbase.lite.IndexType>;
public static Value: com.couchbase.lite.IndexType;
public static FullText: com.couchbase.lite.IndexType;
public static Geo: com.couchbase.lite.IndexType;
public static values(): native.Array<com.couchbase.lite.IndexType>;
public static valueOf(param0: string): com.couchbase.lite.IndexType;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Join {
public static class: java.lang.Class<com.couchbase.lite.Join>;
public static crossJoin(param0: com.couchbase.lite.DataSource): com.couchbase.lite.Join;
public static join(param0: com.couchbase.lite.DataSource): com.couchbase.lite.Join.On;
public static leftJoin(param0: com.couchbase.lite.DataSource): com.couchbase.lite.Join.On;
public static leftOuterJoin(param0: com.couchbase.lite.DataSource): com.couchbase.lite.Join.On;
public static innerJoin(param0: com.couchbase.lite.DataSource): com.couchbase.lite.Join.On;
}
export module Join {
export class On extends com.couchbase.lite.Join {
public static class: java.lang.Class<com.couchbase.lite.Join.On>;
public on(param0: com.couchbase.lite.Expression): com.couchbase.lite.Join;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class JoinRouter {
public static class: java.lang.Class<com.couchbase.lite.JoinRouter>;
/**
* Constructs a new instance of the com.couchbase.lite.JoinRouter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
join(param0: native.Array<com.couchbase.lite.Join>): com.couchbase.lite.Joins;
});
public constructor();
public join(param0: native.Array<com.couchbase.lite.Join>): com.couchbase.lite.Joins;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Joins extends com.couchbase.lite.AbstractQuery implements com.couchbase.lite.WhereRouter, com.couchbase.lite.OrderByRouter, com.couchbase.lite.LimitRouter {
public static class: java.lang.Class<com.couchbase.lite.Joins>;
public execute(): com.couchbase.lite.ResultSet;
public limit(param0: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
public addChangeListener(param0: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public removeChangeListener(param0: com.couchbase.lite.ListenerToken): void;
public limit(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
public getParameters(): com.couchbase.lite.Parameters;
public setParameters(param0: com.couchbase.lite.Parameters): void;
public where(param0: com.couchbase.lite.Expression): com.couchbase.lite.Where;
public orderBy(param0: native.Array<com.couchbase.lite.Ordering>): com.couchbase.lite.OrderBy;
public addChangeListener(param0: java.util.concurrent.Executor, param1: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public explain(): string;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Limit extends com.couchbase.lite.AbstractQuery {
public static class: java.lang.Class<com.couchbase.lite.Limit>;
public execute(): com.couchbase.lite.ResultSet;
public addChangeListener(param0: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public removeChangeListener(param0: com.couchbase.lite.ListenerToken): void;
public getParameters(): com.couchbase.lite.Parameters;
public setParameters(param0: com.couchbase.lite.Parameters): void;
public addChangeListener(param0: java.util.concurrent.Executor, param1: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public explain(): string;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class LimitRouter {
public static class: java.lang.Class<com.couchbase.lite.LimitRouter>;
/**
* Constructs a new instance of the com.couchbase.lite.LimitRouter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
limit(param0: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
limit(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
});
public constructor();
public limit(param0: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
public limit(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ListenerToken {
public static class: java.lang.Class<com.couchbase.lite.ListenerToken>;
/**
* Constructs a new instance of the com.couchbase.lite.ListenerToken interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class LiveQuery extends com.couchbase.lite.DatabaseChangeListener {
public static class: java.lang.Class<com.couchbase.lite.LiveQuery>;
public changed(param0: com.couchbase.lite.DatabaseChange): void;
public finalize(): void;
public toString(): string;
public changed(param0: any): void;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class LogDomain {
public static class: java.lang.Class<com.couchbase.lite.LogDomain>;
public static ALL: com.couchbase.lite.LogDomain;
public static DATABASE: com.couchbase.lite.LogDomain;
public static QUERY: com.couchbase.lite.LogDomain;
public static REPLICATOR: com.couchbase.lite.LogDomain;
public static NETWORK: com.couchbase.lite.LogDomain;
public static values(): native.Array<com.couchbase.lite.LogDomain>;
public static valueOf(param0: string): com.couchbase.lite.LogDomain;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class LogLevel {
public static class: java.lang.Class<com.couchbase.lite.LogLevel>;
public static DEBUG: com.couchbase.lite.LogLevel;
public static VERBOSE: com.couchbase.lite.LogLevel;
public static INFO: com.couchbase.lite.LogLevel;
public static WARNING: com.couchbase.lite.LogLevel;
public static ERROR: com.couchbase.lite.LogLevel;
public static NONE: com.couchbase.lite.LogLevel;
public static values(): native.Array<com.couchbase.lite.LogLevel>;
public static valueOf(param0: string): com.couchbase.lite.LogLevel;
public getValue(): number;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class MValueDelegate implements com.couchbase.litecore.fleece.MValue.Delegate, com.couchbase.litecore.fleece.FLConstants.FLValueType {
public static class: java.lang.Class<com.couchbase.lite.MValueDelegate>;
public toNative(param0: com.couchbase.litecore.fleece.MValue, param1: com.couchbase.litecore.fleece.MCollection, param2: java.util.concurrent.atomic.AtomicBoolean): any;
public encodeNative(param0: com.couchbase.litecore.fleece.Encoder, param1: any): void;
public collectionFromNative(param0: any): com.couchbase.litecore.fleece.MCollection;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Meta {
public static class: java.lang.Class<com.couchbase.lite.Meta>;
public static id: com.couchbase.lite.MetaExpression;
public static sequence: com.couchbase.lite.MetaExpression;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class MetaExpression extends com.couchbase.lite.Expression {
public static class: java.lang.Class<com.couchbase.lite.MetaExpression>;
public from(param0: string): com.couchbase.lite.Expression;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class MutableArray extends com.couchbase.lite.Array implements com.couchbase.lite.MutableArrayInterface {
public static class: java.lang.Class<com.couchbase.lite.MutableArray>;
public insertBoolean(param0: number, param1: boolean): com.couchbase.lite.MutableArrayInterface;
public addDictionary(param0: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableArrayInterface;
public insertArray(param0: number, param1: com.couchbase.lite.Array): com.couchbase.lite.MutableArrayInterface;
public insertDictionary(param0: number, param1: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableArray;
public setDate(param0: number, param1: java.util.Date): com.couchbase.lite.MutableArray;
public insertNumber(param0: number, param1: java.lang.Number): com.couchbase.lite.MutableArray;
public setDouble(param0: number, param1: number): com.couchbase.lite.MutableArray;
public remove(param0: number): com.couchbase.lite.MutableArray;
public insertDictionary(param0: number, param1: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableArrayInterface;
public insertDate(param0: number, param1: java.util.Date): com.couchbase.lite.MutableArray;
public addDictionary(param0: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableArray;
public insertFloat(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public getDictionary(param0: number): com.couchbase.lite.Dictionary;
public setInt(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public setBoolean(param0: number, param1: boolean): com.couchbase.lite.MutableArray;
public addArray(param0: com.couchbase.lite.Array): com.couchbase.lite.MutableArray;
public addFloat(param0: number): com.couchbase.lite.MutableArray;
public insertDouble(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public insertLong(param0: number, param1: number): com.couchbase.lite.MutableArray;
public setValue(param0: number, param1: any): com.couchbase.lite.MutableArray;
public getString(param0: number): string;
public getNumber(param0: number): java.lang.Number;
public setString(param0: number, param1: string): com.couchbase.lite.MutableArray;
public insertInt(param0: number, param1: number): com.couchbase.lite.MutableArray;
public insertValue(param0: number, param1: any): com.couchbase.lite.MutableArray;
public addInt(param0: number): com.couchbase.lite.MutableArray;
public setData(param0: java.util.List<any>): com.couchbase.lite.MutableArrayInterface;
public toList(): java.util.List<any>;
public addLong(param0: number): com.couchbase.lite.MutableArrayInterface;
public insertDate(param0: number, param1: java.util.Date): com.couchbase.lite.MutableArrayInterface;
public addFloat(param0: number): com.couchbase.lite.MutableArrayInterface;
public insertNumber(param0: number, param1: java.lang.Number): com.couchbase.lite.MutableArrayInterface;
public insertValue(param0: number, param1: any): com.couchbase.lite.MutableArrayInterface;
public setLong(param0: number, param1: number): com.couchbase.lite.MutableArray;
public setBlob(param0: number, param1: com.couchbase.lite.Blob): com.couchbase.lite.MutableArray;
public addValue(param0: any): com.couchbase.lite.MutableArrayInterface;
public getBlob(param0: number): com.couchbase.lite.Blob;
public getValue(param0: number): any;
public count(): number;
public insertInt(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public setBoolean(param0: number, param1: boolean): com.couchbase.lite.MutableArrayInterface;
public setBlob(param0: number, param1: com.couchbase.lite.Blob): com.couchbase.lite.MutableArrayInterface;
public encodeTo(param0: com.couchbase.litecore.fleece.FLEncoder): void;
public setArray(param0: number, param1: com.couchbase.lite.Array): com.couchbase.lite.MutableArray;
public insertFloat(param0: number, param1: number): com.couchbase.lite.MutableArray;
public setData(param0: java.util.List<any>): com.couchbase.lite.MutableArray;
public getDouble(param0: number): number;
public insertDouble(param0: number, param1: number): com.couchbase.lite.MutableArray;
public getDictionary(param0: number): com.couchbase.lite.MutableDictionary;
public getDictionary(param0: number): com.couchbase.lite.MutableDictionaryInterface;
public constructor();
public addBoolean(param0: boolean): com.couchbase.lite.MutableArray;
public setDouble(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public setArray(param0: number, param1: com.couchbase.lite.Array): com.couchbase.lite.MutableArrayInterface;
public addNumber(param0: java.lang.Number): com.couchbase.lite.MutableArray;
public getInt(param0: number): number;
public setFloat(param0: number, param1: number): com.couchbase.lite.MutableArray;
public insertBoolean(param0: number, param1: boolean): com.couchbase.lite.MutableArray;
public setLong(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public addString(param0: string): com.couchbase.lite.MutableArray;
public addDouble(param0: number): com.couchbase.lite.MutableArray;
public setString(param0: number, param1: string): com.couchbase.lite.MutableArrayInterface;
public setDate(param0: number, param1: java.util.Date): com.couchbase.lite.MutableArrayInterface;
public addInt(param0: number): com.couchbase.lite.MutableArrayInterface;
public insertArray(param0: number, param1: com.couchbase.lite.Array): com.couchbase.lite.MutableArray;
public insertBlob(param0: number, param1: com.couchbase.lite.Blob): com.couchbase.lite.MutableArrayInterface;
public getArray(param0: number): com.couchbase.lite.MutableArrayInterface;
public addNumber(param0: java.lang.Number): com.couchbase.lite.MutableArrayInterface;
public addBoolean(param0: boolean): com.couchbase.lite.MutableArrayInterface;
public getDate(param0: number): java.util.Date;
public getBoolean(param0: number): boolean;
public insertBlob(param0: number, param1: com.couchbase.lite.Blob): com.couchbase.lite.MutableArray;
public addBlob(param0: com.couchbase.lite.Blob): com.couchbase.lite.MutableArrayInterface;
public addDate(param0: java.util.Date): com.couchbase.lite.MutableArrayInterface;
public getArray(param0: number): com.couchbase.lite.ArrayInterface;
public getFloat(param0: number): number;
public getArray(param0: number): com.couchbase.lite.Array;
public insertString(param0: number, param1: string): com.couchbase.lite.MutableArrayInterface;
public addDate(param0: java.util.Date): com.couchbase.lite.MutableArray;
public getDictionary(param0: number): com.couchbase.lite.DictionaryInterface;
public insertString(param0: number, param1: string): com.couchbase.lite.MutableArray;
public setNumber(param0: number, param1: java.lang.Number): com.couchbase.lite.MutableArrayInterface;
public setFloat(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public insertLong(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public addString(param0: string): com.couchbase.lite.MutableArrayInterface;
public getArray(param0: number): com.couchbase.lite.MutableArray;
public addDouble(param0: number): com.couchbase.lite.MutableArrayInterface;
public getLong(param0: number): number;
public addLong(param0: number): com.couchbase.lite.MutableArray;
public setDictionary(param0: number, param1: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableArray;
public addValue(param0: any): com.couchbase.lite.MutableArray;
public setValue(param0: number, param1: any): com.couchbase.lite.MutableArrayInterface;
public addBlob(param0: com.couchbase.lite.Blob): com.couchbase.lite.MutableArray;
public addArray(param0: com.couchbase.lite.Array): com.couchbase.lite.MutableArrayInterface;
public setInt(param0: number, param1: number): com.couchbase.lite.MutableArray;
public setDictionary(param0: number, param1: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableArrayInterface;
public constructor(param0: java.util.List<any>);
public setNumber(param0: number, param1: java.lang.Number): com.couchbase.lite.MutableArray;
public remove(param0: number): com.couchbase.lite.MutableArrayInterface;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class MutableArrayInterface extends com.couchbase.lite.ArrayInterface {
public static class: java.lang.Class<com.couchbase.lite.MutableArrayInterface>;
/**
* Constructs a new instance of the com.couchbase.lite.MutableArrayInterface interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
setData(param0: java.util.List<any>): com.couchbase.lite.MutableArrayInterface;
setValue(param0: number, param1: any): com.couchbase.lite.MutableArrayInterface;
setString(param0: number, param1: string): com.couchbase.lite.MutableArrayInterface;
setNumber(param0: number, param1: java.lang.Number): com.couchbase.lite.MutableArrayInterface;
setInt(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
setLong(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
setFloat(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
setDouble(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
setBoolean(param0: number, param1: boolean): com.couchbase.lite.MutableArrayInterface;
setBlob(param0: number, param1: com.couchbase.lite.Blob): com.couchbase.lite.MutableArrayInterface;
setDate(param0: number, param1: java.util.Date): com.couchbase.lite.MutableArrayInterface;
setArray(param0: number, param1: com.couchbase.lite.Array): com.couchbase.lite.MutableArrayInterface;
setDictionary(param0: number, param1: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableArrayInterface;
addValue(param0: any): com.couchbase.lite.MutableArrayInterface;
addString(param0: string): com.couchbase.lite.MutableArrayInterface;
addNumber(param0: java.lang.Number): com.couchbase.lite.MutableArrayInterface;
addInt(param0: number): com.couchbase.lite.MutableArrayInterface;
addLong(param0: number): com.couchbase.lite.MutableArrayInterface;
addFloat(param0: number): com.couchbase.lite.MutableArrayInterface;
addDouble(param0: number): com.couchbase.lite.MutableArrayInterface;
addBoolean(param0: boolean): com.couchbase.lite.MutableArrayInterface;
addBlob(param0: com.couchbase.lite.Blob): com.couchbase.lite.MutableArrayInterface;
addDate(param0: java.util.Date): com.couchbase.lite.MutableArrayInterface;
addArray(param0: com.couchbase.lite.Array): com.couchbase.lite.MutableArrayInterface;
addDictionary(param0: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableArrayInterface;
insertValue(param0: number, param1: any): com.couchbase.lite.MutableArrayInterface;
insertString(param0: number, param1: string): com.couchbase.lite.MutableArrayInterface;
insertNumber(param0: number, param1: java.lang.Number): com.couchbase.lite.MutableArrayInterface;
insertInt(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
insertLong(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
insertFloat(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
insertDouble(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
insertBoolean(param0: number, param1: boolean): com.couchbase.lite.MutableArrayInterface;
insertBlob(param0: number, param1: com.couchbase.lite.Blob): com.couchbase.lite.MutableArrayInterface;
insertDate(param0: number, param1: java.util.Date): com.couchbase.lite.MutableArrayInterface;
insertArray(param0: number, param1: com.couchbase.lite.Array): com.couchbase.lite.MutableArrayInterface;
insertDictionary(param0: number, param1: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableArrayInterface;
remove(param0: number): com.couchbase.lite.MutableArrayInterface;
getArray(param0: number): com.couchbase.lite.MutableArrayInterface;
getDictionary(param0: number): com.couchbase.lite.MutableDictionaryInterface;
count(): number;
getValue(param0: number): any;
getString(param0: number): string;
getNumber(param0: number): java.lang.Number;
getInt(param0: number): number;
getLong(param0: number): number;
getFloat(param0: number): number;
getDouble(param0: number): number;
getBoolean(param0: number): boolean;
getBlob(param0: number): com.couchbase.lite.Blob;
getDate(param0: number): java.util.Date;
getArray(param0: number): com.couchbase.lite.ArrayInterface;
getDictionary(param0: number): com.couchbase.lite.DictionaryInterface;
toList(): java.util.List<any>;
});
public constructor();
public insertBoolean(param0: number, param1: boolean): com.couchbase.lite.MutableArrayInterface;
public getDouble(param0: number): number;
public addDictionary(param0: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableArrayInterface;
public getDictionary(param0: number): com.couchbase.lite.MutableDictionaryInterface;
public insertArray(param0: number, param1: com.couchbase.lite.Array): com.couchbase.lite.MutableArrayInterface;
public setDouble(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public insertDictionary(param0: number, param1: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableArrayInterface;
public setArray(param0: number, param1: com.couchbase.lite.Array): com.couchbase.lite.MutableArrayInterface;
public getInt(param0: number): number;
public setLong(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public setString(param0: number, param1: string): com.couchbase.lite.MutableArrayInterface;
public setDate(param0: number, param1: java.util.Date): com.couchbase.lite.MutableArrayInterface;
public addInt(param0: number): com.couchbase.lite.MutableArrayInterface;
public insertBlob(param0: number, param1: com.couchbase.lite.Blob): com.couchbase.lite.MutableArrayInterface;
public getArray(param0: number): com.couchbase.lite.MutableArrayInterface;
public addNumber(param0: java.lang.Number): com.couchbase.lite.MutableArrayInterface;
public addBoolean(param0: boolean): com.couchbase.lite.MutableArrayInterface;
public insertFloat(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public getDate(param0: number): java.util.Date;
public setInt(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public getBoolean(param0: number): boolean;
public insertDouble(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public addBlob(param0: com.couchbase.lite.Blob): com.couchbase.lite.MutableArrayInterface;
public addDate(param0: java.util.Date): com.couchbase.lite.MutableArrayInterface;
public getArray(param0: number): com.couchbase.lite.ArrayInterface;
public getFloat(param0: number): number;
public insertString(param0: number, param1: string): com.couchbase.lite.MutableArrayInterface;
public getString(param0: number): string;
public getDictionary(param0: number): com.couchbase.lite.DictionaryInterface;
public getNumber(param0: number): java.lang.Number;
public setNumber(param0: number, param1: java.lang.Number): com.couchbase.lite.MutableArrayInterface;
public setFloat(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public insertLong(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public setData(param0: java.util.List<any>): com.couchbase.lite.MutableArrayInterface;
public toList(): java.util.List<any>;
public addString(param0: string): com.couchbase.lite.MutableArrayInterface;
public addDouble(param0: number): com.couchbase.lite.MutableArrayInterface;
public getLong(param0: number): number;
public addLong(param0: number): com.couchbase.lite.MutableArrayInterface;
public insertDate(param0: number, param1: java.util.Date): com.couchbase.lite.MutableArrayInterface;
public addFloat(param0: number): com.couchbase.lite.MutableArrayInterface;
public insertNumber(param0: number, param1: java.lang.Number): com.couchbase.lite.MutableArrayInterface;
public insertValue(param0: number, param1: any): com.couchbase.lite.MutableArrayInterface;
public setValue(param0: number, param1: any): com.couchbase.lite.MutableArrayInterface;
public addValue(param0: any): com.couchbase.lite.MutableArrayInterface;
public addArray(param0: com.couchbase.lite.Array): com.couchbase.lite.MutableArrayInterface;
public getBlob(param0: number): com.couchbase.lite.Blob;
public setDictionary(param0: number, param1: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableArrayInterface;
public getValue(param0: number): any;
public count(): number;
public insertInt(param0: number, param1: number): com.couchbase.lite.MutableArrayInterface;
public setBoolean(param0: number, param1: boolean): com.couchbase.lite.MutableArrayInterface;
public setBlob(param0: number, param1: com.couchbase.lite.Blob): com.couchbase.lite.MutableArrayInterface;
public remove(param0: number): com.couchbase.lite.MutableArrayInterface;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class MutableDictionary extends com.couchbase.lite.Dictionary implements com.couchbase.lite.MutableDictionaryInterface {
public static class: java.lang.Class<com.couchbase.lite.MutableDictionary>;
public setDate(param0: string, param1: java.util.Date): com.couchbase.lite.MutableDictionaryInterface;
public setBoolean(param0: string, param1: boolean): com.couchbase.lite.MutableDictionary;
public setBlob(param0: string, param1: com.couchbase.lite.Blob): com.couchbase.lite.MutableDictionary;
public constructor();
public getArray(param0: string): com.couchbase.lite.MutableArray;
public remove(param0: string): com.couchbase.lite.MutableDictionaryInterface;
public getNumber(param0: string): java.lang.Number;
public setDictionary(param0: string, param1: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableDictionaryInterface;
public getDictionary(param0: string): com.couchbase.lite.Dictionary;
public getBoolean(param0: string): boolean;
public getFloat(param0: string): number;
public setNumber(param0: string, param1: java.lang.Number): com.couchbase.lite.MutableDictionary;
public setInt(param0: string, param1: number): com.couchbase.lite.MutableDictionary;
public setLong(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
public getLong(param0: string): number;
public setData(param0: java.util.Map<string,any>): com.couchbase.lite.MutableDictionaryInterface;
public setArray(param0: string, param1: com.couchbase.lite.Array): com.couchbase.lite.MutableDictionaryInterface;
public setArray(param0: string, param1: com.couchbase.lite.Array): com.couchbase.lite.MutableDictionary;
public setFloat(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
public constructor(param0: java.util.Map<string,any>);
public setValue(param0: string, param1: any): com.couchbase.lite.MutableDictionaryInterface;
public getArray(param0: string): com.couchbase.lite.ArrayInterface;
public setInt(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
public getDictionary(param0: string): com.couchbase.lite.MutableDictionary;
public isChanged(): boolean;
public getArray(param0: string): com.couchbase.lite.Array;
public getDictionary(param0: string): com.couchbase.lite.MutableDictionaryInterface;
public finalize(): void;
public setValue(param0: string, param1: any): com.couchbase.lite.MutableDictionary;
public getKeys(): java.util.List<string>;
public setString(param0: string, param1: string): com.couchbase.lite.MutableDictionary;
public getValue(param0: string): any;
public setBlob(param0: string, param1: com.couchbase.lite.Blob): com.couchbase.lite.MutableDictionaryInterface;
public getArray(param0: string): com.couchbase.lite.MutableArrayInterface;
public getDictionary(param0: string): com.couchbase.lite.DictionaryInterface;
public setString(param0: string, param1: string): com.couchbase.lite.MutableDictionaryInterface;
public contains(param0: string): boolean;
public setDouble(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
public getString(param0: string): string;
public getBlob(param0: string): com.couchbase.lite.Blob;
public remove(param0: string): com.couchbase.lite.MutableDictionary;
public setDate(param0: string, param1: java.util.Date): com.couchbase.lite.MutableDictionary;
public setData(param0: java.util.Map<string,any>): com.couchbase.lite.MutableDictionary;
public setLong(param0: string, param1: number): com.couchbase.lite.MutableDictionary;
public setBoolean(param0: string, param1: boolean): com.couchbase.lite.MutableDictionaryInterface;
public setFloat(param0: string, param1: number): com.couchbase.lite.MutableDictionary;
public setDictionary(param0: string, param1: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableDictionary;
public setDouble(param0: string, param1: number): com.couchbase.lite.MutableDictionary;
public getDouble(param0: string): number;
public getDate(param0: string): java.util.Date;
public count(): number;
public encodeTo(param0: com.couchbase.litecore.fleece.FLEncoder): void;
public toMap(): java.util.Map<string,any>;
public setNumber(param0: string, param1: java.lang.Number): com.couchbase.lite.MutableDictionaryInterface;
public getInt(param0: string): number;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class MutableDictionaryInterface extends com.couchbase.lite.DictionaryInterface {
public static class: java.lang.Class<com.couchbase.lite.MutableDictionaryInterface>;
/**
* Constructs a new instance of the com.couchbase.lite.MutableDictionaryInterface interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
setData(param0: java.util.Map<string,any>): com.couchbase.lite.MutableDictionaryInterface;
setValue(param0: string, param1: any): com.couchbase.lite.MutableDictionaryInterface;
setString(param0: string, param1: string): com.couchbase.lite.MutableDictionaryInterface;
setNumber(param0: string, param1: java.lang.Number): com.couchbase.lite.MutableDictionaryInterface;
setInt(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
setLong(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
setFloat(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
setDouble(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
setBoolean(param0: string, param1: boolean): com.couchbase.lite.MutableDictionaryInterface;
setBlob(param0: string, param1: com.couchbase.lite.Blob): com.couchbase.lite.MutableDictionaryInterface;
setDate(param0: string, param1: java.util.Date): com.couchbase.lite.MutableDictionaryInterface;
setArray(param0: string, param1: com.couchbase.lite.Array): com.couchbase.lite.MutableDictionaryInterface;
setDictionary(param0: string, param1: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableDictionaryInterface;
remove(param0: string): com.couchbase.lite.MutableDictionaryInterface;
getArray(param0: string): com.couchbase.lite.MutableArrayInterface;
getDictionary(param0: string): com.couchbase.lite.MutableDictionaryInterface;
count(): number;
getKeys(): java.util.List<string>;
getValue(param0: string): any;
getString(param0: string): string;
getNumber(param0: string): java.lang.Number;
getInt(param0: string): number;
getLong(param0: string): number;
getFloat(param0: string): number;
getDouble(param0: string): number;
getBoolean(param0: string): boolean;
getBlob(param0: string): com.couchbase.lite.Blob;
getDate(param0: string): java.util.Date;
getArray(param0: string): com.couchbase.lite.ArrayInterface;
getDictionary(param0: string): com.couchbase.lite.DictionaryInterface;
toMap(): java.util.Map<string,any>;
contains(param0: string): boolean;
});
public constructor();
public setDate(param0: string, param1: java.util.Date): com.couchbase.lite.MutableDictionaryInterface;
public getKeys(): java.util.List<string>;
public getValue(param0: string): any;
public setBlob(param0: string, param1: com.couchbase.lite.Blob): com.couchbase.lite.MutableDictionaryInterface;
public getArray(param0: string): com.couchbase.lite.MutableArrayInterface;
public getDictionary(param0: string): com.couchbase.lite.DictionaryInterface;
public setString(param0: string, param1: string): com.couchbase.lite.MutableDictionaryInterface;
public remove(param0: string): com.couchbase.lite.MutableDictionaryInterface;
public getNumber(param0: string): java.lang.Number;
public contains(param0: string): boolean;
public setDictionary(param0: string, param1: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableDictionaryInterface;
public getBoolean(param0: string): boolean;
public setDouble(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
public getString(param0: string): string;
public getFloat(param0: string): number;
public getBlob(param0: string): com.couchbase.lite.Blob;
public setLong(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
public getLong(param0: string): number;
public setData(param0: java.util.Map<string,any>): com.couchbase.lite.MutableDictionaryInterface;
public setArray(param0: string, param1: com.couchbase.lite.Array): com.couchbase.lite.MutableDictionaryInterface;
public setBoolean(param0: string, param1: boolean): com.couchbase.lite.MutableDictionaryInterface;
public setFloat(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
public setValue(param0: string, param1: any): com.couchbase.lite.MutableDictionaryInterface;
public getDouble(param0: string): number;
public getArray(param0: string): com.couchbase.lite.ArrayInterface;
public getDate(param0: string): java.util.Date;
public setInt(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
public count(): number;
public toMap(): java.util.Map<string,any>;
public setNumber(param0: string, param1: java.lang.Number): com.couchbase.lite.MutableDictionaryInterface;
public getInt(param0: string): number;
public getDictionary(param0: string): com.couchbase.lite.MutableDictionaryInterface;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class MutableDocument extends com.couchbase.lite.Document implements com.couchbase.lite.MutableDictionaryInterface, com.couchbase.litecore.C4Constants {
public static class: java.lang.Class<com.couchbase.lite.MutableDocument>;
public setDate(param0: string, param1: java.util.Date): com.couchbase.lite.MutableDictionaryInterface;
public setArray(param0: string, param1: com.couchbase.lite.Array): com.couchbase.lite.MutableDocument;
public setData(param0: java.util.Map<string,any>): com.couchbase.lite.MutableDocument;
public setNumber(param0: string, param1: java.lang.Number): com.couchbase.lite.MutableDocument;
public constructor();
public getArray(param0: string): com.couchbase.lite.MutableArray;
public remove(param0: string): com.couchbase.lite.MutableDictionaryInterface;
public getNumber(param0: string): java.lang.Number;
public setDictionary(param0: string, param1: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableDictionaryInterface;
public getDictionary(param0: string): com.couchbase.lite.Dictionary;
public getBoolean(param0: string): boolean;
public getFloat(param0: string): number;
public setLong(param0: string, param1: number): com.couchbase.lite.MutableDocument;
public setLong(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
public getLong(param0: string): number;
public setData(param0: java.util.Map<string,any>): com.couchbase.lite.MutableDictionaryInterface;
public setValue(param0: string, param1: any): com.couchbase.lite.MutableDocument;
public setArray(param0: string, param1: com.couchbase.lite.Array): com.couchbase.lite.MutableDictionaryInterface;
public setString(param0: string, param1: string): com.couchbase.lite.MutableDocument;
public setFloat(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
public constructor(param0: java.util.Map<string,any>);
public setValue(param0: string, param1: any): com.couchbase.lite.MutableDictionaryInterface;
public getArray(param0: string): com.couchbase.lite.ArrayInterface;
public setInt(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
public getDictionary(param0: string): com.couchbase.lite.MutableDictionary;
public getArray(param0: string): com.couchbase.lite.Array;
public setBlob(param0: string, param1: com.couchbase.lite.Blob): com.couchbase.lite.MutableDocument;
public getDictionary(param0: string): com.couchbase.lite.MutableDictionaryInterface;
public setDate(param0: string, param1: java.util.Date): com.couchbase.lite.MutableDocument;
public getKeys(): java.util.List<string>;
public constructor(param0: string);
public toMutable(): com.couchbase.lite.MutableDocument;
public remove(param0: string): com.couchbase.lite.MutableDocument;
public setDictionary(param0: string, param1: com.couchbase.lite.Dictionary): com.couchbase.lite.MutableDocument;
public getValue(param0: string): any;
public setBlob(param0: string, param1: com.couchbase.lite.Blob): com.couchbase.lite.MutableDictionaryInterface;
public getArray(param0: string): com.couchbase.lite.MutableArrayInterface;
public getDictionary(param0: string): com.couchbase.lite.DictionaryInterface;
public setString(param0: string, param1: string): com.couchbase.lite.MutableDictionaryInterface;
public contains(param0: string): boolean;
public setDouble(param0: string, param1: number): com.couchbase.lite.MutableDictionaryInterface;
public getString(param0: string): string;
public getBlob(param0: string): com.couchbase.lite.Blob;
public constructor(param0: string, param1: java.util.Map<string,any>);
public setInt(param0: string, param1: number): com.couchbase.lite.MutableDocument;
public setBoolean(param0: string, param1: boolean): com.couchbase.lite.MutableDictionaryInterface;
public setDouble(param0: string, param1: number): com.couchbase.lite.MutableDocument;
public setFloat(param0: string, param1: number): com.couchbase.lite.MutableDocument;
public getDouble(param0: string): number;
public getDate(param0: string): java.util.Date;
public setBoolean(param0: string, param1: boolean): com.couchbase.lite.MutableDocument;
public count(): number;
public toMap(): java.util.Map<string,any>;
public setNumber(param0: string, param1: java.lang.Number): com.couchbase.lite.MutableDictionaryInterface;
public getInt(param0: string): number;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class NativeLibraryLoader {
public static class: java.lang.Class<com.couchbase.lite.NativeLibraryLoader>;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export abstract class NetworkReachabilityListener {
public static class: java.lang.Class<com.couchbase.lite.NetworkReachabilityListener>;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export abstract class NetworkReachabilityManager {
public static class: java.lang.Class<com.couchbase.lite.NetworkReachabilityManager>;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class OrderBy extends com.couchbase.lite.AbstractQuery implements com.couchbase.lite.LimitRouter {
public static class: java.lang.Class<com.couchbase.lite.OrderBy>;
public execute(): com.couchbase.lite.ResultSet;
public limit(param0: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
public addChangeListener(param0: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public removeChangeListener(param0: com.couchbase.lite.ListenerToken): void;
public limit(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
public getParameters(): com.couchbase.lite.Parameters;
public setParameters(param0: com.couchbase.lite.Parameters): void;
public addChangeListener(param0: java.util.concurrent.Executor, param1: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public explain(): string;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class OrderByRouter {
public static class: java.lang.Class<com.couchbase.lite.OrderByRouter>;
/**
* Constructs a new instance of the com.couchbase.lite.OrderByRouter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
orderBy(param0: native.Array<com.couchbase.lite.Ordering>): com.couchbase.lite.OrderBy;
});
public constructor();
public orderBy(param0: native.Array<com.couchbase.lite.Ordering>): com.couchbase.lite.OrderBy;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export abstract class Ordering {
public static class: java.lang.Class<com.couchbase.lite.Ordering>;
public static expression(param0: com.couchbase.lite.Expression): com.couchbase.lite.Ordering.SortOrder;
public static property(param0: string): com.couchbase.lite.Ordering.SortOrder;
}
export module Ordering {
export class SortOrder extends com.couchbase.lite.Ordering {
public static class: java.lang.Class<com.couchbase.lite.Ordering.SortOrder>;
public descending(): com.couchbase.lite.Ordering;
public ascending(): com.couchbase.lite.Ordering;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Parameters {
public static class: java.lang.Class<com.couchbase.lite.Parameters>;
public setInt(param0: string, param1: number): com.couchbase.lite.Parameters;
public setDate(param0: string, param1: java.util.Date): com.couchbase.lite.Parameters;
public setDouble(param0: string, param1: number): com.couchbase.lite.Parameters;
public setLong(param0: string, param1: number): com.couchbase.lite.Parameters;
public constructor(param0: com.couchbase.lite.Parameters);
public setString(param0: string, param1: string): com.couchbase.lite.Parameters;
public setNumber(param0: string, param1: java.lang.Number): com.couchbase.lite.Parameters;
public setValue(param0: string, param1: any): com.couchbase.lite.Parameters;
public setBoolean(param0: string, param1: boolean): com.couchbase.lite.Parameters;
public constructor();
public setFloat(param0: string, param1: number): com.couchbase.lite.Parameters;
public getValue(param0: string): any;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class PropertyExpression extends com.couchbase.lite.Expression {
public static class: java.lang.Class<com.couchbase.lite.PropertyExpression>;
public from(param0: string): com.couchbase.lite.Expression;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Query {
public static class: java.lang.Class<com.couchbase.lite.Query>;
/**
* Constructs a new instance of the com.couchbase.lite.Query interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getParameters(): com.couchbase.lite.Parameters;
setParameters(param0: com.couchbase.lite.Parameters): void;
execute(): com.couchbase.lite.ResultSet;
explain(): string;
addChangeListener(param0: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
addChangeListener(param0: java.util.concurrent.Executor, param1: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
removeChangeListener(param0: com.couchbase.lite.ListenerToken): void;
});
public constructor();
public execute(): com.couchbase.lite.ResultSet;
public addChangeListener(param0: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public removeChangeListener(param0: com.couchbase.lite.ListenerToken): void;
public getParameters(): com.couchbase.lite.Parameters;
public setParameters(param0: com.couchbase.lite.Parameters): void;
public addChangeListener(param0: java.util.concurrent.Executor, param1: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public explain(): string;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class QueryBuilder {
public static class: java.lang.Class<com.couchbase.lite.QueryBuilder>;
public static selectDistinct(param0: native.Array<com.couchbase.lite.SelectResult>): com.couchbase.lite.Select;
public static select(param0: native.Array<com.couchbase.lite.SelectResult>): com.couchbase.lite.Select;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class QueryChange {
public static class: java.lang.Class<com.couchbase.lite.QueryChange>;
public getResults(): com.couchbase.lite.ResultSet;
public getError(): java.lang.Throwable;
public getQuery(): com.couchbase.lite.Query;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class QueryChangeListener extends com.couchbase.lite.ChangeListener<com.couchbase.lite.QueryChange> {
public static class: java.lang.Class<com.couchbase.lite.QueryChangeListener>;
/**
* Constructs a new instance of the com.couchbase.lite.QueryChangeListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
changed(param0: com.couchbase.lite.QueryChange): void;
changed(param0: any): void;
});
public constructor();
public changed(param0: com.couchbase.lite.QueryChange): void;
public changed(param0: any): void;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Replicator extends com.couchbase.lite.AbstractReplicator {
public static class: java.lang.Class<com.couchbase.lite.Replicator>;
public constructor(param0: com.couchbase.lite.ReplicatorConfiguration);
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ReplicatorChange {
public static class: java.lang.Class<com.couchbase.lite.ReplicatorChange>;
public getStatus(): com.couchbase.lite.AbstractReplicator.Status;
public toString(): string;
public getReplicator(): com.couchbase.lite.Replicator;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ReplicatorChangeListener {
public static class: java.lang.Class<com.couchbase.lite.ReplicatorChangeListener>;
/**
* Constructs a new instance of the com.couchbase.lite.ReplicatorChangeListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
changed(param0: com.couchbase.lite.ReplicatorChange): void;
});
public constructor();
public changed(param0: com.couchbase.lite.ReplicatorChange): void;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ReplicatorChangeListenerToken extends com.couchbase.lite.ListenerToken {
public static class: java.lang.Class<com.couchbase.lite.ReplicatorChangeListenerToken>;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ReplicatorConfiguration {
public static class: java.lang.Class<com.couchbase.lite.ReplicatorConfiguration>;
public setContinuous(param0: boolean): com.couchbase.lite.ReplicatorConfiguration;
public setReplicatorType(param0: com.couchbase.lite.ReplicatorConfiguration.ReplicatorType): com.couchbase.lite.ReplicatorConfiguration;
public setPinnedServerCertificate(param0: native.Array<number>): com.couchbase.lite.ReplicatorConfiguration;
public setHeaders(param0: java.util.Map<string,string>): com.couchbase.lite.ReplicatorConfiguration;
public constructor(param0: com.couchbase.lite.ReplicatorConfiguration);
public getPinnedServerCertificate(): native.Array<number>;
public setAuthenticator(param0: com.couchbase.lite.Authenticator): com.couchbase.lite.ReplicatorConfiguration;
public getDatabase(): com.couchbase.lite.Database;
public isContinuous(): boolean;
public getHeaders(): java.util.Map<string,string>;
public getChannels(): java.util.List<string>;
public constructor(param0: com.couchbase.lite.Database, param1: com.couchbase.lite.Endpoint);
public getDocumentIDs(): java.util.List<string>;
public getReplicatorType(): com.couchbase.lite.ReplicatorConfiguration.ReplicatorType;
public getAuthenticator(): com.couchbase.lite.Authenticator;
public setChannels(param0: java.util.List<string>): com.couchbase.lite.ReplicatorConfiguration;
public setDocumentIDs(param0: java.util.List<string>): com.couchbase.lite.ReplicatorConfiguration;
public getTarget(): com.couchbase.lite.Endpoint;
}
export module ReplicatorConfiguration {
export class ReplicatorType {
public static class: java.lang.Class<com.couchbase.lite.ReplicatorConfiguration.ReplicatorType>;
public static PUSH_AND_PULL: com.couchbase.lite.ReplicatorConfiguration.ReplicatorType;
public static PUSH: com.couchbase.lite.ReplicatorConfiguration.ReplicatorType;
public static PULL: com.couchbase.lite.ReplicatorConfiguration.ReplicatorType;
public static valueOf(param0: string): com.couchbase.lite.ReplicatorConfiguration.ReplicatorType;
public static values(): native.Array<com.couchbase.lite.ReplicatorConfiguration.ReplicatorType>;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Result extends java.lang.Object {
public static class: java.lang.Class<com.couchbase.lite.Result>;
public getDouble(param0: number): number;
public getString(param0: number): string;
public getDictionary(param0: number): com.couchbase.lite.DictionaryInterface;
public getNumber(param0: number): java.lang.Number;
public getKeys(): java.util.List<string>;
public getValue(param0: string): any;
public getDictionary(param0: string): com.couchbase.lite.DictionaryInterface;
public getNumber(param0: string): java.lang.Number;
public contains(param0: string): boolean;
public toList(): java.util.List<any>;
public getLong(param0: number): number;
public getBoolean(param0: string): boolean;
public getDictionary(param0: string): com.couchbase.lite.Dictionary;
public getString(param0: string): string;
public getFloat(param0: string): number;
public getInt(param0: number): number;
public getBlob(param0: string): com.couchbase.lite.Blob;
public getLong(param0: string): number;
public getDate(param0: number): java.util.Date;
public getBoolean(param0: number): boolean;
public getDictionary(param0: number): com.couchbase.lite.Dictionary;
public getBlob(param0: number): com.couchbase.lite.Blob;
public getDouble(param0: string): number;
public getArray(param0: string): com.couchbase.lite.ArrayInterface;
public getDate(param0: string): java.util.Date;
public iterator(): java.util.Iterator<string>;
public getValue(param0: number): any;
public count(): number;
public getArray(param0: number): com.couchbase.lite.ArrayInterface;
public toMap(): java.util.Map<string,any>;
public getFloat(param0: number): number;
public getInt(param0: string): number;
public getArray(param0: string): com.couchbase.lite.Array;
public getArray(param0: number): com.couchbase.lite.Array;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ResultContext extends com.couchbase.lite.DocContext {
public static class: java.lang.Class<com.couchbase.lite.ResultContext>;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ResultSet extends java.lang.Iterable<com.couchbase.lite.Result> {
public static class: java.lang.Class<com.couchbase.lite.ResultSet>;
public allResults(): java.util.List<com.couchbase.lite.Result>;
public next(): com.couchbase.lite.Result;
public iterator(): java.util.Iterator<com.couchbase.lite.Result>;
public finalize(): void;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Select extends com.couchbase.lite.AbstractQuery implements com.couchbase.lite.FromRouter {
public static class: java.lang.Class<com.couchbase.lite.Select>;
public execute(): com.couchbase.lite.ResultSet;
public addChangeListener(param0: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public removeChangeListener(param0: com.couchbase.lite.ListenerToken): void;
public getParameters(): com.couchbase.lite.Parameters;
public setParameters(param0: com.couchbase.lite.Parameters): void;
public from(param0: com.couchbase.lite.DataSource): com.couchbase.lite.From;
public addChangeListener(param0: java.util.concurrent.Executor, param1: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public explain(): string;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class SelectResult {
public static class: java.lang.Class<com.couchbase.lite.SelectResult>;
public static property(param0: string): com.couchbase.lite.SelectResult.As;
public static all(): com.couchbase.lite.SelectResult.From;
public static expression(param0: com.couchbase.lite.Expression): com.couchbase.lite.SelectResult.As;
}
export module SelectResult {
export class As extends com.couchbase.lite.SelectResult {
public static class: java.lang.Class<com.couchbase.lite.SelectResult.As>;
public as(param0: string): com.couchbase.lite.SelectResult;
}
export class From extends com.couchbase.lite.SelectResult {
public static class: java.lang.Class<com.couchbase.lite.SelectResult.From>;
public from(param0: string): com.couchbase.lite.SelectResult;
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class SessionAuthenticator extends com.couchbase.lite.Authenticator {
public static class: java.lang.Class<com.couchbase.lite.SessionAuthenticator>;
public getCookieName(): string;
public getSessionID(): string;
public constructor(param0: string);
public constructor(param0: string, param1: string);
public constructor();
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class URLEndpoint extends com.couchbase.lite.Endpoint {
public static class: java.lang.Class<com.couchbase.lite.URLEndpoint>;
public getURL(): java.net.URI;
public toString(): string;
public constructor(param0: java.net.URI);
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ValueIndex extends com.couchbase.lite.AbstractIndex {
public static class: java.lang.Class<com.couchbase.lite.ValueIndex>;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class ValueIndexItem {
public static class: java.lang.Class<com.couchbase.lite.ValueIndexItem>;
public static property(param0: string): com.couchbase.lite.ValueIndexItem;
public static expression(param0: com.couchbase.lite.Expression): com.couchbase.lite.ValueIndexItem;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class VariableExpression extends com.couchbase.lite.Expression {
public static class: java.lang.Class<com.couchbase.lite.VariableExpression>;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class Where extends com.couchbase.lite.AbstractQuery implements com.couchbase.lite.GroupByRouter, com.couchbase.lite.OrderByRouter, com.couchbase.lite.LimitRouter {
public static class: java.lang.Class<com.couchbase.lite.Where>;
public execute(): com.couchbase.lite.ResultSet;
public limit(param0: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
public addChangeListener(param0: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public removeChangeListener(param0: com.couchbase.lite.ListenerToken): void;
public limit(param0: com.couchbase.lite.Expression, param1: com.couchbase.lite.Expression): com.couchbase.lite.Limit;
public getParameters(): com.couchbase.lite.Parameters;
public setParameters(param0: com.couchbase.lite.Parameters): void;
public orderBy(param0: native.Array<com.couchbase.lite.Ordering>): com.couchbase.lite.OrderBy;
public addChangeListener(param0: java.util.concurrent.Executor, param1: com.couchbase.lite.QueryChangeListener): com.couchbase.lite.ListenerToken;
public groupBy(param0: native.Array<com.couchbase.lite.Expression>): com.couchbase.lite.GroupBy;
public explain(): string;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export class WhereRouter {
public static class: java.lang.Class<com.couchbase.lite.WhereRouter>;
/**
* Constructs a new instance of the com.couchbase.lite.WhereRouter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
where(param0: com.couchbase.lite.Expression): com.couchbase.lite.Where;
});
public constructor();
public where(param0: com.couchbase.lite.Expression): com.couchbase.lite.Where;
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export module internal {
export module replicator {
export class CBLWebSocket extends com.couchbase.litecore.C4Socket {
public static class: java.lang.Class<com.couchbase.lite.internal.replicator.CBLWebSocket>;
public requestClose(param0: number, param1: string): void;
public static socket_open(param0: number, param1: number, param2: string, param3: string, param4: number, param5: string, param6: native.Array<number>): void;
public start(): void;
public close(): void;
public completedReceive(param0: number): void;
public send(param0: native.Array<number>): void;
}
export module CBLWebSocket {
export class CBLWebSocketListener {
public static class: java.lang.Class<com.couchbase.lite.internal.replicator.CBLWebSocket.CBLWebSocketListener>;
public onMessage(param0: okhttp3.WebSocket, param1: okio.ByteString): void;
public onOpen(param0: okhttp3.WebSocket, param1: okhttp3.Response): void;
public onMessage(param0: okhttp3.WebSocket, param1: string): void;
public onFailure(param0: okhttp3.WebSocket, param1: java.lang.Throwable, param2: okhttp3.Response): void;
public onClosing(param0: okhttp3.WebSocket, param1: number, param2: string): void;
public onClosed(param0: okhttp3.WebSocket, param1: number, param2: string): void;
}
}
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export module internal {
export module support {
export class Log {
public static class: java.lang.Class<com.couchbase.lite.internal.support.Log>;
public static DATABASE: string;
public static QUERY: string;
public static SYNC: string;
public static WEB_SOCKET: string;
public static DEBUG: number;
public static VERBOSE: number;
public static INFO: number;
public static WARN: number;
public static ERROR: number;
public static NONE: number;
public static v(param0: string, param1: string): void;
public static w(param0: string, param1: string): void;
public static info(param0: string, param1: string, param2: java.lang.Throwable): void;
public static info(param0: string, param1: string): void;
public static w(param0: string, param1: string, param2: java.lang.Throwable, param3: native.Array<any>): void;
public static v(param0: string, param1: string, param2: native.Array<any>): void;
public static v(param0: string, param1: string, param2: java.lang.Throwable, param3: native.Array<any>): void;
public static e(param0: string, param1: string): void;
public static i(param0: string, param1: string, param2: java.lang.Throwable): void;
public static w(param0: string, param1: java.lang.Throwable): void;
public static i(param0: string, param1: string): void;
public static i(param0: string, param1: string, param2: native.Array<any>): void;
public static w(param0: string, param1: string, param2: java.lang.Throwable): void;
public static setLogLevel(param0: com.couchbase.lite.LogDomain, param1: com.couchbase.lite.LogLevel): void;
public static e(param0: string, param1: string, param2: native.Array<any>): void;
public static i(param0: string, param1: string, param2: java.lang.Throwable, param3: native.Array<any>): void;
public static w(param0: string, param1: string, param2: native.Array<any>): void;
public static e(param0: string, param1: string, param2: java.lang.Throwable): void;
public static e(param0: string, param1: string, param2: java.lang.Throwable, param3: native.Array<any>): void;
public static v(param0: string, param1: string, param2: java.lang.Throwable): void;
public static enableLogging(param0: string, param1: number): void;
}
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export module internal {
export module support {
export class Logger {
public static class: java.lang.Class<com.couchbase.lite.internal.support.Logger>;
}
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export module internal {
export module utils {
export class ClassUtils {
public static class: java.lang.Class<com.couchbase.lite.internal.utils.ClassUtils>;
public static cast(param0: any, param1: java.lang.Class): any;
}
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export module internal {
export module utils {
export class DateUtils {
public static class: java.lang.Class<com.couchbase.lite.internal.utils.DateUtils>;
public static fromJson(param0: string): java.util.Date;
public static toJson(param0: java.util.Date): string;
}
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export module internal {
export module utils {
export class ExecutorUtils {
public static class: java.lang.Class<com.couchbase.lite.internal.utils.ExecutorUtils>;
public static shutdownAndAwaitTermination(param0: java.util.concurrent.ExecutorService, param1: number): void;
}
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export module internal {
export module utils {
export class FileUtils {
public static class: java.lang.Class<com.couchbase.lite.internal.utils.FileUtils>;
public static deleteRecursive(param0: string): boolean;
public static deleteRecursive(param0: java.io.File): boolean;
}
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export module internal {
export module utils {
export class JsonUtils {
public static class: java.lang.Class<com.couchbase.lite.internal.utils.JsonUtils>;
public static fromJson(param0: org.json.JSONArray): java.util.List<any>;
public static toJson(param0: java.util.List<any>): org.json.JSONArray;
public static toJson(param0: java.util.Map<string,any>): org.json.JSONObject;
public static fromJson(param0: org.json.JSONObject): java.util.Map<string,any>;
}
}
}
}
}
}
declare module com {
export module couchbase {
export module lite {
export module internal {
export module utils {
export class StringUtils {
public static class: java.lang.Class<com.couchbase.lite.internal.utils.StringUtils>;
public static stringByDeletingLastPathComponent(param0: string): string;
public static lastPathComponent(param0: string): string;
}
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4 {
public static class: java.lang.Class<com.couchbase.litecore.C4>;
public static getBuildInfo(): string;
public static getenv(param0: string): string;
public static getVersion(): string;
public static setenv(param0: string, param1: string, param2: number): void;
public constructor();
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4Base {
public static class: java.lang.Class<com.couchbase.litecore.C4Base>;
public static getMessage(param0: number, param1: number, param2: number): string;
public constructor();
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4BlobKey {
public static class: java.lang.Class<com.couchbase.litecore.C4BlobKey>;
public finalize(): void;
public toString(): string;
public constructor(param0: string);
public free(): void;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4BlobReadStream {
public static class: java.lang.Class<com.couchbase.litecore.C4BlobReadStream>;
public close(): void;
public read(param0: number): native.Array<number>;
public finalize(): void;
public seek(param0: number): void;
public getLength(): number;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4BlobStore {
public static class: java.lang.Class<com.couchbase.litecore.C4BlobStore>;
public openWriteStream(): com.couchbase.litecore.C4BlobWriteStream;
public getFilePath(param0: com.couchbase.litecore.C4BlobKey): string;
public delete(): void;
public getContents(param0: com.couchbase.litecore.C4BlobKey): com.couchbase.litecore.fleece.FLSliceResult;
public delete(param0: com.couchbase.litecore.C4BlobKey): void;
public finalize(): void;
public getSize(param0: com.couchbase.litecore.C4BlobKey): number;
public create(param0: native.Array<number>): com.couchbase.litecore.C4BlobKey;
public static open(param0: string, param1: number): com.couchbase.litecore.C4BlobStore;
public free(): void;
public openReadStream(param0: com.couchbase.litecore.C4BlobKey): com.couchbase.litecore.C4BlobReadStream;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4BlobWriteStream {
public static class: java.lang.Class<com.couchbase.litecore.C4BlobWriteStream>;
public computeBlobKey(): com.couchbase.litecore.C4BlobKey;
public close(): void;
public install(): void;
public write(param0: native.Array<number>): void;
public finalize(): void;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4Constants {
public static class: java.lang.Class<com.couchbase.litecore.C4Constants>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4Constants interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
export module C4Constants {
export class C4DatabaseFlags {
public static class: java.lang.Class<com.couchbase.litecore.C4Constants.C4DatabaseFlags>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4Constants$C4DatabaseFlags interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kC4DB_Create: number;
public static kC4DB_AutoCompact: number;
public static kC4DB_ReadOnly: number;
public static kC4DB_SharedKeys: number;
public static kC4DB_NonObservable: number;
public static kC4DB_NoUpgrade: number;
}
export class C4DocumentFlags {
public static class: java.lang.Class<com.couchbase.litecore.C4Constants.C4DocumentFlags>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4Constants$C4DocumentFlags interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kDocExists: number;
public static kDocHasAttachments: number;
public static kDocDeleted: number;
public static kDocConflicted: number;
}
export class C4DocumentVersioning {
public static class: java.lang.Class<com.couchbase.litecore.C4Constants.C4DocumentVersioning>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4Constants$C4DocumentVersioning interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kC4RevisionTrees: number;
public static kC4VersionVectors: number;
}
export class C4EncryptionAlgorithm {
public static class: java.lang.Class<com.couchbase.litecore.C4Constants.C4EncryptionAlgorithm>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4Constants$C4EncryptionAlgorithm interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kC4EncryptionAES256: number;
public static kC4EncryptionNone: number;
}
export class C4EncryptionKeySize {
public static class: java.lang.Class<com.couchbase.litecore.C4Constants.C4EncryptionKeySize>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4Constants$C4EncryptionKeySize interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kC4EncryptionKeySizeAES256: number;
}
export class C4EnumeratorFlags {
public static class: java.lang.Class<com.couchbase.litecore.C4Constants.C4EnumeratorFlags>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4Constants$C4EnumeratorFlags interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kC4Descending: number;
public static kC4IncludeNonConflicted: number;
public static kC4Default: number;
public static kC4IncludeDeleted: number;
public static kC4IncludeBodies: number;
}
export class C4ErrorDomain {
public static class: java.lang.Class<com.couchbase.litecore.C4Constants.C4ErrorDomain>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4Constants$C4ErrorDomain interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static SQLiteDomain: number;
public static NetworkDomain: number;
public static kC4MaxErrorDomainPlus1: number;
public static POSIXDomain: number;
public static WebSocketDomain: number;
public static LiteCoreDomain: number;
public static FleeceDomain: number;
}
export class C4IndexType {
public static class: java.lang.Class<com.couchbase.litecore.C4Constants.C4IndexType>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4Constants$C4IndexType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kC4GeoIndex: number;
public static kC4FullTextIndex: number;
public static kC4ValueIndex: number;
}
export class C4LogDomain {
public static class: java.lang.Class<com.couchbase.litecore.C4Constants.C4LogDomain>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4Constants$C4LogDomain interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static Query: string;
public static Database: string;
public static Sync: string;
public static WebSocket: string;
public static SyncBusy: string;
public static BLIP: string;
}
export class C4LogLevel {
public static class: java.lang.Class<com.couchbase.litecore.C4Constants.C4LogLevel>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4Constants$C4LogLevel interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kC4LogDebug: number;
public static kC4LogInfo: number;
public static kC4LogNone: number;
public static kC4LogWarning: number;
public static kC4LogVerbose: number;
public static kC4LogError: number;
}
export class C4RevisionFlags {
public static class: java.lang.Class<com.couchbase.litecore.C4Constants.C4RevisionFlags>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4Constants$C4RevisionFlags interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kRevKeepBody: number;
public static kRevDeleted: number;
public static kRevHasAttachments: number;
public static kRevLeaf: number;
public static kRevNew: number;
public static kRevIsConflict: number;
}
export class LiteCoreError {
public static class: java.lang.Class<com.couchbase.litecore.C4Constants.LiteCoreError>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4Constants$LiteCoreError interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kC4ErrorMissingIndex: number;
public static kC4ErrorNotFound: number;
public static kC4ErrorInvalidQueryParam: number;
public static kC4ErrorInvalidParameter: number;
public static kC4ErrorUnsupported: number;
public static kC4ErrorInvalidQuery: number;
public static kC4ErrorMemoryError: number;
public static kC4ErrorRemoteError: number;
public static kC4ErrorNotInTransaction: number;
public static kC4ErrorBusy: number;
public static kC4ErrorConflict: number;
public static kC4NumErrorCodesPlus1: number;
public static kC4ErrorBadRevisionID: number;
public static kC4ErrorUnimplemented: number;
public static kC4ErrorUnexpectedError: number;
public static kC4ErrorCantUpgradeDatabase: number;
public static kC4ErrorCrypto: number;
public static kC4ErrorUnsupportedEncryption: number;
public static kC4ErrorIOError: number;
public static kC4ErrorCorruptData: number;
public static kC4ErrorWrongFormat: number;
public static kC4ErrorCorruptRevisionData: number;
public static kC4ErrorNotOpen: number;
public static kC4ErrorTransactionNotClosed: number;
public static kC4ErrorNotWriteable: number;
public static kC4ErrorCantOpenFile: number;
public static kC4ErrorBadDocID: number;
public static kC4ErrorDatabaseTooNew: number;
public static kC4ErrorNotADatabaseFile: number;
public static kC4ErrorAssertionFailed: number;
public static kC4ErrorDatabaseTooOld: number;
}
export class NetworkError {
public static class: java.lang.Class<com.couchbase.litecore.C4Constants.NetworkError>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4Constants$NetworkError interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kC4NetErrDNSFailure: number;
public static kC4NetErrTimeout: number;
public static kC4NetErrTooManyRedirects: number;
public static kC4NetErrTLSHandshakeFailed: number;
public static kC4NetErrUnknownHost: number;
public static kC4NetErrTLSClientCertRequired: number;
public static kC4NetErrInvalidRedirect: number;
public static kC4NetErrInvalidURL: number;
public static kC4NetErrTLSCertUnknownRoot: number;
public static kC4NetErrTLSClientCertRejected: number;
public static kC4NetErrTLSCertExpired: number;
public static kC4NetErrTLSCertUntrusted: number;
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4Database extends com.couchbase.litecore.C4Constants {
public static class: java.lang.Class<com.couchbase.litecore.C4Database>;
public beginTransaction(): void;
public endTransaction(param0: boolean): void;
public create(param0: string, param1: native.Array<number>, param2: number): com.couchbase.litecore.C4Document;
public constructor(param0: string, param1: number, param2: string, param3: number, param4: number, param5: native.Array<number>);
public get(param0: string, param1: boolean): com.couchbase.litecore.C4Document;
public getPrivateUUID(): native.Array<number>;
public finalize(): void;
public getDocumentCount(): number;
public createFleeceEncoder(): com.couchbase.litecore.fleece.FLEncoder;
public getMaxRevTreeDepth(): number;
public compact(): void;
public getLastSequence(): number;
public put(param0: com.couchbase.litecore.fleece.FLSliceResult, param1: string, param2: number, param3: boolean, param4: boolean, param5: native.Array<string>, param6: boolean, param7: number, param8: number): com.couchbase.litecore.C4Document;
public createDatabaseObserver(param0: com.couchbase.litecore.C4DatabaseObserverListener, param1: any): com.couchbase.litecore.C4DatabaseObserver;
public delete(): void;
public rawGet(param0: string, param1: string): com.couchbase.litecore.C4RawDocument;
public enumerateAllDocs(param0: number): com.couchbase.litecore.C4DocEnumerator;
public getFLSharedKeys(): com.couchbase.litecore.fleece.FLSharedKeys;
public getExpiration(param0: string): number;
public nextDocExpiration(): number;
public rawPut(param0: string, param1: string, param2: string, param3: string): void;
public encodeJSON(param0: native.Array<number>): com.couchbase.litecore.fleece.FLSliceResult;
public createReplicator(param0: com.couchbase.litecore.C4Socket, param1: number, param2: number, param3: native.Array<number>, param4: com.couchbase.litecore.C4ReplicatorListener, param5: any): com.couchbase.litecore.C4Replicator;
public setMaxRevTreeDepth(param0: number): void;
public close(): void;
public setExpiration(param0: string, param1: number): void;
public getBlobStore(): com.couchbase.litecore.C4BlobStore;
public createReplicator(param0: string, param1: string, param2: number, param3: string, param4: string, param5: com.couchbase.litecore.C4Database, param6: number, param7: number, param8: native.Array<number>, param9: com.couchbase.litecore.C4ReplicatorListener, param10: any, param11: number, param12: number): com.couchbase.litecore.C4Replicator;
public free(): boolean;
public static deleteAtPath(param0: string): void;
public createQuery(param0: string): com.couchbase.litecore.C4Query;
public getPath(): string;
public createDocumentObserver(param0: string, param1: com.couchbase.litecore.C4DocumentObserverListener, param2: any): com.couchbase.litecore.C4DocumentObserver;
public getIndexes(): com.couchbase.litecore.fleece.FLValue;
public isInTransaction(): boolean;
public rekey(param0: number, param1: native.Array<number>): void;
public getPublicUUID(): native.Array<number>;
public static copy(param0: string, param1: string, param2: number, param3: string, param4: number, param5: number, param6: native.Array<number>): void;
public put(param0: native.Array<number>, param1: string, param2: number, param3: boolean, param4: boolean, param5: native.Array<string>, param6: boolean, param7: number, param8: number): com.couchbase.litecore.C4Document;
public create(param0: string, param1: com.couchbase.litecore.fleece.FLSliceResult, param2: number): com.couchbase.litecore.C4Document;
public enumerateChanges(param0: number, param1: number): com.couchbase.litecore.C4DocEnumerator;
public deleteIndex(param0: string): void;
public createIndex(param0: string, param1: string, param2: number, param3: string, param4: boolean): boolean;
public getBySequence(param0: number): com.couchbase.litecore.C4Document;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4DatabaseChange {
public static class: java.lang.Class<com.couchbase.litecore.C4DatabaseChange>;
public isExternal(): boolean;
public getBodySize(): number;
public getSequence(): number;
public getRevID(): string;
public constructor();
public getDocID(): string;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4DatabaseObserver {
public static class: java.lang.Class<com.couchbase.litecore.C4DatabaseObserver>;
public finalize(): void;
public free(): void;
public getChanges(param0: number): native.Array<com.couchbase.litecore.C4DatabaseChange>;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4DatabaseObserverListener {
public static class: java.lang.Class<com.couchbase.litecore.C4DatabaseObserverListener>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4DatabaseObserverListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
callback(param0: com.couchbase.litecore.C4DatabaseObserver, param1: any): void;
});
public constructor();
public callback(param0: com.couchbase.litecore.C4DatabaseObserver, param1: any): void;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4DocEnumerator extends com.couchbase.litecore.C4Constants {
public static class: java.lang.Class<com.couchbase.litecore.C4DocEnumerator>;
public getDocument(): com.couchbase.litecore.C4Document;
public close(): void;
public next(): boolean;
public finalize(): void;
public free(): void;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4Document extends com.couchbase.litecore.RefCounted implements com.couchbase.litecore.C4Constants {
public static class: java.lang.Class<com.couchbase.litecore.C4Document>;
public getSelectedFlags(): number;
public hasRevisionBody(): boolean;
public getSequence(): number;
public bodyAsJSON(param0: boolean): string;
public finalize(): void;
public selectCurrentRevision(): boolean;
public selectParentRevision(): boolean;
public resolveConflict(param0: string, param1: string, param2: native.Array<number>, param3: number): void;
public getSelectedBody2(): com.couchbase.litecore.fleece.FLDict;
public getDocID(): string;
public save(param0: number): void;
public selectNextLeafRevision(param0: boolean, param1: boolean): void;
public deleted(): boolean;
public isSelectedRevFlags(param0: number): boolean;
public getFlags(): number;
public getRevID(): string;
public getSelectedBody(): native.Array<number>;
public selectFirstPossibleAncestorOf(param0: string): boolean;
public static dictContainsBlobs(param0: com.couchbase.litecore.fleece.FLSliceResult, param1: com.couchbase.litecore.fleece.FLSharedKeys): boolean;
public getSelectedSequence(): number;
public update(param0: native.Array<number>, param1: number): com.couchbase.litecore.C4Document;
public loadRevisionBody(): void;
public selectCommonAncestorRevision(param0: string, param1: string): boolean;
public purgeRevision(param0: string): number;
public conflicted(): boolean;
public update(param0: com.couchbase.litecore.fleece.FLSliceResult, param1: number): com.couchbase.litecore.C4Document;
public exists(): boolean;
public selectNextRevision(): boolean;
public getSelectedRevID(): string;
public selectNextPossibleAncestorOf(param0: string): boolean;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4DocumentObserver {
public static class: java.lang.Class<com.couchbase.litecore.C4DocumentObserver>;
public finalize(): void;
public free(): void;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4DocumentObserverListener {
public static class: java.lang.Class<com.couchbase.litecore.C4DocumentObserverListener>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4DocumentObserverListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
callback(param0: com.couchbase.litecore.C4DocumentObserver, param1: string, param2: number, param3: any): void;
});
public constructor();
public callback(param0: com.couchbase.litecore.C4DocumentObserver, param1: string, param2: number, param3: any): void;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4Error {
public static class: java.lang.Class<com.couchbase.litecore.C4Error>;
public constructor(param0: number, param1: number, param2: number);
public getCode(): number;
public getInternalInfo(): number;
public toString(): string;
public getDomain(): number;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4FullTextMatch {
public static class: java.lang.Class<com.couchbase.litecore.C4FullTextMatch>;
public property(): number;
public length(): number;
public toList(): java.util.List<java.lang.Long>;
public start(): number;
public finalize(): void;
public dataSource(): number;
public term(): number;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4Key {
public static class: java.lang.Class<com.couchbase.litecore.C4Key>;
public static pbkdf2(param0: string, param1: native.Array<number>, param2: number, param3: number): native.Array<number>;
public constructor();
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4Listener {
public static class: java.lang.Class<com.couchbase.litecore.C4Listener>;
public constructor(param0: com.couchbase.litecore.C4ListenerConfig);
public static getAvailableAPIs(): number;
public finalize(): void;
public static getURINameFromPath(param0: string): string;
public shareDB(param0: string, param1: com.couchbase.litecore.C4Database): boolean;
public unshareDB(param0: string): boolean;
public free(): void;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4ListenerAPIs {
public static class: java.lang.Class<com.couchbase.litecore.C4ListenerAPIs>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4ListenerAPIs interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kC4RESTAPI: number;
public static kC4SyncAPI: number;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4ListenerConfig {
public static class: java.lang.Class<com.couchbase.litecore.C4ListenerConfig>;
public constructor(param0: number, param1: number, param2: string, param3: boolean, param4: boolean, param5: boolean, param6: boolean);
public setDirectory(param0: string): void;
public isAllowPush(): boolean;
public setPort(param0: number): void;
public setAllowCreateDBs(param0: boolean): void;
public getPort(): number;
public setApis(param0: number): void;
public setAllowDeleteDBs(param0: boolean): void;
public toString(): string;
public constructor();
public setAllowPush(param0: boolean): void;
public setAllowPull(param0: boolean): void;
public getApis(): number;
public isAllowDeleteDBs(): boolean;
public isAllowCreateDBs(): boolean;
public getDirectory(): string;
public isAllowPull(): boolean;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4Log {
public static class: java.lang.Class<com.couchbase.litecore.C4Log>;
public static setLevel(param0: string, param1: number): void;
public constructor();
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4Query {
public static class: java.lang.Class<com.couchbase.litecore.C4Query>;
public run(param0: com.couchbase.litecore.C4QueryOptions, param1: string): com.couchbase.litecore.C4QueryEnumerator;
public finalize(): void;
public getFullTextMatched(param0: com.couchbase.litecore.C4FullTextMatch): native.Array<number>;
public columnCount(): number;
public free(): void;
public explain(): string;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4QueryEnumerator {
public static class: java.lang.Class<com.couchbase.litecore.C4QueryEnumerator>;
public next(): boolean;
public close(): void;
public getMissingColumns(): number;
public refresh(): com.couchbase.litecore.C4QueryEnumerator;
public getRowCount(): number;
public getColumns(): com.couchbase.litecore.fleece.FLArrayIterator;
public getFullTextMatchCount(): number;
public getFullTextMatchs(param0: number): com.couchbase.litecore.C4FullTextMatch;
public finalize(): void;
public seek(param0: number): boolean;
public free(): void;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4QueryOptions {
public static class: java.lang.Class<com.couchbase.litecore.C4QueryOptions>;
public isRankFullText(): boolean;
public setRankFullText(param0: boolean): void;
public constructor();
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4RawDocument {
public static class: java.lang.Class<com.couchbase.litecore.C4RawDocument>;
public body(): string;
public finalize(): void;
public meta(): string;
public free(): void;
public key(): string;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4Replicator {
public static class: java.lang.Class<com.couchbase.litecore.C4Replicator>;
public static kC4Replicator2Scheme: string;
public static kC4Replicator2TLSScheme: string;
public stop(): void;
public getStatus(): com.couchbase.litecore.C4ReplicatorStatus;
public static mayBeNetworkDependent(param0: com.couchbase.litecore.C4Error): boolean;
public finalize(): void;
public getResponseHeaders(): native.Array<number>;
public static mayBeTransient(param0: com.couchbase.litecore.C4Error): boolean;
public free(): void;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4ReplicatorListener {
public static class: java.lang.Class<com.couchbase.litecore.C4ReplicatorListener>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4ReplicatorListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
statusChanged(param0: com.couchbase.litecore.C4Replicator, param1: com.couchbase.litecore.C4ReplicatorStatus, param2: any): void;
documentError(param0: com.couchbase.litecore.C4Replicator, param1: boolean, param2: string, param3: com.couchbase.litecore.C4Error, param4: boolean, param5: any): void;
});
public constructor();
public statusChanged(param0: com.couchbase.litecore.C4Replicator, param1: com.couchbase.litecore.C4ReplicatorStatus, param2: any): void;
public documentError(param0: com.couchbase.litecore.C4Replicator, param1: boolean, param2: string, param3: com.couchbase.litecore.C4Error, param4: boolean, param5: any): void;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4ReplicatorMode {
public static class: java.lang.Class<com.couchbase.litecore.C4ReplicatorMode>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4ReplicatorMode interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kC4Continuous: number;
public static kC4Disabled: number;
public static kC4Passive: number;
public static kC4OneShot: number;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4ReplicatorStatus {
public static class: java.lang.Class<com.couchbase.litecore.C4ReplicatorStatus>;
public getActivityLevel(): number;
public getErrorDomain(): number;
public getC4Error(): com.couchbase.litecore.C4Error;
public constructor(param0: number, param1: number, param2: number);
public getErrorInternalInfo(): number;
public constructor(param0: number, param1: number, param2: number, param3: number, param4: number, param5: number, param6: number);
public setActivityLevel(param0: number): void;
public getErrorCode(): number;
public toString(): string;
public copy(): com.couchbase.litecore.C4ReplicatorStatus;
public getProgressUnitsTotal(): number;
public constructor();
public getProgressUnitsCompleted(): number;
public constructor(param0: number);
public getProgressDocumentCount(): number;
}
export module C4ReplicatorStatus {
export class C4ReplicatorActivityLevel {
public static class: java.lang.Class<com.couchbase.litecore.C4ReplicatorStatus.C4ReplicatorActivityLevel>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4ReplicatorStatus$C4ReplicatorActivityLevel interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kC4Busy: number;
public static kC4Connecting: number;
public static kC4Idle: number;
public static kC4Stopped: number;
public static kC4Offline: number;
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export abstract class C4Socket {
public static class: java.lang.Class<com.couchbase.litecore.C4Socket>;
public static WEBSOCKET_SCHEME: string;
public static WEBSOCKET_SECURE_CONNECTION_SCHEME: string;
public static kC4ReplicatorOptionExtraHeaders: string;
public static kC4ReplicatorOptionCookies: string;
public static kC4ReplicatorOptionAuthentication: string;
public static kC4ReplicatorOptionPinnedServerCert: string;
public static kC4ReplicatorOptionDocIDs: string;
public static kC4ReplicatorOptionChannels: string;
public static kC4ReplicatorOptionFilter: string;
public static kC4ReplicatorOptionFilterParams: string;
public static kC4ReplicatorOptionSkipDeleted: string;
public static kC4ReplicatorOptionNoIncomingConflicts: string;
public static kC4ReplicatorOptionOutgoingConflicts: string;
public static kC4ReplicatorCheckpointInterval: string;
public static kC4ReplicatorOptionRemoteDBUniqueID: string;
public static kC4ReplicatorHeartbeatInterval: string;
public static kC4ReplicatorResetCheckpoint: string;
public static kC4ReplicatorOptionNoConflicts: string;
public static kC4SocketOptionWSProtocols: string;
public static kC4ReplicatorAuthType: string;
public static kC4ReplicatorAuthUserName: string;
public static kC4ReplicatorAuthPassword: string;
public static kC4ReplicatorAuthClientCert: string;
public static kC4AuthTypeBasic: string;
public static kC4AuthTypeSession: string;
public static kC4AuthTypeOpenIDConnect: string;
public static kC4AuthTypeFacebook: string;
public static kC4AuthTypeClientCert: string;
public static kC4WebSocketClientFraming: number;
public static kC4NoFraming: number;
public static kC4WebSocketServerFraming: number;
public static reverseLookupTable: java.util.Map<java.lang.Long,com.couchbase.litecore.C4Socket>;
public static socketFactory: java.util.Map<java.lang.Integer,java.lang.Class>;
public static socketFactoryContext: java.util.Map<java.lang.Integer,com.couchbase.lite.Replicator>;
public handle: number;
public nativeHandle: any;
public close(): void;
public gotHTTPResponse(param0: number, param1: native.Array<number>): void;
public static opened(param0: number): void;
public completedWrite(param0: number): void;
public constructor();
public static completedWrite(param0: number, param1: number): void;
public static fromNative(param0: number, param1: string, param2: string, param3: number, param4: string, param5: number): number;
public completedReceive(param0: number): void;
public static registerFactory(): void;
public static closed(param0: number, param1: number, param2: number, param3: string): void;
public send(param0: native.Array<number>): void;
public constructor(param0: number);
public static gotHTTPResponse(param0: number, param1: number, param2: native.Array<number>): void;
public static closeRequested(param0: number, param1: number, param2: string): void;
public requestClose(param0: number, param1: string): void;
public static received(param0: number, param1: native.Array<number>): void;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class C4WebSocketCloseCode {
public static class: java.lang.Class<com.couchbase.litecore.C4WebSocketCloseCode>;
/**
* Constructs a new instance of the com.couchbase.litecore.C4WebSocketCloseCode interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kWebSocketCloseBadMessageFormat: number;
public static kWebSocketCloseUserPermanent: number;
public static kWebSocketCloseNoCode: number;
public static kWebSocketCloseAbnormal: number;
public static kWebSocketCloseMissingExtension: number;
public static kWebSocketCloseTLSFailure: number;
public static kWebSocketCloseGoingAway: number;
public static kWebSocketCloseNormal: number;
public static kWebSocketClosePolicyError: number;
public static kWebSocketCloseFirstAvailable: number;
public static kWebSocketCloseCantFulfill: number;
public static kWebSocketCloseProtocolError: number;
public static kWebSocketCloseUserTransient: number;
public static kWebSocketCloseDataError: number;
public static kWebSocketCloseMessageTooBig: number;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class LiteCoreException {
public static class: java.lang.Class<com.couchbase.litecore.LiteCoreException>;
public domain: number;
public code: number;
public constructor(param0: number, param1: number, param2: string);
public getCode(): number;
public static throwException(param0: number, param1: number, param2: string): void;
public toString(): string;
public getDomain(): number;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export abstract class RefCounted {
public static class: java.lang.Class<com.couchbase.litecore.RefCounted>;
public release(): void;
public retain(): void;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export class SharedKeys {
public static class: java.lang.Class<com.couchbase.litecore.SharedKeys>;
public constructor(param0: com.couchbase.litecore.C4Database);
public getFLSharedKeys(): com.couchbase.litecore.fleece.FLSharedKeys;
public static valueToObject(param0: com.couchbase.litecore.fleece.FLValue, param1: com.couchbase.litecore.SharedKeys): any;
public static getKey(param0: com.couchbase.litecore.fleece.FLDictIterator, param1: com.couchbase.litecore.SharedKeys): string;
public constructor(param0: com.couchbase.litecore.fleece.FLSharedKeys);
public static dictContainsBlobs(param0: com.couchbase.litecore.fleece.FLSliceResult, param1: com.couchbase.litecore.SharedKeys): boolean;
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class AllocSlice {
public static class: java.lang.Class<com.couchbase.litecore.fleece.AllocSlice>;
public free(): void;
public constructor(param0: native.Array<number>);
public getBuf(): native.Array<number>;
public finalize(): void;
public getSize(): number;
public constructor(param0: number, param1: boolean);
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class Encodable {
public static class: java.lang.Class<com.couchbase.litecore.fleece.Encodable>;
/**
* Constructs a new instance of the com.couchbase.litecore.fleece.Encodable interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
encodeTo(param0: com.couchbase.litecore.fleece.Encoder): void;
});
public constructor();
public encodeTo(param0: com.couchbase.litecore.fleece.Encoder): void;
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class Encoder {
public static class: java.lang.Class<com.couchbase.litecore.fleece.Encoder>;
public free(): void;
public writeKey(param0: string): boolean;
public writeNull(): boolean;
public writeObject(param0: any): boolean;
public constructor(param0: com.couchbase.litecore.fleece.FLEncoder);
public finalize(): void;
public endDict(): boolean;
public endArray(): boolean;
public writeValue(param0: com.couchbase.litecore.fleece.FLValue): boolean;
public release(): void;
public write(param0: java.util.List): boolean;
public beginDict(param0: number): boolean;
public beginArray(param0: number): boolean;
public writeValue(param0: com.couchbase.litecore.fleece.FLArray): boolean;
public constructor();
public finish(): com.couchbase.litecore.fleece.AllocSlice;
public getFLEncoder(): com.couchbase.litecore.fleece.FLEncoder;
public write(param0: java.util.Map): boolean;
public writeValue(param0: com.couchbase.litecore.fleece.FLDict): boolean;
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class FLArray {
public static class: java.lang.Class<com.couchbase.litecore.fleece.FLArray>;
public asArray(): java.util.List<any>;
public count(): number;
public get(param0: number): com.couchbase.litecore.fleece.FLValue;
public constructor(param0: number);
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class FLArrayIterator {
public static class: java.lang.Class<com.couchbase.litecore.fleece.FLArrayIterator>;
public free(): void;
public getValue(): com.couchbase.litecore.fleece.FLValue;
public begin(param0: com.couchbase.litecore.fleece.FLArray): void;
public next(): boolean;
public constructor();
public finalize(): void;
public getValueAt(param0: number): com.couchbase.litecore.fleece.FLValue;
public constructor(param0: number);
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class FLConstants {
public static class: java.lang.Class<com.couchbase.litecore.fleece.FLConstants>;
public constructor();
}
export module FLConstants {
export class FLError {
public static class: java.lang.Class<com.couchbase.litecore.fleece.FLConstants.FLError>;
/**
* Constructs a new instance of the com.couchbase.litecore.fleece.FLConstants$FLError interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static InternalError: number;
public static MemoryError: number;
public static OutOfRange: number;
public static NotFound: number;
public static JSONError: number;
public static InvalidData: number;
public static EncodeError: number;
public static NoError: number;
public static UnknownValue: number;
}
export class FLValueType {
public static class: java.lang.Class<com.couchbase.litecore.fleece.FLConstants.FLValueType>;
/**
* Constructs a new instance of the com.couchbase.litecore.fleece.FLConstants$FLValueType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
public static kFLNull: number;
public static kFLDict: number;
public static kFLNumber: number;
public static kFLArray: number;
public static kFLBoolean: number;
public static kFLString: number;
public static kFLUndefined: number;
public static kFLData: number;
}
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class FLDict {
public static class: java.lang.Class<com.couchbase.litecore.fleece.FLDict>;
public static getKeyString(param0: com.couchbase.litecore.fleece.FLSharedKeys, param1: number): string;
public asDict(): java.util.Map<string,any>;
public toObject(param0: com.couchbase.litecore.SharedKeys): java.util.Map<string,any>;
public count(): number;
public getSharedKey(param0: string, param1: com.couchbase.litecore.fleece.FLSharedKeys): com.couchbase.litecore.fleece.FLValue;
public constructor(param0: number);
public toFLValue(): com.couchbase.litecore.fleece.FLValue;
public getHandle(): number;
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class FLDictIterator {
public static class: java.lang.Class<com.couchbase.litecore.fleece.FLDictIterator>;
public free(): void;
public getValue(): com.couchbase.litecore.fleece.FLValue;
public next(): boolean;
public constructor();
public begin(param0: com.couchbase.litecore.fleece.FLDict): void;
public finalize(): void;
public getKey(): com.couchbase.litecore.fleece.FLValue;
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class FLEncodable {
public static class: java.lang.Class<com.couchbase.litecore.fleece.FLEncodable>;
/**
* Constructs a new instance of the com.couchbase.litecore.fleece.FLEncodable interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
encodeTo(param0: com.couchbase.litecore.fleece.FLEncoder): void;
});
public constructor();
public encodeTo(param0: com.couchbase.litecore.fleece.FLEncoder): void;
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class FLEncoder {
public static class: java.lang.Class<com.couchbase.litecore.fleece.FLEncoder>;
public free(): void;
public writeData(param0: native.Array<number>): boolean;
public finish(): native.Array<number>;
public finish2(): com.couchbase.litecore.fleece.FLSliceResult;
public writeKey(param0: string): boolean;
public finalize(): void;
public writeString(param0: string): boolean;
public endDict(): boolean;
public endArray(): boolean;
public writeValue(param0: any): boolean;
public constructor(param0: number, param1: boolean);
public setExtraInfo(param0: any): void;
public getExtraInfo(): any;
public write(param0: java.util.List): boolean;
public beginDict(param0: number): boolean;
public beginArray(param0: number): boolean;
public constructor();
public write(param0: java.util.Map): boolean;
public constructor(param0: number);
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class FLSharedKeys {
public static class: java.lang.Class<com.couchbase.litecore.fleece.FLSharedKeys>;
public constructor(param0: number);
public getHandle(): number;
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class FLSliceResult {
public static class: java.lang.Class<com.couchbase.litecore.fleece.FLSliceResult>;
public free(): void;
public getBuf(): native.Array<number>;
public finalize(): void;
public getSize(): number;
public constructor(param0: number);
public getHandle(): number;
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class FLValue {
public static class: java.lang.Class<com.couchbase.litecore.fleece.FLValue>;
public getType(): number;
public asArray(): java.util.List<any>;
public asData(): native.Array<number>;
public asFLArray(): com.couchbase.litecore.fleece.FLArray;
public asString(): string;
public asDouble(): number;
public asDict(): java.util.Map<string,any>;
public toObject(param0: com.couchbase.litecore.SharedKeys): any;
public toJSON(): string;
public toStr(): string;
public static json5ToJson(param0: string): string;
public isUnsigned(): boolean;
public constructor(param0: number);
public isDouble(): boolean;
public asFLDict(): com.couchbase.litecore.fleece.FLDict;
public asBool(): boolean;
public asUnsigned(): number;
public static fromData(param0: com.couchbase.litecore.fleece.AllocSlice): com.couchbase.litecore.fleece.FLValue;
public isNumber(): boolean;
public static fromData(param0: native.Array<number>): com.couchbase.litecore.fleece.FLValue;
public asInt(): number;
public static toObject(param0: com.couchbase.litecore.fleece.FLValue): any;
public isInteger(): boolean;
public asFloat(): number;
public toJSON5(): string;
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class MArray extends com.couchbase.litecore.fleece.MCollection {
public static class: java.lang.Class<com.couchbase.litecore.fleece.MArray>;
public remove(param0: number, param1: number): boolean;
public clear(): boolean;
public initInSlot(param0: com.couchbase.litecore.fleece.MValue, param1: com.couchbase.litecore.fleece.MCollection): void;
public count(): number;
public initAsCopyOf(param0: com.couchbase.litecore.fleece.MCollection, param1: boolean): void;
public append(param0: any): boolean;
public remove(param0: number): boolean;
public initAsCopyOf(param0: com.couchbase.litecore.fleece.MArray, param1: boolean): void;
public get(param0: number): com.couchbase.litecore.fleece.MValue;
public set(param0: number, param1: any): boolean;
public constructor();
public getBaseArray(): com.couchbase.litecore.fleece.FLArray;
public initInSlot(param0: com.couchbase.litecore.fleece.MValue, param1: com.couchbase.litecore.fleece.MCollection, param2: boolean): void;
public insert(param0: number, param1: any): boolean;
public encodeTo(param0: com.couchbase.litecore.fleece.Encoder): void;
public constructor(param0: com.couchbase.litecore.fleece.MContext, param1: boolean);
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export abstract class MCollection extends com.couchbase.litecore.fleece.Encodable {
public static class: java.lang.Class<com.couchbase.litecore.fleece.MCollection>;
public getMutableChildren(): boolean;
public constructor();
public mutate(): void;
public setSlot(param0: com.couchbase.litecore.fleece.MValue, param1: com.couchbase.litecore.fleece.MValue): void;
public initAsCopyOf(param0: com.couchbase.litecore.fleece.MCollection, param1: boolean): void;
public initInSlot(param0: com.couchbase.litecore.fleece.MValue, param1: com.couchbase.litecore.fleece.MCollection, param2: boolean): void;
public getContext(): com.couchbase.litecore.fleece.MContext;
public isMutable(): boolean;
public encodeTo(param0: com.couchbase.litecore.fleece.Encoder): void;
public isMutated(): boolean;
public constructor(param0: com.couchbase.litecore.fleece.MContext, param1: boolean);
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class MContext {
public static class: java.lang.Class<com.couchbase.litecore.fleece.MContext>;
public static NULL: com.couchbase.litecore.fleece.MContext;
public getData(): com.couchbase.litecore.fleece.AllocSlice;
public constructor();
public constructor(param0: com.couchbase.litecore.fleece.AllocSlice, param1: com.couchbase.litecore.fleece.FLSharedKeys);
public getSharedKeys(): com.couchbase.litecore.fleece.FLSharedKeys;
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class MDict extends com.couchbase.litecore.fleece.MCollection implements java.lang.Iterable<string> {
public static class: java.lang.Class<com.couchbase.litecore.fleece.MDict>;
public get(param0: string): com.couchbase.litecore.fleece.MValue;
public initAsCopyOf(param0: com.couchbase.litecore.fleece.MDict, param1: boolean): void;
public set(param0: string, param1: com.couchbase.litecore.fleece.MValue): boolean;
public clear(): boolean;
public initInSlot(param0: com.couchbase.litecore.fleece.MValue, param1: com.couchbase.litecore.fleece.MCollection): void;
public count(): number;
public initAsCopyOf(param0: com.couchbase.litecore.fleece.MCollection, param1: boolean): void;
public iterator(): java.util.Iterator<string>;
public constructor();
public initInSlot(param0: com.couchbase.litecore.fleece.MValue, param1: com.couchbase.litecore.fleece.MCollection, param2: boolean): void;
public getKeys(): java.util.List<string>;
public getSharedKeys(): com.couchbase.litecore.fleece.FLSharedKeys;
public contains(param0: string): boolean;
public remove(param0: string): boolean;
public encodeTo(param0: com.couchbase.litecore.fleece.Encoder): void;
public constructor(param0: com.couchbase.litecore.fleece.MContext, param1: boolean);
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class MRoot extends com.couchbase.litecore.fleece.MCollection {
public static class: java.lang.Class<com.couchbase.litecore.fleece.MRoot>;
public constructor(param0: com.couchbase.litecore.fleece.MContext, param1: com.couchbase.litecore.fleece.FLValue, param2: boolean);
public constructor();
public constructor(param0: com.couchbase.litecore.fleece.AllocSlice);
public constructor(param0: com.couchbase.litecore.fleece.AllocSlice, param1: com.couchbase.litecore.fleece.FLSharedKeys, param2: boolean);
public static asNative(param0: com.couchbase.litecore.fleece.AllocSlice, param1: com.couchbase.litecore.fleece.FLSharedKeys, param2: boolean): any;
public encode(): com.couchbase.litecore.fleece.AllocSlice;
public encodeTo(param0: com.couchbase.litecore.fleece.Encoder): void;
public isMutated(): boolean;
public constructor(param0: com.couchbase.litecore.fleece.MContext, param1: boolean);
public asNative(): any;
}
}
}
}
}
declare module com {
export module couchbase {
export module litecore {
export module fleece {
export class MValue extends com.couchbase.litecore.fleece.Encodable {
public static class: java.lang.Class<com.couchbase.litecore.fleece.MValue>;
public static EMPTY: com.couchbase.litecore.fleece.MValue;
public constructor(param0: com.couchbase.litecore.fleece.FLValue);
public static registerDelegate(param0: com.couchbase.litecore.fleece.MValue.Delegate): void;
public getValue(): com.couchbase.litecore.fleece.FLValue;
public constructor(param0: boolean);
public isEmpty(): boolean;
public asNative(param0: com.couchbase.litecore.fleece.MCollection): any;
public mutate(): void;
public finalize(): void;
public constructor(param0: any);
public encodeTo(param0: com.couchbase.litecore.fleece.Encoder): void;
public isMutated(): boolean;
}
export module MValue {
export class Delegate {
public static class: java.lang.Class<com.couchbase.litecore.fleece.MValue.Delegate>;
/**
* Constructs a new instance of the com.couchbase.litecore.fleece.MValue$Delegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
toNative(param0: com.couchbase.litecore.fleece.MValue, param1: com.couchbase.litecore.fleece.MCollection, param2: java.util.concurrent.atomic.AtomicBoolean): any;
collectionFromNative(param0: any): com.couchbase.litecore.fleece.MCollection;
encodeNative(param0: com.couchbase.litecore.fleece.Encoder, param1: any): void;
});
public constructor();
public toNative(param0: com.couchbase.litecore.fleece.MValue, param1: com.couchbase.litecore.fleece.MCollection, param2: java.util.concurrent.atomic.AtomicBoolean): any;
public encodeNative(param0: com.couchbase.litecore.fleece.Encoder, param1: any): void;
public collectionFromNative(param0: any): com.couchbase.litecore.fleece.MCollection;
}
}
}
}
}
}
declare module okhttp3 {
export module internal {
export module tls {
export class CustomHostnameVerifier {
public static class: java.lang.Class<okhttp3.internal.tls.CustomHostnameVerifier>;
public static INSTANCE: okhttp3.internal.tls.CustomHostnameVerifier;
public verify(param0: string, param1: javax.net.ssl.SSLSession): boolean;
public verifyHostname(param0: string, param1: string): boolean;
public static allSubjectAltNames(param0: java.security.cert.X509Certificate): java.util.List<string>;
public static getInstance(): okhttp3.internal.tls.CustomHostnameVerifier;
public verify(param0: string, param1: java.security.cert.X509Certificate): boolean;
}
}
}
}
//Generics information:
//com.couchbase.lite.ChangeListener:1
//com.couchbase.lite.ChangeListenerToken:1
//com.couchbase.lite.ChangeNotifier:1 | the_stack |
import * as React from 'react';
import { Observable } from 'rxjs';
import {
PixieAPIContext, ExecutionStateUpdate, VizierQueryError, GRPCStatusCode, VizierTable,
} from 'app/api';
import { ClusterContext, useClusterConfig } from 'app/common/cluster-context';
import { useSnackbar } from 'app/components';
import { LiveRouteContext, push } from 'app/containers/App/live-routing';
import { SCRATCH_SCRIPT, ScriptsContext } from 'app/containers/App/scripts-context';
import { getQueryFuncs } from 'app/containers/live/vis';
import { ResultsContext } from 'app/context/results-context';
import pixieAnalytics from 'app/utils/analytics';
import {
argsForVis, Arguments, stableSerializeArgs, validateArgs,
} from 'app/utils/args-utils';
import { checkExhaustive } from 'app/utils/check-exhaustive';
import { containsMutation, isStreaming } from 'app/utils/pxl';
import { Script } from 'app/utils/script-bundle';
const NUM_MUTATION_RETRIES = 5;
const MUTATION_RETRY_MS = 5000; // 5s.
export interface ScriptContextProps {
/**
* The currently selected script, including any local edits the user has made.
*/
script: Script;
/** Args that will be passed to the current script if it's executed. Mirrored from LiveRouteContext. */
args: Record<string, string | string[]>;
/**
* Updates the script and args that will be used if execute() is called.
*/
setScriptAndArgs: (script: Script, args: Record<string, string | string[]>) => void;
/**
* Updates the script and args that will be used if execute() is called by a user manually running execute
* through the hot-key or button.
*/
setScriptAndArgsManually: (script: Script, args: Record<string, string | string[]>) => void;
/** Runs the currently selected scripts, with the current args and any user-made edits to the PXL/Vis/etc. */
execute: () => void;
/**
* If there is a script currently running, cancels that execution.
* This happens automatically when running a new script; it should only need to be called manually for things like
* navigating away from the live view entirely or for certain error scenarios.
*/
cancelExecution: () => void;
manual: boolean;
}
export const ScriptContext = React.createContext<ScriptContextProps>({
script: null,
args: {},
manual: false,
setScriptAndArgs: () => {},
setScriptAndArgsManually: () => {},
execute: () => {},
cancelExecution: () => {},
});
ScriptContext.displayName = 'ScriptContext';
export const ScriptContextProvider: React.FC = React.memo(({ children }) => {
const apiClient = React.useContext(PixieAPIContext);
const {
scriptId,
args,
embedState,
} = React.useContext(LiveRouteContext);
const { selectedClusterName } = React.useContext(ClusterContext);
const { scripts: availableScripts, loading: loadingAvailableScripts } = React.useContext(ScriptsContext);
const resultsContext = React.useContext(ResultsContext);
const showSnackbar = useSnackbar();
const clusterConfig = useClusterConfig();
const [script, setScript] = React.useState<Script>(null);
const [manual, setManual] = React.useState(false);
// When the user changes the script entirely (like via breadcrumbs or a fresh navigation): reset PXL, vis, etc.
React.useEffect(() => {
if (!loadingAvailableScripts && availableScripts.has(scriptId)) {
const scriptObj = availableScripts.get(scriptId);
if (!scriptObj) {
return;
}
if (scriptObj.id === SCRATCH_SCRIPT.id) {
setScript((prevScript) => {
if (prevScript) {
return prevScript;
}
return scriptObj;
});
} else {
setScript(scriptObj);
}
}
}, [scriptId, loadingAvailableScripts, availableScripts]);
const serializedArgs = stableSerializeArgs(args);
// Per-execution minutia
const [runningExecution, setRunningExecution] = React.useState<Observable<ExecutionStateUpdate> | null>(null);
const [cancelExecution, setCancelExecution] = React.useState<() => void | null>(null);
const [numExecutionTries, setNumExecutionTries] = React.useState(0);
const [hasMutation, setHasMutation] = React.useState(false);
// Timing: execute can be called before the API has finished returning all needed data, because VizierRoutingContext
// does not depend on the API and can update (triggering ScriptLoader) before required data has loaded for execution.
const readyToExecute = !loadingAvailableScripts;
const [awaitingExecution, setAwaitingExecution] = React.useState(false);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const execute: () => void = React.useMemo(() => () => {
if (!readyToExecute) {
setAwaitingExecution(true);
return;
}
if (!apiClient) throw new Error('Tried to execute a script before PixieAPIClient was ready!');
if (!script || !clusterConfig || !args) {
throw new Error('Tried to execute before script, cluster connection, and/or args were ready!');
}
const validationError = validateArgs(script.vis, args);
if (validationError != null) {
resultsContext.setResults({
error: validationError,
tables: new Map(),
});
return;
}
cancelExecution?.();
if (containsMutation(script.code) && manual) {
setNumExecutionTries(NUM_MUTATION_RETRIES);
} else if (containsMutation(script.code) && !manual) {
// We should call execute() even when the mutation wasn't manually executed.
// This will trigger the proper loading states so that if someone directly
// opened the page to a mutation script, their cluster loading state resolves properly.
setNumExecutionTries(0);
} else {
setNumExecutionTries(1);
}
const execution = apiClient.executeScript(
clusterConfig,
script.code,
{ enableE2EEncryption: true },
getQueryFuncs(script.vis, args, embedState.widget),
);
setRunningExecution(execution);
resultsContext.clearResults();
resultsContext.setLoading(true);
resultsContext.setStreaming(isStreaming(script.code));
setHasMutation(containsMutation(script.code));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [apiClient, script, embedState.widget, clusterConfig, serializedArgs, cancelExecution, manual]);
// As above: delay first execution if required information isn't ready yet.
React.useEffect(() => {
if (awaitingExecution && readyToExecute) {
execute();
setAwaitingExecution(false);
}
}, [readyToExecute, awaitingExecution, execute]);
React.useEffect(() => {
if (numExecutionTries <= 0) {
resultsContext.setLoading(false);
return () => {};
}
const timeout = setTimeout(() => {
if (hasMutation) {
setNumExecutionTries(numExecutionTries - 1);
}
}, MUTATION_RETRY_MS);
let cleanup = () => {};
const subscription = runningExecution?.subscribe((update: ExecutionStateUpdate) => {
switch (update.event.type) {
case 'start':
// Cleanup is called when the React hook is cleaned up. This contains a subset
// of the functions called when an execution is cancelled. This is to handle
// retries for mutations, since the script loading/mutation/streaming state
// should not be completely reset.
cleanup = () => {
update.cancel();
setCancelExecution(null);
};
setCancelExecution(() => () => {
update.cancel();
setHasMutation(false);
resultsContext.setStreaming(false);
resultsContext.setLoading(false);
setNumExecutionTries(0);
setCancelExecution(null);
});
break;
case 'data': {
const updateData = update.event.data;
resultsContext.setResults((prev) => {
for (const updateBatch of updateData) {
const table: VizierTable = prev.tables.get(updateBatch.name)
?? new VizierTable(updateBatch.id, updateBatch.name, updateBatch.relation);
table.appendBatch(updateBatch.batch);
prev.tables.set(updateBatch.name, table);
}
return { ...prev };
});
if (resultsContext.streaming) {
resultsContext.setLoading(false);
}
break;
}
case 'metadata':
case 'mutation-info':
case 'status':
case 'stats':
// Mutation schema not ready yet.
if (hasMutation && update.results.mutationInfo?.getStatus().getCode() === GRPCStatusCode.Unavailable) {
resultsContext.setResults({ tables: new Map(), mutationInfo: update.results.mutationInfo });
break;
}
if (update.results && (resultsContext.streaming || update.results.executionStats)) {
resultsContext.setResults({
error: resultsContext.error,
stats: update.results.executionStats,
mutationInfo: resultsContext.mutationInfo,
tables: update.results.tables.reduce(
(map, table) => map.set(table.name, table),
new Map()),
});
}
// Query completed normally
if (update.results.executionStats) {
setCancelExecution(null);
resultsContext.setLoading(false);
resultsContext.setStreaming(false);
setNumExecutionTries(0);
setHasMutation(false);
pixieAnalytics.track('Query Execution', {
status: 'success',
query: script.code,
queryId: update.results.queryId,
title: script.id,
});
}
break;
case 'error': {
const error = Array.isArray(update.event.error) ? update.event.error[0] : update.event.error;
const { errType } = (error as VizierQueryError);
if (hasMutation && errType === 'unavailable') {
// Ignore unavailable errors from the mutation executor.
break;
}
const errMsg = error.message;
resultsContext.setResults({ error, tables: new Map() });
resultsContext.setLoading(false);
resultsContext.setStreaming(false);
setNumExecutionTries(numExecutionTries - 1);
pixieAnalytics.track('Query Execution', {
status: 'failed',
query: script.code,
queryID: update.results.queryId,
error: errMsg,
title: script.id,
});
if (errType === 'server' || !errType) {
showSnackbar({
message: errMsg,
action: () => execute(),
actionTitle: 'Retry',
autoHideDuration: 5000,
});
}
break;
}
case 'cancel':
break;
default:
checkExhaustive(update.event);
}
});
return () => {
clearTimeout(timeout);
cleanup();
subscription?.unsubscribe();
};
// ONLY watch runningExecution for this. This effect only subscribes/unsubscribes from it.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [runningExecution, numExecutionTries]);
const setScriptAndArgs = React.useCallback((newScript: Script, newArgs: Arguments = args) => {
setScript(newScript);
setManual(false);
push(selectedClusterName, newScript.id, argsForVis(newScript.vis, newArgs), embedState);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [serializedArgs, embedState, push, selectedClusterName]);
const setScriptAndArgsManually = React.useCallback((newScript: Script, newArgs: Arguments = args) => {
setScript(newScript);
setManual(true);
push(selectedClusterName, newScript.id, argsForVis(newScript.vis, newArgs), embedState);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [serializedArgs, embedState, push, selectedClusterName]);
const context: ScriptContextProps = React.useMemo(() => ({
script,
args,
manual,
setScriptAndArgs,
setScriptAndArgsManually,
execute,
cancelExecution: (cancelExecution ?? (() => {})),
// eslint-disable-next-line react-hooks/exhaustive-deps
}), [script, execute, serializedArgs, selectedClusterName, setScriptAndArgs, setScriptAndArgsManually]);
return <ScriptContext.Provider value={context}>{children}</ScriptContext.Provider>;
});
ScriptContextProvider.displayName = 'ScriptContextProvider'; | the_stack |
import { UserComponentFactory } from '../../../components/framework/userComponentFactory';
import { KeyCode } from '../../../constants/keyCode';
import { Autowired, PostConstruct } from '../../../context/context';
import { Column } from '../../../entities/column';
import { Events, FilterChangedEvent } from '../../../events';
import { FilterManager } from '../../../filter/filterManager';
import { IFloatingFilterComp, IFloatingFilterParams } from '../../../filter/floating/floatingFilter';
import { FloatingFilterMapper } from '../../../filter/floating/floatingFilterMapper';
import { ReadOnlyFloatingFilter } from '../../../filter/floating/provided/readOnlyFloatingFilter';
import { GridApi } from '../../../gridApi';
import { IFilterComp, IFilterDef } from '../../../interfaces/iFilter';
import { IMenuFactory } from '../../../interfaces/iMenuFactory';
import { ModuleNames } from '../../../modules/moduleNames';
import { ModuleRegistry } from '../../../modules/moduleRegistry';
import { Beans } from '../../../rendering/beans';
import { ColumnHoverService } from '../../../rendering/columnHoverService';
import { SetLeftFeature } from '../../../rendering/features/setLeftFeature';
import { AgPromise } from '../../../utils';
import { addOrRemoveCssClass, setDisplayed } from '../../../utils/dom';
import { createIconNoSpan } from '../../../utils/icon';
import { RefSelector } from '../../../widgets/componentAnnotations';
import { ManagedFocusFeature } from '../../../widgets/managedFocusFeature';
import { AbstractHeaderCellComp } from '../abstractCell/abstractHeaderCellComp';
import { HoverFeature } from '../hoverFeature';
import { HeaderFilterCellCtrl, IHeaderFilterCellComp } from './headerFilterCellCtrl';
export class HeaderFilterCellComp extends AbstractHeaderCellComp<HeaderFilterCellCtrl> {
private static TEMPLATE = /* html */
`<div class="ag-header-cell ag-floating-filter" role="gridcell" tabindex="-1">
<div class="ag-floating-filter-full-body" ref="eFloatingFilterBody" role="presentation"></div>
<div class="ag-floating-filter-button ag-hidden" ref="eButtonWrapper" role="presentation">
<button type="button" aria-label="Open Filter Menu" class="ag-floating-filter-button-button" ref="eButtonShowMainFilter" tabindex="-1"></button>
</div>
</div>`;
@Autowired('columnHoverService') private readonly columnHoverService: ColumnHoverService;
@Autowired('userComponentFactory') private readonly userComponentFactory: UserComponentFactory;
@Autowired('gridApi') private readonly gridApi: GridApi;
@Autowired('filterManager') private readonly filterManager: FilterManager;
@Autowired('menuFactory') private readonly menuFactory: IMenuFactory;
@Autowired('beans') protected readonly beans: Beans;
@RefSelector('eFloatingFilterBody') private readonly eFloatingFilterBody: HTMLElement;
@RefSelector('eButtonWrapper') private readonly eButtonWrapper: HTMLElement;
@RefSelector('eButtonShowMainFilter') private readonly eButtonShowMainFilter: HTMLElement;
protected readonly column: Column;
protected readonly pinned: string | null;
private suppressFilterButton: boolean;
private floatingFilterCompPromise: AgPromise<IFloatingFilterComp> | null;
constructor(ctrl: HeaderFilterCellCtrl) {
super(HeaderFilterCellComp.TEMPLATE, ctrl);
this.column = ctrl.getColumnGroupChild() as Column;
this.pinned = ctrl.getPinned();
}
@PostConstruct
private postConstruct(): void {
this.setupFloatingFilter();
this.setupWidth();
this.setupLeftPositioning();
this.setupColumnHover();
this.createManagedBean(new HoverFeature([this.column], this.getGui()));
this.createManagedBean(new ManagedFocusFeature(
this.getFocusableElement(),
{
shouldStopEventPropagation: this.shouldStopEventPropagation.bind(this),
onTabKeyDown: this.onTabKeyDown.bind(this),
handleKeyDown: this.handleKeyDown.bind(this),
onFocusIn: this.onFocusIn.bind(this)
}
));
this.addManagedListener(this.eButtonShowMainFilter, 'click', this.showParentFilter.bind(this));
const compProxy: IHeaderFilterCellComp = {
};
this.ctrl.setComp(compProxy, this.getGui());
}
public getColumn(): Column {
return this.column;
}
protected onTabKeyDown(e: KeyboardEvent) {
const activeEl = document.activeElement as HTMLElement;
const eGui = this.getGui();
const wrapperHasFocus = activeEl === eGui;
if (wrapperHasFocus) { return; }
e.preventDefault();
const nextFocusableEl = this.focusService.findNextFocusableElement(eGui, null, e.shiftKey);
if (nextFocusableEl) {
nextFocusableEl.focus();
} else {
eGui.focus();
}
}
protected handleKeyDown(e: KeyboardEvent) {
const activeEl = document.activeElement;
const eGui = this.getGui();
const wrapperHasFocus = activeEl === eGui;
switch (e.keyCode) {
case KeyCode.UP:
case KeyCode.DOWN:
if (!wrapperHasFocus) {
e.preventDefault();
}
case KeyCode.LEFT:
case KeyCode.RIGHT:
if (wrapperHasFocus) { return; }
e.stopPropagation();
case KeyCode.ENTER:
if (wrapperHasFocus) {
if (this.focusService.focusInto(eGui)) {
e.preventDefault();
}
}
break;
case KeyCode.ESCAPE:
if (!wrapperHasFocus) {
this.getGui().focus();
}
}
}
protected onFocusIn(e: FocusEvent): void {
const eGui = this.getGui();
if (!eGui.contains(e.relatedTarget as HTMLElement)) {
const rowIndex = this.ctrl.getRowIndex();
this.beans.focusService.setFocusedHeader(rowIndex, this.getColumn());
}
}
private setupFloatingFilter(): void {
const colDef = this.column.getColDef();
if ((!colDef.filter || !colDef.floatingFilter) && (!colDef.filterFramework || !colDef.floatingFilterComponentFramework)) { return; }
this.floatingFilterCompPromise = this.getFloatingFilterInstance();
if (!this.floatingFilterCompPromise) { return; }
this.floatingFilterCompPromise.then(compInstance => {
if (compInstance) {
this.setupWithFloatingFilter(compInstance);
this.setupSyncWithFilter();
}
});
}
private setupLeftPositioning(): void {
const setLeftFeature = new SetLeftFeature(this.column, this.getGui(), this.beans);
this.createManagedBean(setLeftFeature);
}
private setupSyncWithFilter(): void {
const syncWithFilter = (filterChangedEvent: FilterChangedEvent | null) => {
this.onParentModelChanged(this.currentParentModel(), filterChangedEvent);
};
this.addManagedListener(this.column, Column.EVENT_FILTER_CHANGED, syncWithFilter);
if (this.filterManager.isFilterActive(this.column)) {
syncWithFilter(null);
}
}
// linked to event listener in template
private showParentFilter() {
const eventSource = this.suppressFilterButton ? this.eFloatingFilterBody : this.eButtonShowMainFilter;
this.menuFactory.showMenuAfterButtonClick(this.column, eventSource, 'floatingFilter', 'filterMenuTab', ['filterMenuTab']);
}
private setupColumnHover(): void {
this.addManagedListener(this.eventService, Events.EVENT_COLUMN_HOVER_CHANGED, this.onColumnHover.bind(this));
this.onColumnHover();
}
private onColumnHover(): void {
if (!this.gridOptionsWrapper.isColumnHoverHighlight()) { return; }
addOrRemoveCssClass(this.getGui(), 'ag-column-hover', this.columnHoverService.isHovered(this.column));
}
private setupWidth(): void {
this.addManagedListener(this.column, Column.EVENT_WIDTH_CHANGED, this.onColumnWidthChanged.bind(this));
this.onColumnWidthChanged();
}
private onColumnWidthChanged(): void {
this.getGui().style.width = `${this.column.getActualWidth()}px`;
}
private setupWithFloatingFilter(floatingFilterComp: IFloatingFilterComp): void {
const disposeFunc = () => {
this.getContext().destroyBean(floatingFilterComp);
};
if (!this.isAlive()) {
disposeFunc();
return;
}
this.addDestroyFunc(disposeFunc);
const floatingFilterCompUi = floatingFilterComp.getGui();
addOrRemoveCssClass(this.eFloatingFilterBody, 'ag-floating-filter-full-body', this.suppressFilterButton);
addOrRemoveCssClass(this.eFloatingFilterBody, 'ag-floating-filter-body', !this.suppressFilterButton);
setDisplayed(this.eButtonWrapper, !this.suppressFilterButton);
const eIcon = createIconNoSpan('filter', this.gridOptionsWrapper, this.column);
this.eButtonShowMainFilter.appendChild(eIcon!);
this.eFloatingFilterBody.appendChild(floatingFilterCompUi);
if (floatingFilterComp.afterGuiAttached) {
floatingFilterComp.afterGuiAttached();
}
}
private parentFilterInstance(callback: (filterInstance: IFilterComp) => void): void {
const filterComponent = this.getFilterComponent();
if (filterComponent) {
filterComponent.then(callback);
}
}
private getFilterComponent(createIfDoesNotExist = true): AgPromise<IFilterComp> | null {
return this.filterManager.getFilterComponent(this.column, 'NO_UI', createIfDoesNotExist);
}
public static getDefaultFloatingFilterType(def: IFilterDef): string | null {
if (def == null) { return null; }
let defaultFloatingFilterType: string | null = null;
if (typeof def.filter === 'string') {
// will be undefined if not in the map
defaultFloatingFilterType = FloatingFilterMapper.getFloatingFilterType(def.filter);
} else if (def.filterFramework) {
// If filterFramework, then grid is NOT using one of the provided filters, hence no default.
// Note: We could combine this with another part of the 'if' statement, however explicitly
// having this section makes the code easier to read.
} else if (def.filter === true) {
const setFilterModuleLoaded = ModuleRegistry.isRegistered(ModuleNames.SetFilterModule);
defaultFloatingFilterType = setFilterModuleLoaded ? 'agSetColumnFloatingFilter' : 'agTextColumnFloatingFilter';
}
return defaultFloatingFilterType;
}
private getFloatingFilterInstance(): AgPromise<IFloatingFilterComp> | null {
const colDef = this.column.getColDef();
const defaultFloatingFilterType = HeaderFilterCellComp.getDefaultFloatingFilterType(colDef);
const filterParams = this.filterManager.createFilterParams(this.column, colDef);
const finalFilterParams = this.userComponentFactory.mergeParamsWithApplicationProvidedParams(colDef, 'filter', filterParams);
const params: IFloatingFilterParams = {
api: this.gridApi,
column: this.column,
filterParams: finalFilterParams,
currentParentModel: this.currentParentModel.bind(this),
parentFilterInstance: this.parentFilterInstance.bind(this),
showParentFilter: this.showParentFilter.bind(this),
onFloatingFilterChanged: this.onFloatingFilterChanged.bind(this),
suppressFilterButton: false // This one might be overridden from the colDef
};
// this is unusual - we need a params value OUTSIDE the component the params are for.
// the params are for the floating filter component, but this property is actually for the wrapper.
this.suppressFilterButton = colDef.floatingFilterComponentParams ? !!colDef.floatingFilterComponentParams.suppressFilterButton : false;
let promise = this.userComponentFactory.newFloatingFilterComponent(colDef, params, defaultFloatingFilterType);
if (!promise) {
const compInstance =
this.userComponentFactory.createUserComponentFromConcreteClass(ReadOnlyFloatingFilter, params);
promise = AgPromise.resolve(compInstance);
}
return promise;
}
private currentParentModel(): any {
const filterComponent = this.getFilterComponent(false);
return filterComponent ? filterComponent.resolveNow(null, filter => filter && filter.getModel()) : null;
}
private onParentModelChanged(model: any, filterChangedEvent: FilterChangedEvent | null): void {
if (!this.floatingFilterCompPromise) { return; }
this.floatingFilterCompPromise.then(comp => comp && comp.onParentModelChanged(model, filterChangedEvent));
}
private onFloatingFilterChanged(): void {
console.warn('AG Grid: since version 21.x, how floating filters are implemented has changed. ' +
'Instead of calling params.onFloatingFilterChanged(), get a reference to the main filter via ' +
'params.parentFilterInstance() and then set a value on the parent filter directly.');
}
} | the_stack |
import React, { Component } from 'react'
import { connect } from 'react-redux'
import copy from 'clipboard-copy'
import { GlobalHotKeys } from 'react-hotkeys'
import { replace, StoreStateRouterLocationURI, PropTypes } from '../../family'
import { serve } from '../../relatives/services/constant'
import { METHODS, STATUS_LIST } from './InterfaceForm'
import { CopyToClipboard } from '../utils/'
import { getRelativeUrl } from '../../utils/URLUtils'
import './InterfaceSummary.css'
import { showMessage, MSG_TYPE } from 'actions/common'
import { TextField, Select, InputLabel, Input, MenuItem, FormControl, RadioGroup, FormControlLabel, Radio } from '@material-ui/core'
import Markdown from 'markdown-to-jsx'
export enum BODY_OPTION {
FORM_DATA = 'FORM_DATA',
FORM_URLENCODED = 'FORM_URLENCODED',
RAW = 'RAW',
BINARY = 'BINARY',
}
export const getBodyOptionStr = (bo: string) => {
if (bo === BODY_OPTION.FORM_URLENCODED) {
return 'x-www-form-urlencoded'
} else if (bo === BODY_OPTION.FORM_DATA) {
return 'form-data'
} else if (bo === BODY_OPTION.RAW) {
return 'raw'
} else if (bo === BODY_OPTION.BINARY) {
return 'binary'
} else {
return '-'
}
}
export function formatBodyOption(type: BODY_OPTION) {
switch (type) {
case BODY_OPTION.BINARY:
return 'Binary'
case BODY_OPTION.FORM_DATA:
return 'FormData'
case BODY_OPTION.FORM_URLENCODED:
return 'UrlEncoded'
case BODY_OPTION.RAW:
return 'Raw'
default:
return '-'
}
}
export const BODY_OPTION_LIST = [
{ label: 'form-data', value: BODY_OPTION.FORM_DATA },
{ label: 'x-www-form-urlencoded', value: BODY_OPTION.FORM_URLENCODED },
{ label: 'raw', value: BODY_OPTION.RAW },
{ label: 'binary', value: BODY_OPTION.BINARY },
]
/**
* 参数类型
*/
export enum POS_TYPE {
QUERY = 2,
HEADER = 1,
BODY = 3,
PRE_REQUEST_SCRIPT = 4,
TEST = 5
}
function url2name(itf: any) {
// copy from http://gitlab.alibaba-inc.com/thx/magix-cli/blob/master/platform/rap.js#L306
const method = itf.method.toLowerCase()
const apiUrl = itf.url
const projectId = itf.repositoryId
const id = itf.id
// eslint-disable-next-line
const regExp = /^(?:https?:\/\/[^\/]+)?(\/?.+?\/?)(?:\.[^./]+)?$/
const regExpExec = regExp.exec(apiUrl)
if (!regExpExec) {
return {
ok: false,
name: '',
message: `\n ✘ 您的rap接口url设置格式不正确,参考格式:/api/test.json (接口url:${apiUrl}, 项目id:${projectId}, 接口id:${id})\n`,
}
}
const urlSplit = regExpExec[1].split('/')
// 接口地址为RESTful的,清除占位符
// api/:id/get -> api//get
// api/bid[0-9]{4}/get -> api//get
urlSplit.forEach((item, i) => {
// eslint-disable-next-line
if (/\:id/.test(item)) {
urlSplit[i] = '$id'
// eslint-disable-next-line
} else if (/[\[\]\{\}]/.test(item)) {
urlSplit[i] = '$regx'
}
})
// 只去除第一个为空的值,最后一个为空保留
// 有可能情况是接口 /api/login 以及 /api/login/ 需要同时存在
if (urlSplit[0].trim() === '') {
urlSplit.shift()
}
urlSplit.push(method)
const urlToName = urlSplit.join('_')
return {
ok: true,
name: urlToName,
message: '',
}
}
type InterfaceSummaryProps = {
store: object;
handleChangeInterface: (itf: any) => void;
showMessage: typeof showMessage;
[x: string]: any;
}
type InterfaceSummaryState = {
bodyOption?: any
method?: any
status?: any
posFilter: POS_TYPE
[x: string]: any
}
class InterfaceSummary extends Component<
InterfaceSummaryProps,
InterfaceSummaryState
> {
static contextTypes = {
onDeleteInterface: PropTypes.func.isRequired,
}
constructor(props: any) {
super(props)
this.state = {
bodyOption: props?.itf?.bodyOption ?? BODY_OPTION.FORM_DATA,
posFilter: props?.itf?.method === 'POST' ? POS_TYPE.BODY : POS_TYPE.QUERY,
}
this.changeMethod = this.changeMethod.bind(this)
this.changeHandler = this.changeHandler.bind(this)
this.switchBodyOption = this.switchBodyOption.bind(this)
this.switchPos = this.switchPos.bind(this)
this.copyModelName = this.copyModelName.bind(this)
props.stateChangeHandler && props.stateChangeHandler(this.state)
}
switchBodyOption(val: BODY_OPTION) {
this.setState({ bodyOption: val },
() => {
this.props.stateChangeHandler(this.state)
}
)
}
switchPos(val: POS_TYPE) {
return () => {
this.setState( { posFilter: val },
() => {
this.props.stateChangeHandler(this.state)
}
)
}
}
changeMethod(method: any) {
this.setState({ method })
}
changeStatus(status: any) {
this.setState({ status })
}
changeHandler(e: any) {
this.setState({
[e.target.name]: e.target.value,
})
}
copyModelName() {
const { itf = {} } = this.props
const res = url2name(itf)
if (!res.ok) {
this.props.showMessage(`复制失败: ${res.message}`, MSG_TYPE.ERROR)
return
}
const modelName = res.name
copy(modelName)
.then(() => {
this.props.showMessage(
`成功复制 ${modelName} 到剪贴板`,
MSG_TYPE.SUCCESS
)
})
.catch(() => {
this.props.showMessage(`复制失败`, MSG_TYPE.ERROR)
})
}
render() {
const {
repository = {},
itf = {},
editable,
handleChangeInterface,
} = this.props
const { posFilter } = this.state
const keyMap = {
COPY_MODEL_NAME: ['ctrl+alt+c'],
}
const handlers = {
COPY_MODEL_NAME: this.copyModelName,
}
if (!itf.id) {
return null
}
return (
<div className="InterfaceSummary">
<GlobalHotKeys keyMap={keyMap} handlers={handlers} />
{!editable && (
<div className="header">
<CopyToClipboard text={itf.name}>
<span className="title">{itf.name}</span>
</CopyToClipboard>
</div>
)}
<ul className="summary">
{editable ? (
<div style={{ maxWidth: 600 }}>
<div>
<TextField
style={{ marginTop: 0 }}
id="name"
label="名称"
value={itf.name || ''}
fullWidth={true}
autoComplete="off"
onChange={e => {
handleChangeInterface({ name: e.target.value })
}}
margin="normal"
/>
</div>
<div>
<TextField
id="url"
label="地址"
value={itf.url || ''}
fullWidth={true}
autoComplete="off"
onChange={e => {
handleChangeInterface({ url: e.target.value })
}}
margin="normal"
/>
</div>
<div>
<div style={{ width: 90, display: 'inline-block' }}>
<InputLabel shrink={true} htmlFor="method-label-placeholder"> 类型 </InputLabel>
<Select
value={itf.method}
input={<Input name="method" id="method-label-placeholder" />}
onChange={e => {
handleChangeInterface({ method: e.target.value })
}}
displayEmpty={true}
name="method"
>
{METHODS.map(method => (
<MenuItem key={method} value={method}>
{method}
</MenuItem>
))}
</Select>
</div>
<div style={{ width: 120, display: 'inline-block' }}>
<InputLabel shrink={true} htmlFor="status-label-placeholder" style={{ width: 100 }}> 状态码 </InputLabel>
<Select
value={itf.status}
input={<Input name="status" id="status-label-placeholder" />}
onChange={e => {
handleChangeInterface({ status: e.target.value })
}}
displayEmpty={true}
name="status"
>
{STATUS_LIST.map(status => (
<MenuItem key={status} value={status}>
{status}
</MenuItem>
))}
</Select>
</div>
</div>
<TextField
id="description"
label="描述(可多行, 支持Markdown)"
value={itf.description || ''}
fullWidth={true}
multiline={true}
autoComplete="off"
rowsMax={8}
onChange={e => {
handleChangeInterface({ description: e.target.value })
}}
margin="normal"
/>
</div>
) : (
<>
<li>
<span className="mr5">
<span className="label">接口ID:</span>
{itf.id}
</span>
</li>
<li>
<CopyToClipboard text={itf.url} type="right">
<span className="mr5">
<span className="label">地址:</span>
<a
href={`${serve}/app/mock/${repository.id}${getRelativeUrl(itf.url || '')}`}
target="_blank"
rel="noopener noreferrer"
>
{itf.url}
</a>
</span>
</CopyToClipboard>
</li>
<li>
<span>
<span className="label">类型:</span>
<span>{itf.method}</span>
</span>
</li>
<li>
<span>
<span className="label">状态码:</span>
<span>{itf.status}</span>
</span>
</li>
</>
)}
</ul>
{itf.description && (
<CopyToClipboard text={itf.description}>
<Markdown>{itf.description || ''}</Markdown>
</CopyToClipboard>
)}
{
editable && (
<ul className="nav nav-tabs" role="tablist">
<li className="nav-item" onClick={this.switchPos(POS_TYPE.HEADER)} >
<button
className={`nav-link ${posFilter === POS_TYPE.HEADER ? 'active' : ''}`}
role="tab"
data-toggle="tab"
>
Headers
</button>
</li>
<li className="nav-item" onClick={this.switchPos(POS_TYPE.QUERY)} >
<button
className={`nav-link ${posFilter === POS_TYPE.QUERY ? 'active' : ''}`}
role="tab"
data-toggle="tab"
>
Query Params
</button>
</li>
<li className="nav-item" onClick={this.switchPos(POS_TYPE.BODY)} >
<button
className={`nav-link ${posFilter === POS_TYPE.BODY ? 'active' : ''}`}
role="tab"
data-toggle="tab"
>
Body Params
</button>
</li>
</ul>
)
}
{
editable && posFilter === POS_TYPE.BODY ? (
<FormControl component="fieldset">
<RadioGroup
aria-label="body type"
name="body-type"
value={this.state.bodyOption}
onChange={e => this.switchBodyOption(e.target.value as BODY_OPTION)}
row={true}
>
{BODY_OPTION_LIST.map(x => <FormControlLabel key={x.value} value={x.value} control={<Radio />} label={x.label} />)}
</RadioGroup>
</FormControl>
) : null
}
</div >
)
}
handleDelete = (e: any, itf: any) => {
e.preventDefault()
const message = '接口被删除后不可恢复!\n确认继续删除吗?'
if (window.confirm(message)) {
const { onDeleteInterface } = this.context
onDeleteInterface(itf.id, () => {
const { router, replace } = this.props
const uri = StoreStateRouterLocationURI(router)
const deleteHref = this.props.active
? uri.removeSearch('itf').href()
: uri.href()
replace(deleteHref)
})
}
}
handleUpdate = () => { /** empty */ }
}
const mapStateToProps = () => ({
})
const mapDispatchToProps = {
replace,
showMessage,
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(InterfaceSummary) | the_stack |
import { Observable, Subscription } from 'rxjs';
import { finalize, tap } from 'rxjs/operators';
import {
COMPUTED,
DEFAULT_VERSION,
OPTIMISTIC_CONCURRENCY,
} from '../constants';
import { ODataHelper } from '../helper';
import { ODataParserOptions } from '../options';
import { ODataStructuredTypeFieldParser } from '../parsers';
import {
Expand,
ODataEntitiesAnnotations,
ODataEntityAnnotations,
ODataEntityResource,
ODataEntitySetResource,
ODataNavigationPropertyResource,
ODataPathSegments,
ODataPropertyResource,
ODataQueryOptions,
EntityKey,
ODataResource,
ODataSingletonResource,
OptionHandler,
ODataQueryArguments,
Select,
} from '../resources';
import { ODataEntitySet, ODataStructuredType } from '../schema';
import { Options } from '../types';
import { Objects, Types } from '../utils';
import type { ODataCollection } from './collection';
import type { ODataModel } from './model';
export const CID = '_cid';
export type ODataModelResource<T> =
| ODataEntityResource<T>
| ODataSingletonResource<T>
| ODataNavigationPropertyResource<T>
| ODataPropertyResource<T>;
export type ODataCollectionResource<T> =
| ODataEntitySetResource<T>
| ODataNavigationPropertyResource<T>
| ODataPropertyResource<T>;
export type ODataModelEventType =
| 'change'
| 'reset'
| 'update'
| 'destroy'
| 'add'
| 'remove'
| 'invalid'
| 'request'
| 'sync'
| 'attach';
export class ODataModelEvent<T> {
name: ODataModelEventType;
bubbling: boolean = true;
model?: ODataModel<T>;
collection?: ODataCollection<T, ODataModel<T>>;
chain: [
ODataModel<any> | ODataCollection<any, ODataModel<any>>,
string | number | null
][];
value?: any;
previous?: any;
options?: any;
constructor(
name: ODataModelEventType,
{
model,
collection,
previous,
value,
track,
options,
}: {
model?: ODataModel<T>;
collection?: ODataCollection<T, ODataModel<T>>;
track?: string | number;
previous?: any;
value?: any;
options?: any;
} = {}
) {
this.name = name;
this.model = model;
this.collection = collection;
this.previous = previous;
this.value = value;
this.options = options;
this.chain = [
[
(this.collection || this.model) as
| ODataModel<any>
| ODataCollection<any, ODataModel<any>>,
track || null,
],
];
}
stopPropagation() {
this.bubbling = false;
}
push(
model: ODataModel<any> | ODataCollection<any, ODataModel<any>>,
track: string | number
) {
this.chain.splice(0, 0, [model, track]);
}
visited(model: ODataModel<any> | ODataCollection<any, ODataModel<any>>) {
return (
this.chain.some((c) => c[0] === model) &&
this.chain[this.chain.length - 1][0] !== model
);
}
get path() {
return this.chain
.map(([, track], index) =>
typeof track === 'number'
? `[${track}]`
: typeof track === 'string'
? index === 0
? track
: `.${track}`
: ''
)
.join('');
}
}
export const BUBBLING = [
'change',
'reset',
'update',
'destroy',
'add',
'remove',
];
export const INCLUDE_SHALLOW = {
include_concurrency: true,
include_computed: true,
include_key: true,
};
export const INCLUDE_DEEP = {
include_navigation: true,
include_non_field: true,
...INCLUDE_SHALLOW,
};
export enum ODataModelState {
Added,
Removed,
Changed,
Unchanged,
}
export type ModelOptions = {
cid?: string;
fields: { [name: string]: ModelFieldOptions };
};
export type ModelFieldOptions = {
field?: string;
default?: any;
required?: boolean;
concurrency?: boolean;
maxLength?: number;
minLength?: number;
min?: number;
max?: number;
pattern?: RegExp;
};
export function Model({ cid = CID }: { cid?: string } = {}) {
return <T extends { new (...args: any[]): {} }>(constructor: T) => {
const Klass = <any>constructor;
if (!Klass.hasOwnProperty('options'))
Klass.options = { fields: {} } as ModelOptions;
Klass.options.cid = cid;
return constructor;
};
}
export function ModelField({
name,
...options
}: { name?: string } & ModelFieldOptions = {}) {
return (target: any, key: string): void => {
const Klass = target.constructor;
if (!Klass.hasOwnProperty('options'))
Klass.options = { fields: {} } as ModelOptions;
options.field = name || key;
Klass.options.fields[key] = options;
};
}
export type ODataModelFieldOptions<F> = ModelFieldOptions & {
name: string;
field: string;
parser: ODataStructuredTypeFieldParser<F>;
};
export class ODataModelField<F> {
name: string;
field: string;
parser: ODataStructuredTypeFieldParser<F>;
options: ODataModelOptions<any>;
meta?: ODataModelOptions<any>;
default?: any;
required: boolean;
concurrency: boolean;
maxLength?: number;
minLength?: number;
min?: number;
max?: number;
pattern?: RegExp;
constructor(
options: ODataModelOptions<any>,
{ name, field, parser, ...opts }: ODataModelFieldOptions<F>
) {
this.options = options;
this.name = name;
this.field = field;
this.parser = parser;
this.default = opts.default || this.parser.default;
this.required = Boolean(opts.required);
this.concurrency = Boolean(opts.concurrency);
this.maxLength = opts.maxLength;
this.minLength = opts.minLength;
this.min = opts.min;
this.max = opts.max;
this.pattern = opts.pattern;
}
get api() {
return this.options.api;
}
get type() {
return this.parser.type;
}
get navigation() {
return Boolean(this.parser.navigation);
}
get collection() {
return Boolean(this.parser.collection);
}
get computed() {
return Boolean(
this.parser.findAnnotation((a) => a.term === COMPUTED)?.bool
);
}
configure({
findOptionsForType,
concurrency,
}: {
findOptionsForType: (type: string) => ODataModelOptions<any> | undefined;
concurrency: boolean;
}) {
this.meta = findOptionsForType(this.parser.type);
if (concurrency) this.concurrency = concurrency;
}
isKey() {
return this.parser.isKey();
}
hasReferentials() {
return this.parser.hasReferentials();
}
get referentials() {
return this.parser.referentials;
}
isStructuredType() {
return this.parser.isStructuredType();
}
structured() {
return this.api.findStructuredTypeForType<F>(this.parser.type);
}
isEnumType() {
return this.parser.isEnumType();
}
enum() {
return this.api.findEnumTypeForType<F>(this.parser.type);
}
validate(
value: any,
{
method,
navigation = false,
}: {
method?: 'create' | 'update' | 'modify';
navigation?: boolean;
} = {}
) {
/*
if ('isValid' in value && typeof value.isValid === 'function') {
return !value.isValid({ method, navigation }) ? value._errors : undefined;
} else if ('models' in value && typeof value.models === 'function') {
*/
if (ODataModelOptions.isModel(value)) {
return !value.isValid({ method, navigation }) ? value._errors : undefined;
} else if (ODataModelOptions.isCollection(value)) {
return value
.models()
.some((m: ODataModel<any>) => !m.isValid({ method, navigation }))
? value.models().map((m: ODataModel<any>) => m._errors)
: undefined;
} else {
let errors = this.parser?.validate(value, { method, navigation }) || [];
if (
this.required &&
(value === null || (value === undefined && method !== 'modify')) // Is null or undefined without patch?
) {
errors.push(`required`);
}
if (
this.maxLength !== undefined &&
typeof value === 'string' &&
value.length > this.maxLength
) {
errors.push(`maxlength`);
}
if (
this.minLength !== undefined &&
typeof value === 'string' &&
value.length < this.minLength
) {
errors.push(`minlength`);
}
if (
this.min !== undefined &&
typeof value === 'number' &&
value < this.min
) {
errors.push(`min`);
}
if (
this.max !== undefined &&
typeof value === 'number' &&
value > this.max
) {
errors.push(`max`);
}
if (
this.pattern !== undefined &&
typeof value === 'string' &&
!this.pattern.test(value)
) {
errors.push(`pattern`);
}
return !Types.isEmpty(errors) ? errors : undefined;
}
}
defaults(): any {
return this.isStructuredType() && this.meta !== undefined
? this.meta.defaults()
: this.default;
}
deserialize(value: any, options?: Options): F {
const parserOptions =
options !== undefined
? new ODataParserOptions(options)
: this.api.options;
return this.parser.deserialize(value, parserOptions);
}
serialize(value: F, options?: Options): any {
const parserOptions =
options !== undefined
? new ODataParserOptions(options)
: this.api.options;
return this.parser.serialize(value, parserOptions);
}
encode(value: F, options?: Options): any {
const parserOptions =
options !== undefined
? new ODataParserOptions(options)
: this.api.options;
return this.parser.encode(value, parserOptions);
}
resourceFactory<T, F>(
base: ODataModelResource<T>
): ODataNavigationPropertyResource<F> | ODataPropertyResource<F> {
if (
!(
base instanceof ODataEntityResource ||
base instanceof ODataNavigationPropertyResource ||
base instanceof ODataPropertyResource
)
)
throw new Error("Can't build resource for non compatible base type");
return this.navigation
? (base as ODataEntityResource<T>).navigationProperty<F>(this.parser.name)
: (base as ODataEntityResource<T>).property<F>(this.parser.name);
}
annotationsFactory(
base: ODataEntityAnnotations
): ODataEntityAnnotations | ODataEntitiesAnnotations {
return this.parser.collection
? new ODataEntitiesAnnotations(
base.helper,
base.property(this.parser.name) || {}
)
: new ODataEntityAnnotations(
base.helper,
base.property(this.parser.name) || {}
);
}
schemaFactory<T, F>(
base: ODataStructuredType<T>
): ODataStructuredType<F> | undefined {
return this.api.findStructuredTypeForType(this.parser.type);
}
modelCollectionFactory<T, F>({
parent,
value,
reset,
}: {
parent: ODataModel<any>;
value?: F | F[] | { [name: string]: any } | { [name: string]: any }[];
reset?: boolean;
}): ODataModel<F> | ODataCollection<F, ODataModel<F>> {
const schema = this.schemaFactory<T, F>(parent.schema());
const annots = this.annotationsFactory(parent.annots());
const Model = schema?.model;
const Collection = schema?.collection;
if (Model === undefined || Collection === undefined)
throw Error(`No model for ${this.name}`);
return this.parser.collection
? (new Collection((value || []) as (F | { [name: string]: any })[], {
annots: annots as ODataEntitiesAnnotations,
parent: [parent, this],
reset,
}) as ODataCollection<F, ODataModel<F>>)
: (new Model((value || {}) as F | { [name: string]: any }, {
annots: annots as ODataEntityAnnotations,
parent: [parent, this],
reset,
}) as ODataModel<F>);
}
}
export type ODataModelRelation<T> = {
state: ODataModelState;
model?: ODataModel<T> | ODataCollection<T, ODataModel<T>> | null;
field: ODataModelField<T>;
subscription?: Subscription;
};
export type ODataModelEntry<T, M extends ODataModel<T>> = {
state: ODataModelState;
model: M;
key?: EntityKey<T> | { [name: string]: any };
subscription?: Subscription;
};
export class ODataModelOptions<T> {
name: string;
cid: string;
base?: string;
open?: boolean;
private _fields: ODataModelField<any>[];
schema: ODataStructuredType<T>;
entitySet?: ODataEntitySet;
// Hierarchy
parent?: ODataModelOptions<any>;
children: ODataModelOptions<any>[] = [];
constructor(options: ModelOptions, schema: ODataStructuredType<T>) {
this.name = schema.name;
this.base = schema.base;
this.open = schema.open;
this.schema = schema;
this.cid = options.cid || CID;
const schemaFields = this.schema.fields({
include_navigation: true,
include_parents: true,
});
this._fields = Object.entries(options.fields).map(([name, options]) => {
const { field, ...opts } = options;
if (field === undefined || name === undefined)
throw new Error('Model Properties need name and field');
const parser = schemaFields.find((f: any) => f.name === field);
if (parser === undefined)
throw new Error(`No parser for ${field} with name = ${name}`);
return new ODataModelField<T>(this, { name, field, parser, ...opts });
});
}
get api() {
return this.schema.api;
}
type() {
return this.schema.type();
}
isTypeOf(type: string) {
return this.schema.isTypeOf(type);
}
findChildOptions(
predicate: (options: ODataModelOptions<any>) => boolean
): ODataModelOptions<any> | undefined {
if (predicate(this)) return this;
let match: ODataModelOptions<any> | undefined;
for (let ch of this.children) {
match = ch.findChildOptions(predicate);
if (match !== undefined) break;
}
return match;
}
configure({
findOptionsForType,
}: {
findOptionsForType: (type: string) => ODataModelOptions<any> | undefined;
}) {
if (this.base) {
const parent = findOptionsForType(this.base) as ODataModelOptions<any>;
parent.children.push(this);
this.parent = parent;
}
this.entitySet = this.api.findEntitySetForEntityType(this.type());
let concurrencyFields: string[] = [];
if (this.entitySet !== undefined) {
concurrencyFields =
this.entitySet.findAnnotation((a) => a.term === OPTIMISTIC_CONCURRENCY)
?.properties || [];
}
this._fields.forEach((field) => {
let concurrency = concurrencyFields.indexOf(field.field) !== -1;
field.configure({
findOptionsForType,
concurrency,
});
});
}
fields({
include_navigation = false,
include_parents = true,
}: {
include_parents?: boolean;
include_navigation?: boolean;
} = {}): ODataModelField<any>[] {
return [
...(include_parents && this.parent !== undefined
? this.parent.fields({ include_navigation, include_parents })
: []),
...this._fields.filter(
(field) => include_navigation || !field.navigation
),
];
}
field(name: keyof T | string) {
return this.fields({
include_parents: true,
include_navigation: true,
}).find(
(modelField: ODataModelField<any>) =>
modelField.name === name || modelField.field === name
);
}
attach(self: ODataModel<T>, resource: ODataModelResource<T>) {
if (
self._resource !== undefined &&
resource.type() !== self._resource.type() &&
!resource.isSubtypeOf(self._resource)
)
throw new Error(
`Can't reattach ${resource.type()} to ${self._resource.type()}`
);
const current = self._resource;
if (current === undefined || !current.isEqualTo(resource)) {
self._resource = resource;
self.events$.emit(
new ODataModelEvent('attach', {
model: self,
previous: current,
value: resource,
})
);
}
}
//# region Resource
static chain(
child: ODataModel<any> | ODataCollection<any, ODataModel<any>>
): [
ODataModel<any> | ODataCollection<any, ODataModel<any>>,
ODataModelField<any> | null
][] {
const chain = [] as any[];
let tuple:
| [
ODataModel<any> | ODataCollection<any, ODataModel<any>>,
ODataModelField<any> | null
]
| null = [child, null];
while (tuple !== null) {
const parent = tuple as [
ODataModel<any> | ODataCollection<any, ODataModel<any>>,
ODataModelField<any> | null
];
if (chain.some((p) => p[0] === parent[0])) break;
chain.splice(0, 0, parent);
tuple = tuple[0]._parent;
}
return chain;
}
static resource<T>(
child: ODataModel<T> | ODataCollection<T, ODataModel<T>>
): ODataModelResource<T> | ODataCollectionResource<T> {
let resource:
| ODataModelResource<any>
| ODataCollectionResource<any>
| undefined = undefined;
for (let [model, field] of ODataModelOptions.chain(child)) {
resource =
resource ||
model._resource ||
(ODataModelOptions.isModel(model)
? (model as ODataModel<any>)._meta.modelResourceFactory()
: (
model as ODataCollection<any, ODataModel<any>>
)._model.meta.collectionResourceFactory());
if (resource === undefined) break;
if (ODataModelOptions.isModel(model)) {
let key = (model as ODataModel<any>).key({
field_mapping: true,
}) as EntityKey<any>;
if (key !== undefined)
resource =
resource instanceof ODataEntitySetResource
? resource.entity(key)
: resource.key(key);
}
if (field === null) {
const query = model._resource?.cloneQuery().toQueryArguments();
if (query !== undefined) resource.query.apply(query);
continue;
}
resource = (field as ODataModelField<any>).resourceFactory<any, any>(
resource as ODataModelResource<any>
);
}
if (resource === undefined)
throw new Error(`resource: Can't build resource for ${child}`);
return resource;
}
collectionResourceFactory({
baseResource,
}: { baseResource?: ODataResource<T> } = {}): ODataCollectionResource<T> {
if (this.entitySet !== undefined)
return ODataEntitySetResource.factory<T>(
this.api,
this.entitySet.name,
this.type(),
new ODataPathSegments(),
baseResource?.cloneQuery() || new ODataQueryOptions()
);
if (baseResource === undefined)
throw new Error("collectionResourceFactory: Can't build resource");
return baseResource.clone() as ODataCollectionResource<T>;
}
modelResourceFactory({
baseResource,
}: {
fromSet?: boolean;
baseResource?: ODataResource<T>;
} = {}): ODataModelResource<T> {
const resource = this.collectionResourceFactory({ baseResource });
if (resource instanceof ODataEntitySetResource) return resource.entity();
return resource as ODataModelResource<T>;
}
entityResource(self: ODataModel<T>): ODataModelResource<T> {
let resource = this.modelResourceFactory({
baseResource: self._resource,
fromSet: true,
});
const key = self.key({ field_mapping: true }) as EntityKey<T>;
if (key !== undefined) return resource.key(key);
return resource as ODataModelResource<T>;
}
//#endregion
bind(
self: ODataModel<T>,
{
parent,
resource,
annots,
}: {
parent?: [
ODataModel<any> | ODataCollection<any, ODataModel<any>>,
ODataModelField<any> | null
];
resource?: ODataModelResource<T>;
annots?: ODataEntityAnnotations;
} = {}
) {
// Parent
if (parent !== undefined) {
self._parent = parent;
} else if (resource !== undefined) {
// Resource
this.attach(self, resource);
}
// Annotations
self._annotations =
annots || new ODataEntityAnnotations(ODataHelper[DEFAULT_VERSION]);
const fields = this.fields({
include_navigation: true,
include_parents: true,
});
for (let field of fields) {
Object.defineProperty(self, field.name, {
configurable: true,
get: () => this._get(self, field as ODataModelField<any>),
set: (value: any) =>
this._set(self, field as ODataModelField<any>, value),
});
}
}
query(
self: ODataModel<T>,
resource: ODataModelResource<T>,
func: (q: {
select(opts?: Select<T>): OptionHandler<Select<T>>;
expand(opts?: Expand<T>): OptionHandler<Expand<T>>;
format(opts?: string): OptionHandler<string>;
apply(query: ODataQueryArguments<T>): void;
}) => void
) {
func(resource.query);
this.attach(self, resource);
return self;
}
resolveKey(
value: ODataModel<T> | T | { [name: string]: any },
{
field_mapping = false,
resolve = true,
}: { field_mapping?: boolean; resolve?: boolean } = {}
): EntityKey<T> | { [name: string]: any } | undefined {
const keyTypes = this.schema.keys({ include_parents: true });
const key: any = {};
for (var kt of keyTypes) {
let v = value as any;
let options = this as ODataModelOptions<any>;
let field: ODataModelField<any> | undefined;
for (let name of kt.name.split('/')) {
if (options === undefined) break;
field = options
.fields({ include_parents: true })
.find((field: ODataModelField<any>) => field.field === name);
if (field !== undefined) {
v =
Types.isPlainObject(v) || ODataModelOptions.isModel(v)
? v[field.name]
: v;
options = field.meta as ODataModelOptions<any>;
}
}
if (field === undefined) return undefined;
let name = field_mapping ? field.field : field.name;
if (kt.alias !== undefined) name = kt.alias;
key[name] = v;
}
if (Types.isEmpty(key)) return undefined;
return resolve ? Objects.resolveKey(key) : key;
}
resolveReferential(
value: ODataModel<T> | T | { [name: string]: any } | null,
field: ODataModelField<any>,
{
field_mapping = false,
resolve = true,
}: { field_mapping?: boolean; resolve?: boolean } = {}
): { [name: string]: any } | undefined {
const referential: any = {};
for (var ref of field.referentials) {
let from = this.fields({ include_parents: true }).find(
(p: any) => p.field === ref.referencedProperty
);
let to = field.options
.fields({ include_parents: true })
.find((field: ODataModelField<any>) => field.field === ref.property);
if (from !== undefined && to !== undefined) {
let name = field_mapping ? to.field : to.name;
referential[name] = value && (value as any)[from.name];
}
}
if (Types.isEmpty(referential)) return undefined;
return resolve
? Objects.resolveKey(referential, { single: false })
: referential;
}
resolveReferenced(
value: ODataModel<T> | T | { [name: string]: any } | null,
field: ODataModelField<any>,
{
field_mapping = false,
resolve = true,
}: { field_mapping?: boolean; resolve?: boolean } = {}
): { [name: string]: any } | undefined {
const referenced: any = {};
for (var ref of field.referentials) {
let from = this.fields({ include_parents: true }).find(
(field: ODataModelField<any>) => field.field === ref.property
);
let to = (field.meta as ODataModelOptions<any>)
.fields({ include_parents: true })
.find(
(field: ODataModelField<any>) =>
field.field === ref.referencedProperty
);
if (from !== undefined && to !== undefined) {
let name = field_mapping ? to.field : to.name;
referenced[name] = value && (value as any)[from.name];
}
}
if (Types.isEmpty(referenced)) return undefined;
return resolve
? Objects.resolveKey(referenced, { single: false })
: referenced;
}
validate(
self: ODataModel<T>,
{
method,
navigation = false,
}: {
method?: 'create' | 'update' | 'modify';
navigation?: boolean;
} = {}
): { [name: string]: string[] } | undefined {
const errors = this.fields({
include_parents: true,
include_navigation: navigation,
}).reduce((acc, field) => {
let value = (self as any)[field.name];
let errs = field.validate(value, { method });
return errs !== undefined
? Object.assign(acc, { [field.name]: errs })
: acc;
}, {});
return !Types.isEmpty(errors) ? errors : undefined;
}
defaults(): T | { [name: string]: any } | undefined {
const defs = this.fields().reduce((acc, field) => {
let value = field.defaults();
return value !== undefined
? Object.assign(acc, { [field.name]: value })
: acc;
}, {});
return !Types.isEmpty(defs) ? defs : undefined;
}
hasChanged(
self: ODataModel<T>,
{ include_navigation = false }: { include_navigation?: boolean } = {}
): boolean {
return (
!Types.isEmpty(self._changes) ||
Object.values(self._relations)
.filter(({ field }) => !field.navigation || include_navigation)
.some(
({ field, state, model }) =>
(!include_navigation || field.navigation) &&
(state === ODataModelState.Changed ||
(model != undefined && model.hasChanged({ include_navigation })))
)
);
}
asEntity<R, M extends ODataModel<T>>(self: M, func: (model: M) => R): R {
const parent = self._parent;
self._parent = null;
const result = func(self);
if (result instanceof Observable) {
return (result as any).pipe(finalize(() => (self._parent = parent)));
} else {
self._parent = parent;
return result;
}
}
toEntity(
self: ODataModel<T>,
{
client_id = false,
include_navigation = false,
include_concurrency = false,
include_computed = false,
include_key = true,
include_non_field = false,
changes_only = false,
field_mapping = false,
chain = [],
}: {
client_id?: boolean;
include_navigation?: boolean;
include_concurrency?: boolean;
include_computed?: boolean;
include_key?: boolean;
include_non_field?: boolean;
changes_only?: boolean;
field_mapping?: boolean;
chain?: (ODataModel<any> | ODataCollection<any, ODataModel<any>>)[];
} = {}
): T | { [name: string]: any } {
let attrs = self.attributes({
changes_only,
field_mapping,
include_concurrency,
include_computed,
include_non_field,
});
let relations = Object.entries(self._relations)
.filter(
// Chain
([, { model }]) => chain.every((c) => c !== model)
)
.filter(
// Changes only
([, { model, state }]) =>
!changes_only ||
(changes_only &&
(state === ODataModelState.Changed ||
(model != undefined && model.hasChanged({ include_navigation }))))
)
.filter(
([, { field, model }]) =>
// Navigation
(include_navigation && field.navigation && model !== null) ||
!field.navigation
)
.map(([k, { model, field, state }]) => {
let changesOnly =
changes_only &&
state !== ODataModelState.Changed &&
!!field.navigation;
let includeKey = include_key && !!field.navigation;
if (ODataModelOptions.isModel(model)) {
return [
k,
(model as ODataModel<any>).toEntity({
client_id,
include_navigation,
include_concurrency,
include_non_field,
field_mapping,
changes_only: changesOnly,
include_key: includeKey,
chain: [self, ...chain],
}),
];
} else if (ODataModelOptions.isCollection(model)) {
return [
k,
(model as ODataCollection<any, ODataModel<any>>).toEntities({
client_id,
include_navigation,
include_concurrency,
include_non_field,
field_mapping,
changes_only: changesOnly,
include_key: includeKey,
chain: [self, ...chain],
}),
];
}
return [k, model];
})
.reduce((acc, [k, v]) => {
const name = field_mapping
? this.fields().find(
(field: ODataModelField<any>) => field.name === k
)?.field || k
: k;
return Object.assign(acc, { [name]: v });
}, {});
// Create entity
let entity = { ...attrs, ...relations };
// Add client_id
if (client_id) {
(<any>entity)[this.cid] = (<any>self)[this.cid];
}
// Add key
if (include_key) {
entity = {
...entity,
...(this.resolveKey(self, { field_mapping, resolve: false }) as {}),
};
}
// Add type
if (
self._parent !== null &&
((ODataModelOptions.isModel(self._parent[0]) &&
(self._parent[1] as ODataModelField<any>).meta !== self._meta) ||
(ODataModelOptions.isCollection(self._parent[0]) &&
(self._parent[0] as ODataCollection<any, ODataModel<any>>)._model
.meta !== self._meta))
) {
this.api.options.helper.type(entity, this.schema.type());
}
return entity;
}
attributes(
self: ODataModel<T>,
{
changes_only = false,
include_concurrency = false,
include_computed = false,
include_non_field = false,
field_mapping = false,
}: {
changes_only?: boolean;
include_concurrency?: boolean;
include_computed?: boolean;
include_non_field?: boolean;
field_mapping?: boolean;
} = {}
): { [name: string]: any } {
// Attributes by fields (attributes for the model type)
const fieldAttrs = this.fields().reduce((acc, f) => {
const isChanged = f.name in self._changes;
const name = field_mapping ? f.field : f.name;
const value = isChanged
? self._changes[f.name]
: self._attributes[f.name];
if (f.concurrency && include_concurrency) {
return Object.assign(acc, { [name]: value });
} else if (f.computed && include_computed) {
return Object.assign(acc, { [name]: value });
} else if (changes_only && isChanged) {
return Object.assign(acc, { [name]: value });
} else if (!changes_only && !f.concurrency && !f.computed) {
return Object.assign(acc, { [name]: value });
} else {
return acc;
}
}, {});
if (!include_non_field) return fieldAttrs;
const names = Object.keys(fieldAttrs);
// Attributes from object (attributes for object)
const nonFieldAttrs = Object.entries(self)
.filter(
([k]) =>
names.indexOf(k) === -1 && !k.startsWith('_') && !k.endsWith('$')
)
.reduce((acc, [k, v]) => Object.assign(acc, { [k]: v }), {});
return { ...fieldAttrs, ...nonFieldAttrs };
}
reset(
self: ODataModel<T>,
{ name, silent = false }: { name?: string; silent?: boolean } = {}
) {
if (!Types.isEmpty(name) && (name as string) in self._changes) {
const value = self._attributes[name as string];
const previous = self._changes[name as string];
delete self._changes[name as string];
if (!silent) {
self.events$.emit(
new ODataModelEvent('change', {
model: self,
track: name,
value,
previous,
})
);
}
} else if (Types.isEmpty(name)) {
const entries = Object.entries(self._changes);
self._changes = {};
if (!silent) {
entries.forEach((entry) => {
self.events$.emit(
new ODataModelEvent('change', {
track: entry[0],
model: self,
value: self._attributes[entry[0]],
previous: entry[1],
})
);
});
}
}
}
assign(
self: ODataModel<T>,
entity: Partial<T> | { [name: string]: any },
{
reset = false,
silent = false,
}: { reset?: boolean; silent?: boolean } = {}
) {
self._resetting = reset;
self._silent = silent;
const changes: string[] = [];
// Apply entity
const model = self as any;
Object.entries(entity)
.filter(([, value]) => value !== undefined) // Filter undefined
.forEach(([key, value]) => {
const field = this.fields({
include_parents: true,
include_navigation: true,
}).find(
(field: ODataModelField<any>) =>
(self._resetting && field.field === key) || field.name === key
);
if (field !== undefined) {
// Delegated to private setter
if (this._set(self, field, value)) {
changes.push(field.name);
if (
ODataModelOptions.isCollection(value) ||
ODataModelOptions.isModel(value)
)
// Set Parent
value._parent = [self, field];
}
} else {
// Basic assignment
const current = model[key];
model[key] = value;
if (current !== value) changes.push(key);
}
});
if (!self._silent && changes.length > 0) {
self.events$.emit(
new ODataModelEvent(self._resetting ? 'reset' : 'update', {
model: self,
options: { changes },
})
);
}
self._resetting = false;
self._silent = false;
}
static isModel(obj: any) {
return {}.toString.call(obj) === '[object Model]';
}
static isCollection(obj: any) {
return {}.toString.call(obj) === '[object Collection]';
}
private updateCollection<F>(
self: ODataModel<T>,
field: ODataModelField<F>,
collection: ODataCollection<F, ODataModel<F>>,
value: ODataCollection<F, ODataModel<F>> | T[] | { [name: string]: any }[]
) {
if (
ODataModelOptions.isCollection(value) &&
collection.equals(value as ODataCollection<F, ODataModel<F>>)
) {
return false;
}
if (ODataModelOptions.isCollection(value)) {
value = (value as ODataCollection<any, ODataModel<any>>).toEntities(
INCLUDE_DEEP
);
}
collection._annotations = field.annotationsFactory(
self.annots()
) as ODataEntitiesAnnotations;
collection.assign(value as T[] | { [name: string]: any }[], {
reset: self._resetting,
silent: self._silent,
});
return collection.hasChanged();
}
private updateModel<F>(
self: ODataModel<T>,
field: ODataModelField<F>,
model: ODataModel<F>,
value: ODataModel<F> | F | { [name: string]: any }
) {
if (
ODataModelOptions.isModel(value) &&
model.equals(value as ODataModel<F>)
) {
return false;
}
if (ODataModelOptions.isModel(value)) {
value = (value as ODataModel<F>).toEntity(INCLUDE_DEEP);
}
model._annotations = field.annotationsFactory(
self.annots()
) as ODataEntityAnnotations;
model.assign(value as F | { [name: string]: any }, {
reset: self._resetting,
silent: self._silent,
});
return model.hasChanged();
}
private _get<F>(
self: ODataModel<T>,
field: ODataModelField<F>
): F | ODataModel<F> | ODataCollection<F, ODataModel<F>> | null | undefined {
if (field.isStructuredType()) {
return self._relations[field.name]?.model;
} else {
return this.attributes(self, {
include_concurrency: true,
include_computed: true,
})[field.name];
}
}
private _setStructured<F>(
self: ODataModel<T>,
field: ODataModelField<F>,
value:
| F
| F[]
| { [name: string]: any }
| { [name: string]: any }[]
| ODataModel<F>
| ODataCollection<F, ODataModel<F>>
| null
): boolean {
let changed = false;
// Ensures that the relation exists
if (!(field.name in self._relations)) {
self._relations[field.name] = {
state: ODataModelState.Unchanged,
field: field,
};
}
const relation = self._relations[field.name];
const currentModel = relation.model;
if (value === null) {
relation.model = value as null;
changed = currentModel !== value;
this._unsubscribe(self, relation);
} else if (ODataModelOptions.isCollection(currentModel)) {
changed = this.updateCollection<F>(
self,
field,
currentModel as ODataCollection<F, ODataModel<F>>,
value as
| ODataCollection<F, ODataModel<F>>
| T[]
| { [name: string]: any }[]
);
} else if (ODataModelOptions.isModel(currentModel)) {
changed = this.updateModel<F>(
self,
field,
currentModel as ODataModel<F>,
value as ODataModel<F> | F | { [name: string]: any }
);
} else {
relation.model =
ODataModelOptions.isCollection(value) ||
ODataModelOptions.isModel(value)
? (value as ODataModel<F> | ODataCollection<F, ODataModel<F>>)
: field.modelCollectionFactory<T, F>({
parent: self,
value: value,
reset: self._resetting,
});
changed = true;
this._subscribe(self, relation);
}
if (!ODataModelOptions.isCollection(relation.model)) {
var ref = field.meta?.resolveReferential(relation.model, field);
if (ref !== undefined) {
Object.entries(ref).forEach(([k, v]) =>
this._setValue(self, k, v, false)
);
}
}
relation.state =
self._resetting || !changed
? ODataModelState.Unchanged
: ODataModelState.Changed;
if (!self._silent && changed) {
self.events$.emit(
new ODataModelEvent('change', {
track: field.name,
model: self,
value: relation.model,
previous: currentModel,
})
);
}
return changed;
}
private _setValue<F>(
self: ODataModel<T>,
field: string,
value:
| F
| F[]
| { [name: string]: any }
| { [name: string]: any }[]
| ODataModel<F>
| ODataCollection<F, ODataModel<F>>
| null,
key?: boolean
): boolean {
let changed = false;
const attrs = this.attributes(self, {
include_concurrency: true,
include_computed: true,
});
const currentValue = attrs[field];
changed = !Types.isEqual(currentValue, value);
if (self._resetting) {
delete self._changes[field];
self._attributes[field] = value;
} else if (Types.isEqual(value, self._attributes[field])) {
delete self._changes[field];
} else if (changed) {
self._changes[field] = value;
}
if (!self._silent && changed) {
self.events$.emit(
new ODataModelEvent('change', {
track: field,
model: self,
value,
previous: currentValue,
options: { key },
})
);
}
return changed;
}
private _set<F>(
self: ODataModel<T>,
field: ODataModelField<F>,
value:
| F
| F[]
| { [name: string]: any }
| { [name: string]: any }[]
| ODataModel<F>
| ODataCollection<F, ODataModel<F>>
| null
): boolean {
return field.isStructuredType()
? this._setStructured(self, field, value)
: this._setValue(self, field.name, value, field.isKey());
}
private _unsubscribe<F>(
self: ODataModel<T>,
relation: ODataModelRelation<F>
) {
if (relation.subscription) {
relation.subscription.unsubscribe();
delete relation.subscription;
}
}
private _subscribe<F>(self: ODataModel<T>, relation: ODataModelRelation<F>) {
if (relation.subscription) {
throw new Error('Subscription already exists');
}
if (relation.model == null) {
throw new Error('Subscription model is null');
}
relation.subscription = relation.model.events$.subscribe(
(event: ODataModelEvent<any>) => {
if (
BUBBLING.indexOf(event.name) !== -1 &&
event.bubbling &&
!event.visited(self)
) {
if (event.model === relation.model) {
if (
event.name === 'change' &&
relation.field.navigation &&
event.options?.key
) {
var ref = (relation.model as ODataModel<any>).referential(
relation.field
);
if (ref !== undefined) {
Object.entries(ref).forEach(([k, v]) =>
this._setValue(self, k, v, false)
);
}
}
}
event.push(self, relation.field.name);
self.events$.emit(event);
}
}
);
}
} | the_stack |
/* eslint-disable node/no-extraneous-import */
import myProbotApp from '../src/snippet-bot';
import {SNIPPET_BOT_LABELS} from '../src/labels';
import * as apiLabelsModule from '../src/api-labels';
import * as snippetsModule from '../src/snippets';
import schema from '../src/config-schema.json';
import {CONFIGURATION_FILE_PATH} from '../src/configuration';
import {Snippets} from '../src/snippets';
import * as configUtilsModule from '@google-automations/bot-config-utils';
import * as labelUtilsModule from '@google-automations/label-utils';
import {ConfigChecker} from '@google-automations/bot-config-utils';
import {resolve} from 'path';
import {Probot, ProbotOctokit} from 'probot';
import snapshot from 'snap-shot-it';
import nock from 'nock';
import * as fs from 'fs';
import {describe, it, beforeEach, afterEach} from 'mocha';
import * as sinon from 'sinon';
nock.disableNetConnect();
const fixturesPath = resolve(__dirname, '../../test/fixtures');
function createConfigResponse(configFile: string) {
const config = fs.readFileSync(resolve(fixturesPath, configFile));
const base64Config = config.toString('base64');
return {
sha: '',
node_id: '',
size: base64Config.length,
url: '',
content: base64Config,
encoding: 'base64',
};
}
describe('snippet-bot scheduler handler', () => {
let probot: Probot;
const sandbox = sinon.createSandbox();
let getConfigStub: sinon.SinonStub;
let syncLabelsStub: sinon.SinonStub;
beforeEach(() => {
probot = new Probot({
githubToken: 'abc123',
Octokit: ProbotOctokit.defaults({
retry: {enabled: false},
throttle: {enabled: false},
}),
});
probot.load(myProbotApp);
getConfigStub = sandbox.stub(configUtilsModule, 'getConfig');
syncLabelsStub = sandbox.stub(labelUtilsModule, 'syncLabels');
});
afterEach(() => {
nock.cleanAll();
sandbox.restore();
});
it('does not call syncLabels for repos without the config', async () => {
getConfigStub.resolves(null);
await probot.receive({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
name: 'schedule.repository' as any,
payload: {
repository: {
name: 'testRepo',
owner: {
login: 'testOwner',
},
},
organization: {
login: 'googleapis',
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any,
id: 'abc123',
});
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'googleapis',
'testRepo',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
sinon.assert.notCalled(syncLabelsStub);
});
it('calls syncLabels for repos with the config', async () => {
getConfigStub.resolves({
alwaysCreateStatusCheck: false,
ignoreFiles: [],
});
await probot.receive({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
name: 'schedule.repository' as any,
payload: {
repository: {
name: 'testRepo',
owner: {
login: 'testOwner',
},
},
organization: {
login: 'googleapis',
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any,
id: 'abc123',
});
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'googleapis',
'testRepo',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
sinon.assert.calledOnceWithExactly(
syncLabelsStub,
sinon.match.instanceOf(ProbotOctokit),
'googleapis',
'testRepo',
SNIPPET_BOT_LABELS
);
});
});
describe('snippet-bot config validation', () => {
let probot: Probot;
const sandbox = sinon.createSandbox();
let getApiLabelsStub: sinon.SinonStub<[string], Promise<{}>>;
let getSnippetsStub: sinon.SinonStub<[string], Promise<Snippets>>;
let getConfigStub: sinon.SinonStub;
beforeEach(() => {
probot = new Probot({
githubToken: 'abc123',
Octokit: ProbotOctokit.defaults({
retry: {enabled: false},
throttle: {enabled: false},
}),
});
probot.load(myProbotApp);
getApiLabelsStub = sandbox.stub(apiLabelsModule, 'getApiLabels');
const products = require(resolve(fixturesPath, './products'));
getApiLabelsStub.resolves(products);
const testSnippets = {};
getSnippetsStub = sandbox.stub(snippetsModule, 'getSnippets');
getSnippetsStub.resolves(testSnippets);
getConfigStub = sandbox.stub(configUtilsModule, 'getConfig');
getConfigStub.resolves({
ignoreFiles: ['ignore.py'],
aggregateChecks: false,
});
});
afterEach(() => {
nock.cleanAll();
sandbox.restore();
});
it('submits a failing check with a broken config file', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const payload = require(resolve(fixturesPath, './pr_event'));
const files_payload = require(resolve(
fixturesPath,
'./pr_files_config_added'
));
const configBlob = createConfigResponse('broken_config.yaml');
const requests = nock('https://api.github.com')
.get('/repos/tmatsuo/repo-automation-bots/pulls/14/files?per_page=100')
.reply(200, files_payload)
.get(
'/repos/tmatsuo/repo-automation-bots/git/blobs/223828dbd668486411b475665ab60855ba9898f3'
)
.reply(200, configBlob)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(404, {});
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
requests.done();
diffRequests.done();
});
it('does not submits a failing check with a correct config file', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const payload = require(resolve(fixturesPath, './pr_event'));
const files_payload = require(resolve(
fixturesPath,
'./pr_files_config_added'
));
const configBlob = createConfigResponse('correct_config.yaml');
const requests = nock('https://api.github.com')
.get('/repos/tmatsuo/repo-automation-bots/pulls/14/files?per_page=100')
.reply(200, files_payload)
.get(
'/repos/tmatsuo/repo-automation-bots/git/blobs/223828dbd668486411b475665ab60855ba9898f3'
)
.reply(200, configBlob);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(404, {});
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
requests.done();
diffRequests.done();
});
});
describe('snippet-bot bot-config-utils integration', () => {
let probot: Probot;
const sandbox = sinon.createSandbox();
let getApiLabelsStub: sinon.SinonStub<[string], Promise<{}>>;
let getSnippetsStub: sinon.SinonStub<[string], Promise<Snippets>>;
let validateConfigStub: sinon.SinonStub;
beforeEach(() => {
probot = new Probot({
githubToken: 'abc123',
Octokit: ProbotOctokit.defaults({
retry: {enabled: false},
throttle: {enabled: false},
}),
});
probot.load(myProbotApp);
getApiLabelsStub = sandbox.stub(apiLabelsModule, 'getApiLabels');
const products = require(resolve(fixturesPath, './products'));
getApiLabelsStub.resolves(products);
const testSnippets = {};
getSnippetsStub = sandbox.stub(snippetsModule, 'getSnippets');
getSnippetsStub.resolves(testSnippets);
validateConfigStub = sandbox.stub(
ConfigChecker.prototype,
'validateConfigChanges'
);
validateConfigStub.resolves(undefined);
});
afterEach(() => {
nock.cleanAll();
sandbox.restore();
});
it('survives config validation with an empty config file', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const payload = require(resolve(fixturesPath, './pr_event'));
const scopes = [
nock('https://api.github.com')
.get(
'/repos/tmatsuo/repo-automation-bots/contents/.github%2Fsnippet-bot.yml'
)
.reply(200, createConfigResponse('empty.yaml'))
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, [])
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200),
nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(404, {}),
];
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
sinon.assert.calledOnceWithExactly(
validateConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
'ce03c1b7977aadefb5f6afc09901f106ee6ece6a',
14
);
for (const scope of scopes) {
scope.done();
}
});
});
describe('snippet-bot', () => {
let probot: Probot;
const tarBall = fs.readFileSync(
resolve(fixturesPath, 'tmatsuo-python-docs-samples-abcde.tar.gz')
);
const sandbox = sinon.createSandbox();
let getApiLabelsStub: sinon.SinonStub<[string], Promise<{}>>;
let getSnippetsStub: sinon.SinonStub<[string], Promise<Snippets>>;
let invalidateCacheStub: sinon.SinonStub;
let getConfigStub: sinon.SinonStub;
let validateConfigStub: sinon.SinonStub;
beforeEach(() => {
probot = new Probot({
githubToken: 'abc123',
Octokit: ProbotOctokit.defaults({
retry: {enabled: false},
throttle: {enabled: false},
}),
});
probot.load(myProbotApp);
getApiLabelsStub = sandbox.stub(apiLabelsModule, 'getApiLabels');
const products = require(resolve(fixturesPath, './products'));
getApiLabelsStub.resolves(products);
const testSnippets = {};
getSnippetsStub = sandbox.stub(snippetsModule, 'getSnippets');
getSnippetsStub.resolves(testSnippets);
getConfigStub = sandbox.stub(configUtilsModule, 'getConfig');
getConfigStub.resolves({
ignoreFiles: ['ignore.py'],
aggregateChecks: false,
});
validateConfigStub = sandbox.stub(
ConfigChecker.prototype,
'validateConfigChanges'
);
validateConfigStub.resolves(undefined);
});
afterEach(() => {
nock.cleanAll();
sandbox.restore();
});
describe('responds to PR', () => {
it('quits early', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const payload = require(resolve(fixturesPath, './pr_event'));
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(404, {});
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
sinon.assert.calledOnceWithExactly(
validateConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
'ce03c1b7977aadefb5f6afc09901f106ee6ece6a',
14
);
});
it('quits early for PRs with null head', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const payload = require(resolve(fixturesPath, './pr_event_null_head'));
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
});
it('quits early if PR is closed', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const payload = require(resolve(fixturesPath, './pr_event_closed'));
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
});
it('sets a "failure" context on PR without a warning about removal of region tags in use', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const diffResponse = fs.readFileSync(resolve(fixturesPath, 'diff.txt'));
const payload = require(resolve(fixturesPath, './pr_event'));
const blob = require(resolve(fixturesPath, './failure_blob'));
const requests = nock('https://api.github.com')
.get(
'/repos/tmatsuo/repo-automation-bots/contents/test.py?ref=ce03c1b7977aadefb5f6afc09901f106ee6ece6a'
)
.reply(200, blob)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200)
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, [])
.post(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments',
body => {
snapshot(body);
return true;
}
)
.reply(200)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(200, diffResponse);
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
requests.done();
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('quits early for normal labels', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const payload = require(resolve(
fixturesPath,
'./pr_event_label_ignored'
));
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('responds to snippet-bot:force-run label, invalidating the Snippet cache', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
invalidateCacheStub = sandbox.stub(snippetsModule, 'invalidateCache');
const diffResponse = fs.readFileSync(resolve(fixturesPath, 'diff.txt'));
const payload = require(resolve(fixturesPath, './pr_event_label_added'));
const blob = require(resolve(fixturesPath, './failure_blob'));
const requests = nock('https://api.github.com')
.delete(
// For removing the label.
'/repos/tmatsuo/repo-automation-bots/issues/14/labels/snippet-bot%3Aforce-run'
)
.reply(200)
.get(
'/repos/tmatsuo/repo-automation-bots/contents/test.py?ref=ce03c1b7977aadefb5f6afc09901f106ee6ece6a'
)
.reply(200, blob)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200)
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, [])
.post(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments',
body => {
snapshot(body);
return true;
}
)
.reply(200)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(200, diffResponse);
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
sinon.assert.calledOnce(invalidateCacheStub);
requests.done();
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('quits early for an irelevant issue_comment.edited event', async () => {
const payload = require(resolve(
fixturesPath,
'./pr_event_comment_edited_irelevant'
));
await probot.receive({
name: 'issue_comment',
payload,
id: 'abc123',
});
sinon.assert.notCalled(getConfigStub);
});
it('responds to refresh checkbox, invalidating the Snippet cache, updating without region tag changes', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
invalidateCacheStub = sandbox.stub(snippetsModule, 'invalidateCache');
const payload = require(resolve(
fixturesPath,
'./pr_event_comment_edited'
));
const prResponse = require(resolve(fixturesPath, './pr_response'));
const requests = nock('https://api.github.com')
.get('/repos/tmatsuo/repo-automation-bots/pulls/14')
.reply(200, prResponse)
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, []);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(200, '');
await probot.receive({
name: 'issue_comment',
payload,
id: 'abc123',
});
sinon.assert.calledOnce(invalidateCacheStub);
requests.done();
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('ignores 404 error upon label deletion', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const diffResponse = fs.readFileSync(resolve(fixturesPath, 'diff.txt'));
const payload = require(resolve(fixturesPath, './pr_event_label_added'));
const blob = require(resolve(fixturesPath, './failure_blob'));
const requests = nock('https://api.github.com')
.delete(
// For removing the label.
'/repos/tmatsuo/repo-automation-bots/issues/14/labels/snippet-bot%3Aforce-run'
)
.reply(404)
.get(
'/repos/tmatsuo/repo-automation-bots/contents/test.py?ref=ce03c1b7977aadefb5f6afc09901f106ee6ece6a'
)
.reply(200, blob)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200)
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, [])
.post(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments',
body => {
snapshot(body);
return true;
}
)
.reply(200)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(200, diffResponse);
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
requests.done();
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('does not submit a check for unmatched region tags on PR if there are no region tags', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const diffResponse = fs.readFileSync(resolve(fixturesPath, 'diff.txt'));
const payload = require(resolve(fixturesPath, './pr_event'));
const blob = require(resolve(fixturesPath, './blob_no_region_tags'));
const requests = nock('https://api.github.com')
.get(
'/repos/tmatsuo/repo-automation-bots/contents/test.py?ref=ce03c1b7977aadefb5f6afc09901f106ee6ece6a'
)
.reply(200, blob)
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, [])
.post(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments',
body => {
snapshot(body);
return true;
}
)
.reply(200)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(200, diffResponse);
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
requests.done();
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('does not submit a check on PR by ignoreFile', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const diffResponse = fs.readFileSync(resolve(fixturesPath, 'diff.txt'));
const payload = require(resolve(fixturesPath, './pr_event'));
getConfigStub.reset();
getConfigStub.resolves({
ignoreFiles: ['test.py'],
aggregateChecks: false,
});
const requests = nock('https://api.github.com')
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, [])
.post(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments',
body => {
snapshot(body);
return true;
}
)
.reply(200);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(200, diffResponse);
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
requests.done();
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('submits 3 checks on PR because alwaysCreateStatusCheck is true', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const diffResponse = fs.readFileSync(
resolve(fixturesPath, 'diff_without_regiontag_changes.txt')
);
const payload = require(resolve(fixturesPath, './pr_event'));
getConfigStub.reset();
getConfigStub.resolves({
ignoreFiles: ['test.py'],
alwaysCreateStatusCheck: true,
aggregateChecks: false,
});
const requests = nock('https://api.github.com')
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200)
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, [])
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(200, diffResponse);
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
requests.done();
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('agggregates 3 checks into one because aggregateChecks is true', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const diffResponse = fs.readFileSync(
resolve(fixturesPath, 'diff_without_regiontag_changes.txt')
);
const payload = require(resolve(fixturesPath, './pr_event'));
getConfigStub.reset();
getConfigStub.resolves({
ignoreFiles: ['test.py'],
aggregateChecks: true,
});
const requests = nock('https://api.github.com')
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, [])
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(200, diffResponse);
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
requests.done();
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('does not create a comment because no region tag is edited in the PR', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const diffResponse = fs.readFileSync(
resolve(fixturesPath, 'diff_without_regiontag_changes.txt')
);
const payload = require(resolve(fixturesPath, './pr_event'));
getConfigStub.reset();
getConfigStub.resolves({
ignoreFiles: ['test.py'],
aggregateChecks: true,
});
const requests = nock('https://api.github.com')
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, [])
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(200, diffResponse);
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
requests.done();
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('update the past comment even if no region tag is edited in the PR', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const diffResponse = fs.readFileSync(
resolve(fixturesPath, 'diff_without_regiontag_changes.txt')
);
const payload = require(resolve(fixturesPath, './pr_event'));
getConfigStub.reset();
getConfigStub.resolves({
ignoreFiles: ['test.py'],
aggregateChecks: true,
});
const requests = nock('https://api.github.com')
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, [
{
body: '<!-- probot comment [11237253]-->',
id: 42,
},
])
.patch(
'/repos/tmatsuo/repo-automation-bots/issues/comments/42',
body => {
snapshot(body);
return true;
}
)
.reply(200)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(200, diffResponse);
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
requests.done();
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('quits early if there is no config file', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const payload = require(resolve(fixturesPath, './pr_event'));
getConfigStub.reset();
getConfigStub.resolves(null);
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
// Make sure we check the config schema when
// adding the config file for the first time.
sinon.assert.calledOnceWithExactly(
validateConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
'ce03c1b7977aadefb5f6afc09901f106ee6ece6a',
14
);
});
it('gives warnings about removing region tag in use', async () => {
getApiLabelsStub.reset();
const products = require(resolve(fixturesPath, './products'));
getApiLabelsStub.resolves(products);
getSnippetsStub.reset();
const snippets = require(resolve(fixturesPath, './snippets'));
getSnippetsStub.resolves(snippets);
// eslint-disable-next-line @typescript-eslint/no-var-requires
const diffResponse = fs.readFileSync(resolve(fixturesPath, 'diff.txt'));
const payload = require(resolve(fixturesPath, './pr_event'));
const blob = require(resolve(fixturesPath, './failure_blob'));
const requests = nock('https://api.github.com')
.get(
'/repos/tmatsuo/repo-automation-bots/contents/test.py?ref=ce03c1b7977aadefb5f6afc09901f106ee6ece6a'
)
.reply(200, blob)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200)
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, [])
.post(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments',
body => {
snapshot(body);
return true;
}
)
.reply(200)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(200, diffResponse);
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
sinon.assert.calledOnce(getApiLabelsStub);
sinon.assert.calledOnce(getSnippetsStub);
requests.done();
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('creates failure check with combined results', async () => {
getApiLabelsStub.reset();
const products = require(resolve(fixturesPath, './products'));
getApiLabelsStub.resolves(products);
getSnippetsStub.reset();
const snippets = require(resolve(fixturesPath, './snippets'));
getSnippetsStub.resolves(snippets);
getConfigStub.reset();
getConfigStub.resolves({aggregateChecks: true});
// eslint-disable-next-line @typescript-eslint/no-var-requires
const diffResponse = fs.readFileSync(resolve(fixturesPath, 'diff.txt'));
const payload = require(resolve(fixturesPath, './pr_event'));
const blob = require(resolve(fixturesPath, './failure_blob'));
const requests = nock('https://api.github.com')
.get(
'/repos/tmatsuo/repo-automation-bots/contents/test.py?ref=ce03c1b7977aadefb5f6afc09901f106ee6ece6a'
)
.reply(200, blob)
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, [])
.post(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments',
body => {
snapshot(body);
return true;
}
)
.reply(200)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(200, diffResponse);
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
sinon.assert.calledOnce(getApiLabelsStub);
sinon.assert.calledOnce(getSnippetsStub);
requests.done();
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('does not give warnings about wrong product prefix with snippet-bot:no-prefix-req label', async () => {
getSnippetsStub.reset();
const snippets = require(resolve(fixturesPath, './snippets'));
getSnippetsStub.resolves(snippets);
// eslint-disable-next-line @typescript-eslint/no-var-requires
const diffResponse = fs.readFileSync(resolve(fixturesPath, 'diff.txt'));
const payload = require(resolve(
fixturesPath,
'./pr_event_no_prefix_req'
));
const blob = require(resolve(fixturesPath, './failure_blob'));
const requests = nock('https://api.github.com')
.get(
'/repos/tmatsuo/repo-automation-bots/contents/test.py?ref=ce03c1b7977aadefb5f6afc09901f106ee6ece6a'
)
.reply(200, blob)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200)
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, [])
.post(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments',
body => {
snapshot(body);
return true;
}
)
.reply(200)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(200, diffResponse);
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
sinon.assert.calledOnce(getSnippetsStub);
requests.done();
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('gives fyi message for removing frozen region tag', async () => {
getApiLabelsStub.reset();
const products = require(resolve(fixturesPath, './products'));
getApiLabelsStub.resolves(products);
getSnippetsStub.reset();
const snippets = require(resolve(fixturesPath, './snippets-frozen'));
getSnippetsStub.resolves(snippets);
// eslint-disable-next-line @typescript-eslint/no-var-requires
const diffResponse = fs.readFileSync(resolve(fixturesPath, 'diff.txt'));
const payload = require(resolve(fixturesPath, './pr_event'));
const blob = require(resolve(fixturesPath, './failure_blob'));
const requests = nock('https://api.github.com')
.get(
'/repos/tmatsuo/repo-automation-bots/contents/test.py?ref=ce03c1b7977aadefb5f6afc09901f106ee6ece6a'
)
.reply(200, blob)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200)
.get(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments?per_page=50'
)
.reply(200, [])
.post(
'/repos/tmatsuo/repo-automation-bots/issues/14/comments',
body => {
snapshot(body);
return true;
}
)
.reply(200)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200)
.post('/repos/tmatsuo/repo-automation-bots/check-runs', body => {
snapshot(body);
return true;
})
.reply(200);
const diffRequests = nock('https://github.com')
.get('/tmatsuo/repo-automation-bots/pull/14.diff')
.reply(200, diffResponse);
await probot.receive({
name: 'pull_request',
payload,
id: 'abc123',
});
sinon.assert.calledOnce(getApiLabelsStub);
sinon.assert.calledOnce(getSnippetsStub);
requests.done();
diffRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'repo-automation-bots',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
});
describe('responds to issue', () => {
it('quits early because issue title does not contain the command', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const payload = require(resolve(fixturesPath, './issue_event_no_scan'));
await probot.receive({
name: 'issues',
payload,
id: 'abc123',
});
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'python-docs-samples',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('reports failure upon download failure', async () => {
const payload = require(resolve(fixturesPath, './issue_event'));
const requests = nock('https://api.github.com')
.patch('/repos/tmatsuo/python-docs-samples/issues/10', body => {
snapshot(body);
return true;
})
.reply(200);
const tarBallRequests = nock('https://github.com')
.get('/tmatsuo/python-docs-samples/tarball/master')
.reply(403, 'Error');
await probot.receive({
name: 'issues',
payload,
id: 'abc123',
});
requests.done();
tarBallRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'python-docs-samples',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
it('reports the scan result', async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const payload = require(resolve(fixturesPath, './issue_event'));
const requests = nock('https://api.github.com')
.patch('/repos/tmatsuo/python-docs-samples/issues/10', body => {
snapshot(body);
return true;
})
.reply(200);
const tarBallRequests = nock('https://github.com')
.get('/tmatsuo/python-docs-samples/tarball/master')
.reply(200, tarBall, {
'Content-Type': 'application/tar+gzip',
});
await probot.receive({
name: 'issues',
payload,
id: 'abc123',
});
requests.done();
tarBallRequests.done();
sinon.assert.calledOnceWithExactly(
getConfigStub,
sinon.match.instanceOf(ProbotOctokit),
'tmatsuo',
'python-docs-samples',
CONFIGURATION_FILE_PATH,
{schema: schema}
);
});
});
}); | the_stack |
import spawnAsync from '@expo/spawn-async';
import chalk from 'chalk';
import fs from 'fs-extra';
import inquirer from 'inquirer';
import path from 'path';
import readline from 'readline';
import * as Directories from '../Directories';
import * as Packages from '../Packages';
import * as ProjectVersions from '../ProjectVersions';
type ActionOptions = {
sdkVersion: string;
packages?: string;
};
type Package = {
name: string;
sourceDir: string;
buildDirRelative: string;
};
// There are a few packages that we want to exclude from shell app builds; they don't follow any
// easy pattern so we just keep track of them manually here.
export const EXCLUDED_PACKAGE_SLUGS = [
'expo-dev-menu',
'expo-dev-menu-interface',
'expo-module-template',
'unimodules-test-core',
'unimodules-core',
'unimodules-react-native-adapter',
];
const EXPO_ROOT_DIR = Directories.getExpoRepositoryRootDir();
const ANDROID_DIR = Directories.getAndroidDir();
const REACT_ANDROID_PKG = {
name: 'ReactAndroid',
sourceDir: path.join(ANDROID_DIR, 'ReactAndroid'),
buildDirRelative: path.join('com', 'facebook', 'react'),
};
const EXPOVIEW_PKG = {
name: 'expoview',
sourceDir: path.join(ANDROID_DIR, 'expoview'),
buildDirRelative: path.join('host', 'exp', 'exponent', 'expoview'),
};
async function _findUnimodules(pkgDir: string): Promise<Package[]> {
const unimodules: Package[] = [];
const packages = await Packages.getListOfPackagesAsync();
for (const pkg of packages) {
if (!pkg.isSupportedOnPlatform('android') || !pkg.androidPackageName) continue;
unimodules.push({
name: pkg.packageSlug,
sourceDir: path.join(pkg.path, pkg.androidSubdirectory),
buildDirRelative: `${pkg.androidPackageName.replace(/\./g, '/')}/${pkg.packageSlug}`,
});
}
return unimodules;
}
async function _isPackageUpToDate(sourceDir: string, buildDir: string): Promise<boolean> {
try {
const sourceCommits = await _gitLogAsync(sourceDir);
const buildCommits = await _gitLogAsync(buildDir);
const latestSourceCommitSha = sourceCommits.lines[0].split(' ')[0];
const latestBuildCommitSha = buildCommits.lines[0].split(' ')[0];
// throws if source commit is not an ancestor of build commit
await spawnAsync(
'git',
['merge-base', '--is-ancestor', latestSourceCommitSha, latestBuildCommitSha],
{
cwd: EXPO_ROOT_DIR,
}
);
return true;
} catch (e) {
return false;
}
}
async function _gitLogAsync(path: string): Promise<{ lines: string[] }> {
const child = await spawnAsync('git', ['log', `--pretty=oneline`, '--', path], {
stdio: 'pipe',
cwd: EXPO_ROOT_DIR,
});
return {
lines: child.stdout
.trim()
.split(/\r?\n/g)
.filter((a) => a),
};
}
async function _getSuggestedPackagesToBuild(packages: Package[]): Promise<string[]> {
let packagesToBuild: string[] = [];
for (const pkg of packages) {
const isUpToDate = await _isPackageUpToDate(
pkg.sourceDir,
path.join(EXPO_ROOT_DIR, 'android', 'maven', pkg.buildDirRelative)
);
if (!isUpToDate) {
packagesToBuild.push(pkg.name);
}
}
return packagesToBuild;
}
async function _regexFileAsync(
filename: string,
regex: RegExp | string,
replace: string
): Promise<void> {
let file = await fs.readFile(filename);
let fileString = file.toString();
await fs.writeFile(filename, fileString.replace(regex, replace));
}
let savedFiles = {};
async function _stashFilesAsync(filenames: string[]): Promise<void> {
for (const filename of filenames) {
let file = await fs.readFile(filename);
savedFiles[filename] = file.toString();
}
}
async function _restoreFilesAsync(): Promise<void> {
for (const filename in savedFiles) {
await fs.writeFile(filename, savedFiles[filename]);
delete savedFiles[filename];
}
}
async function _commentWhenDistributing(filenames: string[]): Promise<void> {
for (const filename of filenames) {
await _regexFileAsync(
filename,
/\/\/ WHEN_DISTRIBUTING_REMOVE_FROM_HERE/g,
'/* WHEN_DISTRIBUTING_REMOVE_FROM_HERE'
);
await _regexFileAsync(
filename,
/\/\ WHEN_DISTRIBUTING_REMOVE_TO_HERE/g,
'WHEN_DISTRIBUTING_REMOVE_TO_HERE */'
);
}
}
async function _uncommentWhenDistributing(filenames: string[]): Promise<void> {
for (const filename of filenames) {
await _regexFileAsync(filename, '/* UNCOMMENT WHEN DISTRIBUTING', '');
await _regexFileAsync(filename, 'END UNCOMMENT WHEN DISTRIBUTING */', '');
}
}
async function _updateExpoViewAsync(packages: Package[], sdkVersion: string): Promise<number> {
let appBuildGradle = path.join(ANDROID_DIR, 'app', 'build.gradle');
let rootBuildGradle = path.join(ANDROID_DIR, 'build.gradle');
let expoViewBuildGradle = path.join(ANDROID_DIR, 'expoview', 'build.gradle');
const settingsGradle = path.join(ANDROID_DIR, 'settings.gradle');
const constantsJava = path.join(
ANDROID_DIR,
'expoview/src/main/java/host/exp/exponent/Constants.java'
);
const multipleVersionReactNativeActivity = path.join(
ANDROID_DIR,
'expoview/src/versioned/java/host/exp/exponent/experience/MultipleVersionReactNativeActivity.java'
);
// Modify permanently
await _regexFileAsync(expoViewBuildGradle, /version = '[\d.]+'/, `version = '${sdkVersion}'`);
await _regexFileAsync(
expoViewBuildGradle,
/api 'com.facebook.react:react-native:[\d.]+'/,
`api 'com.facebook.react:react-native:${sdkVersion}'`
);
await _regexFileAsync(
path.join(ANDROID_DIR, 'ReactAndroid', 'release.gradle'),
/version = '[\d.]+'/,
`version = '${sdkVersion}'`
);
await _regexFileAsync(
path.join(ANDROID_DIR, 'app', 'build.gradle'),
/host.exp.exponent:expoview:[\d.]+/,
`host.exp.exponent:expoview:${sdkVersion}`
);
await _stashFilesAsync([
appBuildGradle,
rootBuildGradle,
expoViewBuildGradle,
multipleVersionReactNativeActivity,
constantsJava,
settingsGradle,
]);
// Modify temporarily
await _regexFileAsync(
constantsJava,
/TEMPORARY_ABI_VERSION\s*=\s*null/,
`TEMPORARY_ABI_VERSION = "${sdkVersion}"`
);
await _uncommentWhenDistributing([appBuildGradle, expoViewBuildGradle]);
await _commentWhenDistributing([
constantsJava,
rootBuildGradle,
expoViewBuildGradle,
multipleVersionReactNativeActivity,
]);
// Clear maven local so that we don't end up with multiple versions
console.log(' ❌ Clearing old package versions...');
for (const pkg of packages) {
await fs.remove(path.join(process.env.HOME!, '.m2', 'repository', pkg.buildDirRelative));
await fs.remove(path.join(ANDROID_DIR, 'maven', pkg.buildDirRelative));
await fs.remove(path.join(pkg.sourceDir, 'build'));
}
// hacky workaround for weird issue where some packages need to be built twice after cleaning
// in order to have .so libs included in the aar
const reactAndroidIndex = packages.findIndex((pkg) => pkg.name === REACT_ANDROID_PKG.name);
if (reactAndroidIndex > -1) {
packages.splice(reactAndroidIndex, 0, REACT_ANDROID_PKG);
}
const expoviewIndex = packages.findIndex((pkg) => pkg.name === EXPOVIEW_PKG.name);
if (expoviewIndex > -1) {
packages.splice(expoviewIndex, 0, EXPOVIEW_PKG);
}
let failedPackages: string[] = [];
for (const pkg of packages) {
process.stdout.write(` 🛠 Building ${pkg.name}...`);
try {
await spawnAsync('./gradlew', [`:${pkg.name}:uploadArchives`], {
cwd: ANDROID_DIR,
});
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0);
process.stdout.write(` ✅ Finished building ${pkg.name}\n`);
} catch (e) {
if (
e.status === 130 ||
e.signal === 'SIGINT' ||
e.status === 137 ||
e.signal === 'SIGKILL' ||
e.status === 143 ||
e.signal === 'SIGTERM'
) {
throw e;
} else {
failedPackages.push(pkg.name);
readline.clearLine(process.stdout, 0);
readline.cursorTo(process.stdout, 0);
process.stdout.write(` ❌ Failed to build ${pkg.name}:\n`);
console.error(chalk.red(e.message));
console.error(chalk.red(e.stderr));
}
}
}
await _restoreFilesAsync();
console.log(' 🚚 Copying newly built packages...');
await fs.mkdirs(path.join(ANDROID_DIR, 'maven/com/facebook'));
await fs.mkdirs(path.join(ANDROID_DIR, 'maven/host/exp/exponent'));
await fs.mkdirs(path.join(ANDROID_DIR, 'maven/org/unimodules'));
for (const pkg of packages) {
if (failedPackages.includes(pkg.name)) {
continue;
}
await fs.copy(
path.join(process.env.HOME!, '.m2', 'repository', pkg.buildDirRelative),
path.join(ANDROID_DIR, 'maven', pkg.buildDirRelative)
);
}
if (failedPackages.length) {
console.log(' ❌ The following packages failed to build:');
console.log(failedPackages);
console.log(
`You will need to fix the compilation errors show in the logs above and then run \`et abp -s ${sdkVersion} -p ${failedPackages.join(
','
)}\``
);
}
return failedPackages.length;
}
async function action(options: ActionOptions) {
process.on('SIGINT', _exitHandler);
process.on('SIGTERM', _exitHandler);
const detachableUniversalModules = (
await _findUnimodules(path.join(EXPO_ROOT_DIR, 'packages'))
).filter((unimodule) => !EXCLUDED_PACKAGE_SLUGS.includes(unimodule.name));
// packages must stay in this order --
// ReactAndroid MUST be first and expoview MUST be last
const packages: Package[] = [REACT_ANDROID_PKG, ...detachableUniversalModules, EXPOVIEW_PKG];
let packagesToBuild: string[] = [];
const expoviewBuildGradle = await fs.readFile(path.join(ANDROID_DIR, 'expoview', 'build.gradle'));
const match = expoviewBuildGradle
.toString()
.match(/api 'com.facebook.react:react-native:([\d.]+)'/);
if (!match || !match[1]) {
throw new Error(
'Could not find SDK version in android/expoview/build.gradle: unexpected format'
);
}
if (match[1] !== options.sdkVersion) {
console.log(
" 🔍 It looks like you're adding a new SDK version. Ignoring the `--packages` option and rebuilding all packages..."
);
packagesToBuild = packages.map((pkg) => pkg.name);
} else if (options.packages) {
if (options.packages === 'all') {
packagesToBuild = packages.map((pkg) => pkg.name);
} else if (options.packages === 'suggested') {
console.log(' 🔍 Gathering data about packages...');
packagesToBuild = await _getSuggestedPackagesToBuild(packages);
} else {
const packageNames = options.packages.split(',');
packagesToBuild = packages
.map((pkg) => pkg.name)
.filter((pkgName) => packageNames.includes(pkgName));
}
console.log(' 🛠 Rebuilding the following packages:');
console.log(packagesToBuild);
} else {
// gather suggested package data and then show prompts
console.log(' 🔍 Gathering data...');
packagesToBuild = await _getSuggestedPackagesToBuild(packages);
console.log(' 🕵️ It appears that the following packages need to be rebuilt:');
console.log(packagesToBuild);
const { option } = await inquirer.prompt<{ option: string }>([
{
type: 'list',
name: 'option',
message: 'What would you like to do?',
choices: [
{ value: 'suggested', name: 'Build the suggested packages only' },
{ value: 'all', name: 'Build all packages' },
{ value: 'choose', name: 'Choose packages manually' },
],
},
]);
if (option === 'all') {
packagesToBuild = packages.map((pkg) => pkg.name);
} else if (option === 'choose') {
const result = await inquirer.prompt<{ packagesToBuild: string[] }>([
{
type: 'checkbox',
name: 'packagesToBuild',
message: 'Choose which packages to build\n ● selected ○ unselected\n',
choices: packages.map((pkg) => pkg.name),
default: packagesToBuild,
pageSize: Math.min(packages.length, (process.stdout.rows || 100) - 2),
},
]);
packagesToBuild = result.packagesToBuild;
}
}
try {
const failedPackagesCount = await _updateExpoViewAsync(
packages.filter((pkg) => packagesToBuild.includes(pkg.name)),
options.sdkVersion
);
if (failedPackagesCount > 0) {
process.exitCode = 1;
}
} catch (e) {
await _exitHandler();
throw e;
}
}
async function _exitHandler(): Promise<void> {
if (Object.keys(savedFiles).length) {
console.log('Exited early, cleaning up...');
await _restoreFilesAsync();
}
}
export default (program: any) => {
program
.command('android-build-packages')
.alias('abp')
.description('Builds all Android AAR packages for Turtle')
.option('-s, --sdkVersion [string]', '[optional] SDK version')
.option(
'-p, --packages [string]',
'[optional] packages to build. May be `all`, `suggested`, or a comma-separate list of package names.'
)
.asyncAction(async (options: Partial<ActionOptions>) => {
const sdkVersion =
options.sdkVersion ?? (await ProjectVersions.getNewestSDKVersionAsync('android'));
if (!sdkVersion) {
throw new Error('Could not infer SDK version, please run with `--sdkVersion SDK_VERSION`');
}
await action({ ...options, sdkVersion });
});
}; | the_stack |
import React from 'react';
import { mount, ReactWrapper } from 'enzyme';
import { RefObject } from '@devextreme-generator/declarations';
import { titleize } from '../../../../../core/utils/inflector';
import {
ScrollDirection,
} from '../../utils/scroll_direction';
import {
ScrollableSimulated as Scrollable,
ScrollableSimulated,
viewFunction,
} from '../simulated';
import {
SCROLLABLE_CONTAINER_CLASS,
SCROLLABLE_CONTENT_CLASS,
SCROLLVIEW_BOTTOM_POCKET_CLASS,
SCROLLVIEW_CONTENT_CLASS,
SCROLLVIEW_TOP_POCKET_CLASS,
} from '../../common/consts';
import { Scrollbar, ScrollbarPropsType } from '../../scrollbar/scrollbar';
import { ScrollableSimulatedProps } from '../../common/simulated_strategy_props';
import { AnimatedScrollbar } from '../../scrollbar/animated_scrollbar';
jest.mock('../../../load_indicator', () => ({ LoadIndicator: React.forwardRef(() => null) }));
jest.mock('../../internal/load_panel', () => ({ ScrollViewLoadPanel: React.forwardRef(() => null) }));
const TOP_POCKET_HEIGHT = 80;
const BOTTOM_POCKET_HEIGHT = 55;
interface Mock extends jest.Mock {}
class ScrollableTestHelper {
options: Partial<ScrollableSimulatedProps & ScrollbarPropsType & { overflow: 'hidden' | 'visible' }>;
viewModel: ScrollableSimulated;
scrollable: any;
isVertical: boolean;
isHorizontal: boolean;
isBoth: boolean;
scrollBarHandlers?: { name: string }[];
actionHandlers: { [key: string]: any };
constructor(props: Partial<ScrollableSimulatedProps & ScrollbarPropsType & { overflow: 'hidden' | 'visible' }>) {
this.options = props;
this.actionHandlers = this.getActionHandlers(this.options);
this.viewModel = new Scrollable({
onStart: this.actionHandlers.onStart,
onScroll: this.actionHandlers.onScroll,
onUpdated: this.actionHandlers.onUpdated,
onEnd: this.actionHandlers.onEnd,
onPullDown: this.actionHandlers.onPullDown,
onReachBottom: this.actionHandlers.onReachBottom,
onBounce: this.actionHandlers.onBounce,
onVisibilityChange: this.actionHandlers.onVisibilityChange,
needRenderScrollbars: true,
...this.options,
});
this.viewModel.scrollableRef = React.createRef() as RefObject<HTMLDivElement>;
this.viewModel.containerRef = React.createRef() as RefObject<HTMLDivElement>;
this.viewModel.contentRef = React.createRef() as RefObject<HTMLDivElement>;
this.viewModel.wrapperRef = React.createRef() as RefObject<HTMLDivElement>;
this.viewModel.topPocketRef = React.createRef() as RefObject<HTMLDivElement>;
this.viewModel.bottomPocketRef = React.createRef() as RefObject<HTMLDivElement>;
this.viewModel.vScrollbarRef = React.createRef() as RefObject<AnimatedScrollbar>;
this.viewModel.hScrollbarRef = React.createRef() as RefObject<AnimatedScrollbar>;
const { isVertical, isHorizontal, isBoth } = new ScrollDirection(this.options.direction);
this.isVertical = isVertical;
this.isHorizontal = isHorizontal;
this.isBoth = isBoth;
this.scrollable = mount(viewFunction(this.viewModel));
this.viewModel.scrollableRef.current = this.scrollable.getDOMNode();
this.viewModel.containerRef.current = this.getContainerElement();
this.viewModel.contentRef.current = this.getContentElement();
const { contentSize = 200, containerSize = 100, overflow = 'hidden' } = this.options;
let contentHeight = contentSize;
if (this.options.needScrollViewContentWrapper) {
this.viewModel.scrollViewContentRef = React.createRef() as RefObject<HTMLDivElement>;
this.viewModel.scrollViewContentRef.current = this.getScrollViewContentElement();
}
if (this.options.forceGeneratePockets) {
if (this.options.pullDownEnabled) {
contentHeight += TOP_POCKET_HEIGHT;
this.viewModel.topPocketRef.current = this.getTopPocketElement();
Object.defineProperties(this.viewModel.topPocketRef.current, {
clientWidth: { configurable: true, get() { return 100; } },
clientHeight: { configurable: true, get() { return TOP_POCKET_HEIGHT; } },
});
}
if (this.options.reachBottomEnabled) {
contentHeight += BOTTOM_POCKET_HEIGHT;
this.viewModel.bottomPocketRef.current = this.getBottomPocketElement();
Object.defineProperties(this.viewModel.bottomPocketRef.current, {
clientWidth: { configurable: true, get() { return 100; } },
clientHeight: { configurable: true, get() { return BOTTOM_POCKET_HEIGHT; } },
});
}
}
this.viewModel.containerRef.current.scrollTop = 0;
this.viewModel.containerRef.current.scrollLeft = 0;
this.initStyles(this.viewModel.containerRef.current,
{ width: containerSize, height: containerSize },
{ width: contentSize, height: contentHeight });
this.initStyles(this.viewModel.contentRef.current,
{ width: contentSize, height: contentHeight },
{ width: contentSize, height: contentHeight }, overflow);
this.initStyles(this.viewModel.scrollableRef.current!,
{ width: containerSize, height: containerSize },
{ width: contentSize, height: contentHeight });
this.viewModel.updateElementDimensions();
}
// eslint-disable-next-line class-methods-use-this
initStyles(
element: HTMLDivElement,
size: { width: number; height: number },
scrollSize: { width: number; height: number },
overflow?: string,
): HTMLDivElement {
const el = element;
Object.defineProperties(el, {
offsetHeight: {
get() { return size.height || 0; },
},
offsetWidth: {
get() { return size.width || 0; },
},
scrollHeight: {
configurable: true,
get() { return scrollSize.height || 0; },
},
scrollWidth: {
configurable: true,
get() { return scrollSize.width || 0; },
},
clientWidth: {
configurable: true,
get() { return size.width || 0; },
},
clientHeight: {
configurable: true,
get() { return size.height || 0; },
},
});
['width', 'height'].forEach((prop) => {
el.style[prop] = `${size[prop]}px`;
});
['outerWidth', 'outerHeight'].forEach((prop) => {
el.style[prop] = `${size[`outer${titleize(prop)}`]}px`;
});
if (overflow) {
['overflowX', 'overflowY'].forEach((prop) => {
el.style[prop] = overflow;
});
}
el.getBoundingClientRect = () => ({ width: size.width, height: size.height } as DOMRect);
return el;
}
getScrollable(): ReactWrapper<ScrollableSimulated> {
return this.scrollable;
}
getContainerElement(): HTMLDivElement {
return this.scrollable.find(`.${SCROLLABLE_CONTAINER_CLASS}`).getDOMNode();
}
getContentElement(): HTMLDivElement {
return this.scrollable.find(`.${SCROLLABLE_CONTENT_CLASS}`).getDOMNode();
}
getScrollViewContentElement(): HTMLDivElement {
return this.scrollable.find(`.${SCROLLVIEW_CONTENT_CLASS}`).getDOMNode();
}
getTopPocketElement(): HTMLDivElement {
return this.scrollable.find(`.${SCROLLVIEW_TOP_POCKET_CLASS}`).getDOMNode();
}
getBottomPocketElement(): HTMLDivElement {
return this.scrollable.find(`.${SCROLLVIEW_BOTTOM_POCKET_CLASS}`).getDOMNode();
}
getAnimatedScrollbars(): any {
return this.scrollable.find(AnimatedScrollbar);
}
getScrollbars(): any {
return this.scrollable.find(Scrollbar);
}
getVScrollbar(): AnimatedScrollbar {
return this.viewModel.vScrollbarRef.current!;
}
getHScrollbar(): AnimatedScrollbar {
return this.viewModel.hScrollbarRef.current!;
}
initScrollbarSettings(additionalProps:
{ [key: string]: any } = { props: {} }): void {
const { vScrollLocation = -50, hScrollLocation = -50, ...restProps } = additionalProps.props;
const initSettings = (animatedScrollbars, scrollbars, index) => {
const animatedScrollbar = animatedScrollbars.at(index).instance();
const scrollbar = scrollbars.at(index).instance();
if (scrollbar.props.direction === 'vertical') {
restProps.scrollLocation = vScrollLocation;
scrollbar.prevScrollLocation = vScrollLocation;
}
if (scrollbar.props.direction === 'horizontal') {
restProps.scrollLocation = hScrollLocation;
scrollbar.prevScrollLocation = hScrollLocation;
}
scrollbar.scrollbarRef = React.createRef();
scrollbar.scrollbarRef.current = scrollbars.at(index).getDOMNode();
scrollbar.thumbRef = React.createRef();
scrollbar.thumbRef.current = scrollbars.at(index).find('.dx-scrollable-scroll').getDOMNode();
Object.assign(animatedScrollbar, {
props: {
...animatedScrollbar.props,
...{
contentSize: 200,
containerSize: 100,
minOffset: 0,
maxOffset: -100,
bottomPocketSize: 0,
scrollLocationChange:
animatedScrollbar.props.scrollLocationChange.bind(this.viewModel),
...restProps,
},
},
});
Object.assign(scrollbar, {
props: {
...scrollbar.props,
...{
contentSize: 200,
containerSize: 100,
minOffset: 0,
maxOffset: -100,
scrollLocationChange:
scrollbar.props.scrollLocationChange.bind(this.viewModel),
...restProps,
},
},
});
animatedScrollbar.scrollbarRef = {
current: scrollbar,
};
return animatedScrollbar;
};
const animatedScrollbars = this.getAnimatedScrollbars();
const scrollbars = this.getScrollbars();
if (this.isBoth) {
this.viewModel.hScrollbarRef.current = initSettings(animatedScrollbars, scrollbars, 0);
this.viewModel.vScrollbarRef.current = initSettings(animatedScrollbars, scrollbars, 1);
} else if (this.isVertical) {
this.viewModel.vScrollbarRef.current = initSettings(animatedScrollbars, scrollbars, 0);
} else if (this.isHorizontal) {
this.viewModel.hScrollbarRef.current = initSettings(animatedScrollbars, scrollbars, 0);
}
}
initScrollbarHandlerMocks(): void {
this.scrollBarHandlers = [
{ name: 'init' },
{ name: 'start' },
{ name: 'end' },
{ name: 'cancel' },
{ name: 'stop' },
{ name: 'move' },
{ name: 'release' }];
this.scrollBarHandlers.forEach(({ name }) => {
this[`${name}VScrollbarHandlerMock`] = jest.fn();
this[`${name}HScrollbarHandlerMock`] = jest.fn();
if (this.isVertical) {
this.getVScrollbar()[`${name}Handler`] = this[`${name}VScrollbarHandlerMock`];
}
if (this.isHorizontal) {
this.getHScrollbar()[`${name}Handler`] = this[`${name}HScrollbarHandlerMock`];
}
});
}
changeScrollbarMethod(method: string, mock: Mock): void {
if (this.isVertical) {
this.getVScrollbar()[method] = mock;
}
if (this.isHorizontal) {
this.getHScrollbar()[method] = mock;
}
}
initContainerPosition({ top, left }: { top: number; left: number }): void {
this.viewModel.containerRef.current!.scrollTop = top;
this.viewModel.containerRef.current!.scrollLeft = left;
this.viewModel.vScrollLocation = -top;
this.viewModel.hScrollLocation = -left;
}
checkContainerPosition(jestExpect: (any) => any,
expectedPosition: { top: number; left: number }): void {
const { scrollTop, scrollLeft } = this.viewModel.containerRef.current!;
jestExpect(scrollTop).toEqual(expectedPosition.top);
jestExpect(scrollLeft).toEqual(expectedPosition.left);
}
checkScrollbarEventHandlerCalls(jestExpect: (any) => any,
direction: 'vertical' | 'horizontal',
expectedHandlers: string[],
expectedArgs: (boolean | number | { [key: string]: any })[][]): void {
const prefix = direction === 'vertical' ? 'V' : 'H';
this.scrollBarHandlers?.forEach((handler) => {
const indexOf = expectedHandlers.indexOf(handler.name);
if (indexOf !== -1 && this[`is${titleize(direction)}`]) {
jestExpect(this[`${handler.name}${prefix}ScrollbarHandlerMock`]).toBeCalledTimes(1);
jestExpect(this[`${handler.name}${prefix}ScrollbarHandlerMock`].mock.calls).toEqual([expectedArgs[indexOf]]);
} else {
jestExpect(this[`${handler.name}${prefix}ScrollbarHandlerMock`]).toBeCalledTimes(0);
}
});
}
checkActionHandlerCalls(jestExpect: (any) => any,
expectedHandlers: string[],
expectedArgs: ({ [key: string]: any })): void {
Object.keys(this.actionHandlers).forEach((key) => {
const indexOf = expectedHandlers.indexOf(key);
if (indexOf !== -1) {
jestExpect(this.actionHandlers[key]).toBeCalledTimes(1);
jestExpect(this.actionHandlers[key]).toHaveBeenCalledWith(expectedArgs[indexOf][0]);
} else if (this.actionHandlers[key]) {
jestExpect(this.actionHandlers[key]).toBeCalledTimes(0);
} else {
jestExpect(this.actionHandlers[key]).toEqual(undefined);
}
});
}
// eslint-disable-next-line class-methods-use-this
getActionHandlers(
props: Pick<ScrollableSimulatedProps, 'onStart' | 'onScroll' | 'onUpdated' | 'onEnd' | 'onPullDown' | 'onReachBottom' | 'onBounce' | 'onVisibilityChange'>,
): { [T in 'onStart' | 'onScroll' | 'onUpdated' | 'onEnd' | 'onPullDown' | 'onReachBottom' | 'onBounce' | 'onVisibilityChange']: any } {
const actionHandlers = {
onStart: jest.fn(),
onScroll: jest.fn(),
onUpdated: jest.fn(),
onEnd: jest.fn(),
onPullDown: jest.fn(),
onReachBottom: jest.fn(),
onBounce: jest.fn(),
onVisibilityChange: jest.fn(),
};
Object.keys(actionHandlers).forEach((key) => {
// eslint-disable-next-line no-prototype-builtins
if (props.hasOwnProperty(key)) {
actionHandlers[key] = props[key];
}
});
return actionHandlers;
}
}
export { ScrollableTestHelper }; | the_stack |
* topic返回信息展示字段
*/
export interface TopicSet {
/**
* 主题的 ID。
注意:此字段可能返回 null,表示取不到有效值。
*/
TopicId: string
/**
* 主题名称。
注意:此字段可能返回 null,表示取不到有效值。
*/
TopicName: string
/**
* 消息在主题中最长存活时间,从发送到该主题开始经过此参数指定的时间后,不论消息是否被成功推送给用户都将被删除,单位为秒。固定为一天(86400秒),该属性不能修改。
注意:此字段可能返回 null,表示取不到有效值。
*/
MsgRetentionSeconds: number
/**
* 消息最大长度。取值范围1024 - 1048576Byte(即1 - 1024K),默认值为65536。
注意:此字段可能返回 null,表示取不到有效值。
*/
MaxMsgSize: number
/**
* 每秒钟发布消息的条数。
注意:此字段可能返回 null,表示取不到有效值。
*/
Qps: number
/**
* 描述用户创建订阅时选择的过滤策略:
FilterType = 1表示用户使用 FilterTag 标签过滤;
FilterType = 2表示用户使用 BindingKey 过滤。
注意:此字段可能返回 null,表示取不到有效值。
*/
FilterType: number
/**
* 主题的创建时间。返回 Unix 时间戳,精确到秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
CreateTime: number
/**
* 最后一次修改主题属性的时间。返回 Unix 时间戳,精确到秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
LastModifyTime: number
/**
* 当前该主题中消息数目(消息堆积数)。
注意:此字段可能返回 null,表示取不到有效值。
*/
MsgCount: number
/**
* 创建者 Uin,CAM 鉴权 resource 由该字段组合而成。
注意:此字段可能返回 null,表示取不到有效值。
*/
CreateUin: number
/**
* 关联的标签。
注意:此字段可能返回 null,表示取不到有效值。
*/
Tags: Array<Tag>
/**
* 消息轨迹。true表示开启,false表示不开启。
注意:此字段可能返回 null,表示取不到有效值。
*/
Trace: boolean
}
/**
* RewindQueue请求参数结构体
*/
export interface RewindQueueRequest {
/**
* 队列名字,在单个地域同一帐号下唯一。队列名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
QueueName: string
/**
* 设定该时间,则(Batch)receiveMessage接口,会按照生产消息的先后顺序消费该时间戳以后的消息。
*/
StartConsumeTime: number
}
/**
* DescribeSubscriptionDetail请求参数结构体
*/
export interface DescribeSubscriptionDetailRequest {
/**
* 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
TopicName: string
/**
* 分页时本页获取主题列表的起始位置。如果填写了该值,必须也要填写 limit 。该值缺省时,后台取默认值 0
*/
Offset?: number
/**
* 分页时本页获取主题的个数,如果不传递该参数,则该参数默认为20,最大值为50。
*/
Limit?: number
/**
* 筛选参数,目前只支持SubscriptionName,且仅支持一个关键字。
*/
Filters?: Array<Filter>
}
/**
* ModifyQueueAttribute返回参数结构体
*/
export interface ModifyQueueAttributeResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateQueue请求参数结构体
*/
export interface CreateQueueRequest {
/**
* 队列名字,在单个地域同一帐号下唯一。队列名称是一个不超过 64 个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
QueueName: string
/**
* 最大堆积消息数。取值范围在公测期间为 1,000,000 - 10,000,000,正式上线后范围可达到 1000,000-1000,000,000。默认取值在公测期间为 10,000,000,正式上线后为 100,000,000。
*/
MaxMsgHeapNum?: number
/**
* 消息接收长轮询等待时间。取值范围 0-30 秒,默认值 0。
*/
PollingWaitSeconds?: number
/**
* 消息可见性超时。取值范围 1-43200 秒(即12小时内),默认值 30。
*/
VisibilityTimeout?: number
/**
* 消息最大长度。取值范围 1024-65536 Byte(即1-64K),默认值 65536。
*/
MaxMsgSize?: number
/**
* 消息保留周期。取值范围 60-1296000 秒(1min-15天),默认值 345600 (4 天)。
*/
MsgRetentionSeconds?: number
/**
* 队列是否开启回溯消息能力,该参数取值范围0-msgRetentionSeconds,即最大的回溯时间为消息在队列中的保留周期,0表示不开启。
*/
RewindSeconds?: number
/**
* 1 表示事务队列,0 表示普通队列
*/
Transaction?: number
/**
* 第一次回查间隔
*/
FirstQueryInterval?: number
/**
* 最大回查次数
*/
MaxQueryCount?: number
/**
* 死信队列名称
*/
DeadLetterQueueName?: string
/**
* 死信策略。0为消息被多次消费未删除,1为Time-To-Live过期
*/
Policy?: number
/**
* 最大接收次数 1-1000
*/
MaxReceiveCount?: number
/**
* policy为1时必选。最大未消费过期时间。范围300-43200,单位秒,需要小于消息最大保留时间msgRetentionSeconds
*/
MaxTimeToLive?: number
/**
* 是否开启消息轨迹追踪,当不设置字段时,默认为不开启,该字段为true表示开启,为false表示不开启
*/
Trace?: boolean
}
/**
* ModifySubscriptionAttribute返回参数结构体
*/
export interface ModifySubscriptionAttributeResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeadLetterPolicy
*/
export interface DeadLetterPolicy {
/**
* 死信队列名字。
注意:此字段可能返回 null,表示取不到有效值。
*/
DeadLetterQueueName: string
/**
* 死信队列。
注意:此字段可能返回 null,表示取不到有效值。
*/
DeadLetterQueue: string
/**
* 死信队列策略。
注意:此字段可能返回 null,表示取不到有效值。
*/
Policy: number
/**
* 最大未消费过期时间。Policy为1时必选。范围300-43200,单位秒,需要小于消息最大保留时间MsgRetentionSeconds。
注意:此字段可能返回 null,表示取不到有效值。
*/
MaxTimeToLive: number
/**
* 最大接收次数。
注意:此字段可能返回 null,表示取不到有效值。
*/
MaxReceiveCount: number
}
/**
* ModifyTopicAttribute返回参数结构体
*/
export interface ModifyTopicAttributeResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteSubscribe请求参数结构体
*/
export interface DeleteSubscribeRequest {
/**
* 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
TopicName: string
/**
* 订阅名字,在单个地域同一帐号的同一主题下唯一。订阅名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
SubscriptionName: string
}
/**
* DescribeSubscriptionDetail返回参数结构体
*/
export interface DescribeSubscriptionDetailResponse {
/**
* 总数
*/
TotalCount?: number
/**
* Subscription属性集合
注意:此字段可能返回 null,表示取不到有效值。
*/
SubscriptionSet?: Array<Subscription>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* CreateSubscribe请求参数结构体
*/
export interface CreateSubscribeRequest {
/**
* 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
TopicName: string
/**
* 订阅名字,在单个地域同一帐号的同一主题下唯一。订阅名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
SubscriptionName: string
/**
* 订阅的协议,目前支持两种协议:http、queue。使用http协议,用户需自己搭建接受消息的web server。使用queue,消息会自动推送到CMQ queue,用户可以并发地拉取消息。
*/
Protocol: string
/**
* 接收通知的Endpoint,根据协议Protocol区分:对于http,Endpoint必须以“`http://`”开头,host可以是域名或IP;对于Queue,则填QueueName。 请注意,目前推送服务不能推送到私有网络中,因此Endpoint填写为私有网络域名或地址将接收不到推送的消息,目前支持推送到公网和基础网络。
*/
Endpoint: string
/**
* 向Endpoint推送消息出现错误时,CMQ推送服务器的重试策略。取值有:1)BACKOFF_RETRY,退避重试。每隔一定时间重试一次,重试够一定次数后,就把该消息丢弃,继续推送下一条消息;2)EXPONENTIAL_DECAY_RETRY,指数衰退重试。每次重试的间隔是指数递增的,例如开始1s,后面是2s,4s,8s...由于Topic消息的周期是一天,所以最多重试一天就把消息丢弃。默认值是EXPONENTIAL_DECAY_RETRY。
*/
NotifyStrategy?: string
/**
* 消息正文。消息标签(用于消息过滤)。标签数量不能超过5个,每个标签不超过16个字符。与(Batch)PublishMessage的MsgTag参数配合使用,规则:1)如果FilterTag没有设置,则无论MsgTag是否有设置,订阅接收所有发布到Topic的消息;2)如果FilterTag数组有值,则只有数组中至少有一个值在MsgTag数组中也存在时(即FilterTag和MsgTag有交集),订阅才接收该发布到Topic的消息;3)如果FilterTag数组有值,但MsgTag没设置,则不接收任何发布到Topic的消息,可以认为是2)的一种特例,此时FilterTag和MsgTag没有交集。规则整体的设计思想是以订阅者的意愿为主。
*/
FilterTag?: Array<string>
/**
* BindingKey数量不超过5个, 每个BindingKey长度不超过64字节,该字段表示订阅接收消息的过滤策略,每个BindingKey最多含有15个“.”, 即最多16个词组。
*/
BindingKey?: Array<string>
/**
* 推送内容的格式。取值:1)JSON;2)SIMPLIFIED,即raw格式。如果Protocol是queue,则取值必须为SIMPLIFIED。如果Protocol是http,两个值均可以,默认值是JSON。
*/
NotifyContentFormat?: string
}
/**
* ClearQueue请求参数结构体
*/
export interface ClearQueueRequest {
/**
* 队列名字,在单个地域同一帐号下唯一。队列名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
QueueName: string
}
/**
* CreateTopic返回参数结构体
*/
export interface CreateTopicResponse {
/**
* TopicName
*/
TopicId?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ClearSubscriptionFilterTags返回参数结构体
*/
export interface ClearSubscriptionFilterTagsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* UnbindDeadLetter返回参数结构体
*/
export interface UnbindDeadLetterResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* TransactionPolicy
*/
export interface TransactionPolicy {
/**
* 第一次回查时间。
注意:此字段可能返回 null,表示取不到有效值。
*/
FirstQueryInterval: number
/**
* 最大查询次数。
注意:此字段可能返回 null,表示取不到有效值。
*/
MaxQueryCount: number
}
/**
* DescribeTopicDetail请求参数结构体
*/
export interface DescribeTopicDetailRequest {
/**
* 分页时本页获取队列列表的起始位置。如果填写了该值,必须也要填写 limit 。该值缺省时,后台取默认值 0。
*/
Offset?: number
/**
* 分页时本页获取队列的个数,如果不传递该参数,则该参数默认为20,最大值为50。
*/
Limit?: number
/**
* 目前只支持过滤TopicName , 且只能填一个过滤值。
*/
Filters?: Array<Filter>
/**
* 标签匹配。
*/
TagKey?: string
/**
* 精确匹配TopicName。
*/
TopicName?: string
}
/**
* DeleteTopic请求参数结构体
*/
export interface DeleteTopicRequest {
/**
* 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
TopicName: string
}
/**
* DescribeTopicDetail返回参数结构体
*/
export interface DescribeTopicDetailResponse {
/**
* 主题列表总数。
*/
TotalCount?: number
/**
* 主题详情列表。
*/
TopicSet?: Array<TopicSet>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeQueueDetail返回参数结构体
*/
export interface DescribeQueueDetailResponse {
/**
* 总队列数。
*/
TotalCount?: number
/**
* 队列详情列表。
*/
QueueSet?: Array<QueueSet>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* UnbindDeadLetter请求参数结构体
*/
export interface UnbindDeadLetterRequest {
/**
* 死信策略源队列名称,调用本接口会清空该队列的死信队列策略。
*/
QueueName: string
}
/**
* CreateTopic请求参数结构体
*/
export interface CreateTopicRequest {
/**
* 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
TopicName: string
/**
* 消息最大长度。取值范围 1024-65536 Byte(即1-64K),默认值 65536。
*/
MaxMsgSize?: number
/**
* 用于指定主题的消息匹配策略。1:表示标签匹配策略;2:表示路由匹配策略,默认值为标签匹配策略。
*/
FilterType?: number
/**
* 消息保存时间。取值范围60 - 86400 s(即1分钟 - 1天),默认值86400。
*/
MsgRetentionSeconds?: number
/**
* 是否开启消息轨迹标识,true表示开启,false表示不开启,不填表示不开启。
*/
Trace?: boolean
}
/**
* DeleteQueue请求参数结构体
*/
export interface DeleteQueueRequest {
/**
* 队列名字,在单个地域同一帐号下唯一。队列名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
QueueName: string
}
/**
* 过滤参数
*/
export interface Filter {
/**
* 过滤参数的名字
*/
Name?: string
/**
* 数值
*/
Values?: Array<string>
}
/**
* DescribeDeadLetterSourceQueues返回参数结构体
*/
export interface DescribeDeadLetterSourceQueuesResponse {
/**
* 满足本次条件的队列个数
*/
TotalCount?: number
/**
* 死信队列源队列
*/
QueueSet?: Array<DeadLetterSource>
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* RewindQueue返回参数结构体
*/
export interface RewindQueueResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifyTopicAttribute请求参数结构体
*/
export interface ModifyTopicAttributeRequest {
/**
* 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
TopicName: string
/**
* 消息最大长度。取值范围1024 - 65536 Byte(即1 - 64K),默认值65536。
*/
MaxMsgSize?: number
/**
* 消息保存时间。取值范围60 - 86400 s(即1分钟 - 1天),默认值86400。
*/
MsgRetentionSeconds?: number
/**
* 是否开启消息轨迹标识,true表示开启,false表示不开启,不填表示不开启。
*/
Trace?: boolean
}
/**
* DescribeQueueDetail请求参数结构体
*/
export interface DescribeQueueDetailRequest {
/**
* 分页时本页获取队列列表的起始位置。如果填写了该值,必须也要填写 limit 。该值缺省时,后台取默认值 0
*/
Offset?: number
/**
* 分页时本页获取队列的个数,如果不传递该参数,则该参数默认为20,最大值为50。
*/
Limit?: number
/**
* 筛选参数,目前支持QueueName筛选,且仅支持一个关键字
*/
Filters?: Array<Filter>
/**
* 标签搜索
*/
TagKey?: string
/**
* 精确匹配QueueName
*/
QueueName?: string
}
/**
* 批量queue属性信息
*/
export interface QueueSet {
/**
* 消息队列ID。
*/
QueueId: string
/**
* 消息队列名字。
*/
QueueName: string
/**
* 每秒钟生产消息条数的限制,消费消息的大小是该值的1.1倍。
注意:此字段可能返回 null,表示取不到有效值。
*/
Qps: number
/**
* 带宽限制。
注意:此字段可能返回 null,表示取不到有效值。
*/
Bps: number
/**
* 飞行消息最大保留时间。
注意:此字段可能返回 null,表示取不到有效值。
*/
MaxDelaySeconds: number
/**
* 最大堆积消息数。取值范围在公测期间为 1,000,000 - 10,000,000,正式上线后范围可达到 1000,000-1000,000,000。默认取值在公测期间为 10,000,000,正式上线后为 100,000,000。
注意:此字段可能返回 null,表示取不到有效值。
*/
MaxMsgHeapNum: number
/**
* 消息接收长轮询等待时间。取值范围0 - 30秒,默认值0。
注意:此字段可能返回 null,表示取不到有效值。
*/
PollingWaitSeconds: number
/**
* 消息保留周期。取值范围60-1296000秒(1min-15天),默认值345600秒(4 天)。
注意:此字段可能返回 null,表示取不到有效值。
*/
MsgRetentionSeconds: number
/**
* 消息可见性超时。取值范围1 - 43200秒(即12小时内),默认值30。
注意:此字段可能返回 null,表示取不到有效值。
*/
VisibilityTimeout: number
/**
* 消息最大长度。取值范围1024 - 1048576 Byte(即1K - 1024K),默认值65536。
注意:此字段可能返回 null,表示取不到有效值。
*/
MaxMsgSize: number
/**
* 回溯队列的消息回溯时间最大值,取值范围0 - 43200秒,0表示不开启消息回溯。
注意:此字段可能返回 null,表示取不到有效值。
*/
RewindSeconds: number
/**
* 队列的创建时间。返回 Unix 时间戳,精确到秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
CreateTime: number
/**
* 最后一次修改队列属性的时间。返回 Unix 时间戳,精确到秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
LastModifyTime: number
/**
* 在队列中处于 Active 状态(不处于被消费状态)的消息总数,为近似值。
注意:此字段可能返回 null,表示取不到有效值。
*/
ActiveMsgNum: number
/**
* 在队列中处于 Inactive 状态(正处于被消费状态)的消息总数,为近似值。
注意:此字段可能返回 null,表示取不到有效值。
*/
InactiveMsgNum: number
/**
* 延迟消息数。
注意:此字段可能返回 null,表示取不到有效值。
*/
DelayMsgNum: number
/**
* 已调用 DelMsg 接口删除,但还在回溯保留时间内的消息数量。
注意:此字段可能返回 null,表示取不到有效值。
*/
RewindMsgNum: number
/**
* 消息最小未消费时间,单位为秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
MinMsgTime: number
/**
* 事务消息队列。true表示是事务消息,false表示不是事务消息。
注意:此字段可能返回 null,表示取不到有效值。
*/
Transaction: boolean
/**
* 死信队列。
注意:此字段可能返回 null,表示取不到有效值。
*/
DeadLetterSource: Array<DeadLetterSource>
/**
* 死信队列策略。
注意:此字段可能返回 null,表示取不到有效值。
*/
DeadLetterPolicy: DeadLetterPolicy
/**
* 事务消息策略。
注意:此字段可能返回 null,表示取不到有效值。
*/
TransactionPolicy: TransactionPolicy
/**
* 创建者Uin。
注意:此字段可能返回 null,表示取不到有效值。
*/
CreateUin: number
/**
* 关联的标签。
注意:此字段可能返回 null,表示取不到有效值。
*/
Tags: Array<Tag>
/**
* 消息轨迹。true表示开启,false表示不开启。
注意:此字段可能返回 null,表示取不到有效值。
*/
Trace: boolean
}
/**
* DeleteTopic返回参数结构体
*/
export interface DeleteTopicResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ClearSubscriptionFilterTags请求参数结构体
*/
export interface ClearSubscriptionFilterTagsRequest {
/**
* 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
TopicName: string
/**
* 订阅名字,在单个地域同一帐号的同一主题下唯一。订阅名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
SubscriptionName: string
}
/**
* CreateQueue返回参数结构体
*/
export interface CreateQueueResponse {
/**
* 创建成功的queueId
*/
QueueId?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DeleteSubscribe返回参数结构体
*/
export interface DeleteSubscribeResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* DescribeDeadLetterSourceQueues请求参数结构体
*/
export interface DescribeDeadLetterSourceQueuesRequest {
/**
* 死信队列名称
*/
DeadLetterQueueName: string
/**
* 分页时本页获取主题列表的起始位置。如果填写了该值,必须也要填写 limit 。该值缺省时,后台取默认值 0。
*/
Limit?: number
/**
* 分页时本页获取主题的个数,如果不传递该参数,则该参数默认为20,最大值为50。
*/
Offset?: number
/**
* 过滤死信队列源队列名称,目前仅支持SourceQueueName过滤
*/
Filters?: Array<Filter>
}
/**
* 标签
*/
export interface Tag {
/**
* 标签Key
注意:此字段可能返回 null,表示取不到有效值。
*/
TagKey: string
/**
* 标签值
注意:此字段可能返回 null,表示取不到有效值。
*/
TagValue: string
}
/**
* DeadLetterSource
*/
export interface DeadLetterSource {
/**
* 消息队列ID。
注意:此字段可能返回 null,表示取不到有效值。
*/
QueueId: string
/**
* 消息队列名字。
注意:此字段可能返回 null,表示取不到有效值。
*/
QueueName: string
}
/**
* CreateSubscribe返回参数结构体
*/
export interface CreateSubscribeResponse {
/**
* SubscriptionId
*/
SubscriptionId?: string
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ClearQueue返回参数结构体
*/
export interface ClearQueueResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifySubscriptionAttribute请求参数结构体
*/
export interface ModifySubscriptionAttributeRequest {
/**
* 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
TopicName: string
/**
* 订阅名字,在单个地域同一帐号的同一主题下唯一。订阅名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
SubscriptionName: string
/**
* 向 Endpoint 推送消息出现错误时,CMQ 推送服务器的重试策略。取值如下:
(1)BACKOFF_RETRY,退避重试。每隔一定时间重试一次,重试够一定次数后,就把该消息丢弃,继续推送下一条消息。
(2)EXPONENTIAL_DECAY_RETRY,指数衰退重试。每次重试的间隔是指数递增的,例如开始1s,后面是2s,4s,8s···由于 Topic 消息的周期是一天,所以最多重试一天就把消息丢弃。默认值是 EXPONENTIAL_DECAY_RETRY。
*/
NotifyStrategy?: string
/**
* 推送内容的格式。取值:(1)JSON;(2)SIMPLIFIED,即 raw 格式。如果 Protocol 是 queue,则取值必须为 SIMPLIFIED。如果 Protocol 是 HTTP,两个值均可以,默认值是 JSON。
*/
NotifyContentFormat?: string
/**
* 消息正文。消息标签(用于消息过滤)。标签数量不能超过5个,每个标签不超过16个字符。与(Batch)PublishMessage的MsgTag参数配合使用,规则:1)如果FilterTag没有设置,则无论MsgTag是否有设置,订阅接收所有发布到Topic的消息;2)如果FilterTag数组有值,则只有数组中至少有一个值在MsgTag数组中也存在时(即FilterTag和MsgTag有交集),订阅才接收该发布到Topic的消息;3)如果FilterTag数组有值,但MsgTag没设置,则不接收任何发布到Topic的消息,可以认为是2)的一种特例,此时FilterTag和MsgTag没有交集。规则整体的设计思想是以订阅者的意愿为主。
*/
FilterTags?: Array<string>
/**
* BindingKey数量不超过5个, 每个BindingKey长度不超过64字节,该字段表示订阅接收消息的过滤策略,每个BindingKey最多含有15个“.”, 即最多16个词组。
*/
BindingKey?: Array<string>
}
/**
* 订阅返回参数
*/
export interface Subscription {
/**
* 订阅名字,在单个地域同一帐号的同一主题下唯一。订阅名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
注意:此字段可能返回 null,表示取不到有效值。
*/
SubscriptionName: string
/**
* 订阅 ID。订阅 ID 在拉取监控数据时会用到。
注意:此字段可能返回 null,表示取不到有效值。
*/
SubscriptionId: string
/**
* 订阅拥有者的 APPID。
注意:此字段可能返回 null,表示取不到有效值。
*/
TopicOwner: number
/**
* 该订阅待投递的消息数。
注意:此字段可能返回 null,表示取不到有效值。
*/
MsgCount: number
/**
* 最后一次修改订阅属性的时间。返回 Unix 时间戳,精确到秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
LastModifyTime: number
/**
* 订阅的创建时间。返回 Unix 时间戳,精确到秒。
注意:此字段可能返回 null,表示取不到有效值。
*/
CreateTime: number
/**
* 表示订阅接收消息的过滤策略。
注意:此字段可能返回 null,表示取不到有效值。
*/
BindingKey: Array<string>
/**
* 接收通知的 endpoint,根据协议 protocol 区分:对于 HTTP,endpoint 必须以http://开头,host 可以是域名或 IP;对于 queue,则填 queueName。
注意:此字段可能返回 null,表示取不到有效值。
*/
Endpoint: string
/**
* 描述用户创建订阅时选择的过滤策略:
filterType = 1表示用户使用 filterTag 标签过滤
filterType = 2表示用户使用 bindingKey 过滤。
注意:此字段可能返回 null,表示取不到有效值。
*/
FilterTags: Array<string>
/**
* 订阅的协议,目前支持两种协议:HTTP、queue。使用 HTTP 协议,用户需自己搭建接受消息的 Web Server。使用 queue,消息会自动推送到 CMQ queue,用户可以并发地拉取消息。
注意:此字段可能返回 null,表示取不到有效值。
*/
Protocol: string
/**
* 向 endpoint 推送消息出现错误时,CMQ 推送服务器的重试策略。取值有:
(1)BACKOFF_RETRY,退避重试。每隔一定时间重试一次,重试够一定次数后,就把该消息丢弃,继续推送下一条消息;
(2)EXPONENTIAL_DECAY_RETRY,指数衰退重试。每次重试的间隔是指数递增的,例如开始 1s,后面是 2s,4s,8s...由于 Topic 消息的周期是一天,所以最多重试一天就把消息丢弃。默认值是 EXPONENTIAL_DECAY_RETRY。
注意:此字段可能返回 null,表示取不到有效值。
*/
NotifyStrategy: string
/**
* 推送内容的格式。取值:(1)JSON;(2)SIMPLIFIED,即 raw 格式。如果 protocol 是 queue,则取值必须为 SIMPLIFIED。如果 protocol 是 HTTP,两个值均可以,默认值是 JSON。
注意:此字段可能返回 null,表示取不到有效值。
*/
NotifyContentFormat: string
}
/**
* DeleteQueue返回参数结构体
*/
export interface DeleteQueueResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string
}
/**
* ModifyQueueAttribute请求参数结构体
*/
export interface ModifyQueueAttributeRequest {
/**
* 队列名字,在单个地域同一帐号下唯一。队列名称是一个不超过 64 个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。
*/
QueueName: string
/**
* 最大堆积消息数。取值范围在公测期间为 1,000,000 - 10,000,000,正式上线后范围可达到 1000,000-1000,000,000。默认取值在公测期间为 10,000,000,正式上线后为 100,000,000。
*/
MaxMsgHeapNum?: number
/**
* 消息接收长轮询等待时间。取值范围 0-30 秒,默认值 0。
*/
PollingWaitSeconds?: number
/**
* 消息可见性超时。取值范围 1-43200 秒(即12小时内),默认值 30。
*/
VisibilityTimeout?: number
/**
* 消息最大长度。取值范围 1024-65536 Byte(即1-64K),默认值 65536。
*/
MaxMsgSize?: number
/**
* 消息保留周期。取值范围 60-1296000 秒(1min-15天),默认值 345600 (4 天)。
*/
MsgRetentionSeconds?: number
/**
* 消息最长回溯时间,取值范围0-msgRetentionSeconds,消息的最大回溯之间为消息在队列中的保存周期,0表示不开启消息回溯。
*/
RewindSeconds?: number
/**
* 第一次查询时间
*/
FirstQueryInterval?: number
/**
* 最大查询次数
*/
MaxQueryCount?: number
/**
* 死信队列名称
*/
DeadLetterQueueName?: string
/**
* MaxTimeToLivepolicy为1时必选。最大未消费过期时间。范围300-43200,单位秒,需要小于消息最大保留时间MsgRetentionSeconds
*/
MaxTimeToLive?: number
/**
* 最大接收次数
*/
MaxReceiveCount?: number
/**
* 死信队列策略
*/
Policy?: number
/**
* 是否开启消息轨迹标识,true表示开启,false表示不开启,不填表示不开启。
*/
Trace?: boolean
} | the_stack |
import {DanmakuManager} from "./danmaku/danmakuManager";
import {DanmakuItem} from "./danmaku/DanmakuItem";
import {EventBase} from "./eventBase";
declare function require(module: string);
declare const Hls: any;
const style = require('./player.css');
let DEBUG = false;
function log(info) {
if (DEBUG) {
console.log(info)
}
}
function createEle(tag: string, classname: string) {
let newEle = document.createElement(tag);
newEle.className = classname;
return newEle
}
export enum PlayerEvent {
play,
pause,
ready,
error,
timeupdate,
resize,
enterfullscreen,
exitfullscreen,
seeking,
seeked,
buffer,
sendDanmaku
}
export class Player extends EventBase {
containerEl: HTMLElement;
videoEl;
playerEl: HTMLElement;
danmakuManager: DanmakuManager;
controlLayer: ControlLayer;
fullscreenState: boolean;
duration: number;
touchMode: boolean;
isLive: boolean;
contextMenu: ContextMenu;
seekingTime: number = 0;
get currentTime() {
return this.videoEl.currentTime;
}
set currentTime(v) {
this.seeked(v);
}
get volume() {
return this.videoEl.volume
}
set volume(v) {
this.videoEl.volume = v
}
get isPlaying() {
return !this.videoEl.paused
}
constructor(container: HTMLElement, title = null, vid = null) {
super();
this.containerEl = container;
container.innerHTML = '<video webkit-playsinline preload="auto"></video>';
//this.videoEl=document.createElement('video');
//this.videoEl.outerHTML='<video webkit-playsinline></video>';
//this.videoEl.autoplay=true;
//this.videoEl.preload='auto';
//this.videoEl['webkitPlaysinline']=true;
this.videoEl = this.containerEl.querySelector('video');
this.controlLayer = new ControlLayer(this, title);
this.danmakuManager = new DanmakuManager(vid);
this.danmakuManager.init(this);
this.containerEl.appendChild(this.videoEl);
this.containerEl.appendChild(this.danmakuManager.canvas);
this.danmakuManager.resize();
this.containerEl.appendChild(this.controlLayer.element);
this.touchMode = !!document['createTouch'];
this.videoEl.addEventListener('play', function () {
this.dispatchEvent(PlayerEvent.ready)
}.bind(this));
this.videoEl.load();
this.videoEl.addEventListener('playing', function () {
this.dispatchEvent(PlayerEvent.play);
}.bind(this));
this.videoEl.addEventListener('pause', function () {
this.dispatchEvent(PlayerEvent.pause);
}.bind(this));
this.videoEl.addEventListener('error', function () {
this.dispatchEvent(PlayerEvent.error)
}.bind(this));
this.videoEl.addEventListener('seeked', function () {
this.dispatchEvent(PlayerEvent.seeked)
}.bind(this));
this.videoEl.addEventListener('timeupdate', e => {
this.dispatchEvent(PlayerEvent.timeupdate);
localStorage.setItem('lasttime:' + vid, this.videoEl.currentTime)
});
this.videoEl.addEventListener('loadedmetadata', () => {
this.duration = this.videoEl.duration;
this.dispatchEvent(PlayerEvent.resize);
let lasttime = localStorage.getItem('lasttime:' + vid);
if (lasttime) {
this.videoEl.currentTime = lasttime
}
});
window.addEventListener('resize', function () {
this.dispatchEvent(PlayerEvent.resize);
//PlayerEventBus.dispatchEvent('resize');
}.bind(this));
window.addEventListener('keypress', e => {
if (!(e.target['nodeName'] == 'TEXTAREA' || e.target['nodeName'] == 'INPUT')) {
e.preventDefault();
if (e.keyCode == 32) {
if (this.isPlaying) {
this.pause()
} else {
this.play();
}
}
}
});
window.addEventListener('keyup', e => {
if (!(e.target['nodeName'] == 'TEXTAREA' || e.target['nodeName'] == 'INPUT')) {
e.preventDefault();
if (e.keyCode == 37) {
this.seek(Math.max(0, this.currentTime - 15))
} else if (e.keyCode == 39) {
this.seek(Math.min(this.duration, this.currentTime + 15))
}
}
});
document.addEventListener("webkitfullscreenchange", () => {
if (document['webkitIsFullScreen'] === true) {
this.fullscreenState = true;
this.containerEl.classList.add('fullscreen');
setTimeout(() => {
this.videoEl.style.marginTop = (window.innerHeight - this.videoEl.offsetHeight) / 2 + 'px';
this.danmakuManager.resize();
}, 300);
} else {
this.fullscreenState = false;
this.containerEl.classList.remove('fullscreen');
this.videoEl.style.marginTop = null;
this.danmakuManager.resize();
}
});
this.containerEl.addEventListener('contextmenu', e => {
e.preventDefault();
if (this.contextMenu) {
this.contextMenu.dispose();
this.contextMenu = null;
}
this.contextMenu = new ContextMenu();
this.containerEl.appendChild(this.contextMenu.element);
this.contextMenu.element.style.left = e.offsetX + 'px';
this.contextMenu.element.style.top = e.offsetY + 'px';
this.contextMenu.addEventListener('CLICK', method => {
switch (method) {
case('pause'): {
this.pause();
break
}
case('togleGPU'): {
if (localStorage.getItem('useGPU') == 'true') {
localStorage.setItem('useGPU', 'false')
} else {
localStorage.setItem('useGPU', 'true')
}
location.reload()
}
}
this.contextMenu.dispose();
this.contextMenu = null;
});
});
window.addEventListener('click', e => {
if (this.contextMenu && e.button == 0) {
this.contextMenu.dispose();
this.contextMenu = null;
}
}, false);
setInterval(this.checkBufferState.bind(this), 250)
}
lastUpdateTime = -1;
buffering = false;
checkBufferState() {
if (this.videoEl.currentTime == this.lastUpdateTime && (!this.buffering)) {
this.buffering = true;
this.dispatchEvent(PlayerEvent.buffer)
} else if (this.videoEl.currentTime != this.lastUpdateTime && (this.buffering || this.isPlaying)) {
this.buffering = false;
this.dispatchEvent(PlayerEvent.play)
}
this.lastUpdateTime = this.videoEl.currentTime
}
initVideo(src: string) {
this.videoEl.src = src;
}
initHls(hlsUrl: string, isLive = true) {
if (!window['Hls']) {
console.log('Moe2Player requires hls.js to support http live streaming.');
return;
}
if (this.videoEl.canPlayType('application/vnd.apple.mpegurl')) {
this.videoEl.src = hlsUrl;
this.videoEl.addEventListener('loadedmetadata', () => {
})
} else {
if (Hls.isSupported()) {
const hls = new Hls();
hls.loadSource(hlsUrl);
hls.attachMedia(this.videoEl);
hls.on(Hls.Events.MANIFEST_PARSED, () => {
})
} else {
console.log('flv.js is not supported in current browser.');
}
}
this.isLive = isLive;
if (this.isLive) {
this.controlLayer.setliveMode()
}
}
initFlv(flvUrl: string) {
if (!window['flvjs']) {
console.log('Moe2Player requires flv.js to support live streaming.');
return;
}
const flvJS = window['flvjs'] as any;
if (flvJS.isSupported()) {
const sourceElement = this.videoEl;
const flvPlayer = flvJS.createPlayer({
type: 'flv',
url: flvUrl
});
flvPlayer.attachMediaElement(sourceElement);
flvPlayer.load();
this.isLive = true;
} else {
console.log('flv.js is not supported in current browser.');
}
}
loadDanmaku(src, type = 'bilibili') {
this.danmakuManager.loadDanmaku(src, type)
}
pushDanmaku(content, color = '#ffffff', type = 0, fontSize = 28) {
const time = this.videoEl.currentTime + 0.1;
const danmaku = new DanmakuItem(this.danmakuManager, content, time, type, color, fontSize);
this.danmakuManager.sendDanmaku(danmaku);
}
sendDanmaku(content, color = '#ffffff', type = 0, fontSize = 28) {
const time = this.videoEl.currentTime + 0.1;
this.dispatchEvent(PlayerEvent.sendDanmaku, {time, content, color, type, fontSize})
}
play() {
if (this.isLive) {
this.videoEl.currentTime = this.videoEl.seekable.end(0)
}
this.videoEl.play()
}
pause() {
this.videoEl.pause()
}
seek(time) {
if (this.isLive) return;
this.videoEl.currentTime = time;
this.play()
}
seeked(time) {
if (this.isLive) return;
this.videoEl.currentTime = time;
}
seeking(time) {
if (this.isLive) return;
if (!this.touchMode) {
this.dispatchEvent(PlayerEvent.seeking, time)
}
}
enterFullScreen() {
if (this.containerEl['requestFullscreen']) {
this.containerEl['requestFullscreen']();
} else if (this.containerEl['msRequestFullscreen']) {
this.containerEl['msRequestFullscreen']();
} else if (this.containerEl['mozRequestFullScreen']) {
this.containerEl['mozRequestFullScreen']();
} else if (this.containerEl['webkitRequestFullscreen']) {
this.containerEl['webkitRequestFullscreen']();
} else if (this.videoEl['webkitEnterFullscreen']) {
this.videoEl['webkitEnterFullscreen']();
}
}
get use3D() {
return localStorage.getItem('useGPU') == 'true' || false
}
set use3D(v) {
localStorage.setItem('useGPU', v.toString());
location.reload()
}
get useVR() {
let useVR = localStorage.getItem('useVR') == 'true' || false;
if (useVR) {
this.containerEl.classList.add('vr');
this.danmakuManager.resize()
} else {
this.containerEl.classList.remove('vr')
}
return useVR
}
set useVR(v) {
let isMobile = /Android/i.test(navigator.userAgent) || /iPhone|iPad|iPod/i.test(navigator.userAgent);
if (!isMobile) {
alert('请使用移动设备配合cardboard观看!(oculus等我的到货后支持)');
return
}
if (/iPhone|iPod/.test(navigator.userAgent) && (!navigator['standalone'])) {
alert('请回到首页然后点击Safari菜单中的添加到主屏幕,然后从主屏幕中的图标进入本站观看VR模式');
return
}
localStorage.setItem('useVR', v.toString());
if (!this.use3D) {
this.use3D = true;
} else {
this.danmakuManager.useVR = v
}
if (this.useVR) {
this.containerEl.classList.add('vr')
} else {
this.containerEl.classList.remove('vr')
}
}
exitFullScreen() {
if (document['exitFullscreen']) {
document['exitFullscreen']()
} else if (document['webkitExitFullscreen']) {
document['webkitExitFullscreen']()
} else if (document['msExitFullscreen']) {
document['msExitFullscreen']()
} else if (document['mozCancelFullScreen']) {
document['mozCancelFullScreen']()
}
this.danmakuManager.resize()
}
get bufferRange() {
if (this.videoEl.buffered.length == 0) {
return [0, 0]
}
return [this.videoEl.buffered.start(0) / this.duration, this.videoEl.buffered.end(0) / this.duration]
}
toogleDanmaku() {
this.danmakuManager.visible = !this.danmakuManager.visible
}
}
enum ProgressBarEvent {
startSeek,
seeking,
seeked
}
export class ContextMenu extends EventBase {
element: HTMLElement;
constructor() {
super();
this.initDom();
}
initDom() {
let dom = `<div class="wrapper">
<ul>
<li><a >Moe2 player 1.0.0</a></li>
</ul>
<hr/>
<ul>
<li><a data-role='pause'>暂停播放</a></li>
</ul>
<hr/>
<ul>
<li>
<a >显示视频信息</a>
</li>
</ul>
<hr/>
<ul>
<li><a >设置...</a></li>
<li><a >全局设置...</a></li>
<li><a >关于 Adobe Flash Player 18.0.0.290</a></li>
</ul>
</div>`;
this.element = createEle('div', 'flake flake_osx');
this.element.innerHTML = dom;
this.element.addEventListener('click', function (e) {
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
this.dispatchEvent('CLICK', e.target.getAttribute('data-role'))
}.bind(this), true)
}
dispose() {
this.element.parentElement.removeChild(this.element);
this.element = null;
this.listeners = null;
}
}
export class ProgressBar extends EventBase {
value: number = 0;
private player: Player;
element: HTMLElement;
private totalRangeEl: HTMLElement;
private currentRangeEl: HTMLElement;
private bufferedRangeEl: HTMLElement;
private indicatorEL: HTMLElement;
private indInner: HTMLElement;
private touchMode: boolean;
private downEvent: string;
private moveEvent: string;
private upEvent: string;
private sliderStartX: number;
touchDown = false;
private downValue;
constructor(player: Player, touchMode = !!document['createTouch']) {
super();
this.player = player;
this.element = createEle('div', 'progress-wrapper');
this.element.appendChild(this.totalRangeEl = createEle('div', 'player-progress-bar'));
this.bufferedRangeEl = createEle('div', 'buffer-range');
this.totalRangeEl.appendChild(this.bufferedRangeEl);
this.currentRangeEl = createEle('div', 'current-range');
this.totalRangeEl.appendChild(this.currentRangeEl);
this.indicatorEL = createEle('div', 'indicator');
this.indicatorEL.appendChild(this.indInner = createEle('div', 'ind-inner'));
this.totalRangeEl.appendChild(this.indicatorEL);
this.touchMode = touchMode;
this.downEvent = touchMode ? 'touchstart' : 'mousedown';
this.moveEvent = touchMode ? 'touchmove' : 'mousemove';
this.upEvent = touchMode ? 'touchend' : 'mouseup';
this.element.addEventListener(this.downEvent, (e: any) => {
e.preventDefault();
e.stopPropagation();
this.touchDown = true;
this.sliderStartX = e.clientX - e.offsetX;
if (e.target == this.indicatorEL || e.target == this.indInner) {
this.sliderStartX -= e.target.offsetLeft;
if (e.target != this.indicatorEL) {
this.sliderStartX -= this.indicatorEL.offsetLeft;
}
}
let value = this.getPageX(e) / this.element.offsetWidth;
this.downValue = value;
if (e.target == this.indicatorEL || e.target == this.indInner) {
return
}
this.setValue(value);
this.dispatchEvent(ProgressBarEvent.startSeek);
}, true);
window.addEventListener(this.moveEvent, e => {
if (this.touchDown) {
e.preventDefault();
let value = this.getPageX(e) / this.element.offsetWidth;
this.setValue(value);
this.player.seeking(value * player.duration)
}
});
window.addEventListener(this.upEvent, e => {
if (this.touchDown) {
e.preventDefault();
e.stopPropagation();
this.touchDown = false;
let value = this.getPageX(e) / this.element.offsetWidth;
if (value == this.downValue) {
return
}
this.setValue(value);
this.dispatchEvent(ProgressBarEvent.seeked);
}
}, true);
window.addEventListener('touchcancel', e => {
this.touchDown = false;
})
}
hide() {
this.element.hidden = true;
}
getPageX(e) {
if (this.touchMode) {
return e.changedTouches[0].pageX
} else {
return e.clientX - this.sliderStartX
}
}
private seeking = false;
set currentValue(v) {
if (!this.touchDown) {
this.setValue(v);
}
}
private setValue(v) {
if (v > 1) {
v = 1
}
this.currentRangeEl.style.width = v * 100 + '%';
this.indicatorEL.style.left = v * 100 + '%';
this.value = v;
}
// 应该设置[start,end]
set bufferRange(v: Array<number>) {
this.bufferedRangeEl.style.left = v[0] * 100 + '%';
this.bufferedRangeEl.style.width = (v[1] - v[0]) * 100 + '%';
}
}
export class ControlLayer extends EventBase {
element: HTMLElement;
progressBar: ProgressBar;
player: Player;
controlPanelEl: HTMLElement;
private playIconEl: HTMLElement;
private fullScreenIcon: HTMLElement;
private danmakuIconEl: HTMLElement;
private icon3DEl;
private dmkInput;
private vrIconEl;
private touchMode: boolean;
private downEvent: string;
private moveEvent: string;
private upEvent: string;
private currentTimeEl: HTMLElement;
private durationEl: HTMLElement;
lastActive = 0;
visible = true;
constructor(player: Player, title = null, touchMode = !!document['createTouch']) {
super();
this.player = player;
this.progressBar = new ProgressBar(player);
this.element = createEle('div', 'control-layer');
this.controlPanelEl = createEle('div', 'control-panel');
this.element.appendChild(this.controlPanelEl);
this.controlPanelEl.appendChild(this.progressBar.element);
if (title) {
let titleEl = createEle('div', 'video-title');
titleEl.innerHTML = `<h3>${title}</h3>`;
this.element.appendChild(titleEl);
}
let playIconElDiv = createEle('div', '');
this.playIconEl = createEle('i', 'fa fa-lg fa-play play-icon');
playIconElDiv.appendChild(this.playIconEl);
this.controlPanelEl.appendChild(this.fullScreenIcon = createEle('i', 'fa fa-lg fa-arrows-alt fullscreen-icon'));
this.controlPanelEl.appendChild(this.danmakuIconEl = createEle('i', 'fa fa-lg fa-bars danmaku-icon icon-active'));
// this.controlPanelEl.appendChild(this.icon3DEl = createEle('span', 'fa fa-lg danmaku-icon'));
// this.icon3DEl.innerHTML = '<strong>3D</strong>';
// if (this.player.use3D) {
// this.icon3DEl.classList.add('icon-active')
// }
// this.controlPanelEl.appendChild(this.vrIconEl = createEle('span', 'fa fa-lg danmaku-icon'));
// this.vrIconEl.innerHTML = '<strong>VR</strong>';
// if (this.player.useVR) {
// this.vrIconEl.classList.add('icon-active')
// }
this.controlPanelEl.appendChild(playIconElDiv);
let timeind = createEle('div', 'time-indicator');
timeind.appendChild(this.currentTimeEl = createEle('span', 'current-time'));
timeind.appendChild(this.durationEl = createEle('span', 'total-time'));
this.controlPanelEl.appendChild(timeind);
let inputBar = document.createElement('form');
inputBar.innerHTML = '<input type="text"><button type="submit">发送</button>';
let dmkInput: any = this.dmkInput = inputBar.querySelector('input');
let sendButton = inputBar.querySelector('button');
inputBar.addEventListener('submit', e => {
e.preventDefault();
let value = dmkInput.value;
player.sendDanmaku(value);
dmkInput.value = '';
});
this.controlPanelEl.appendChild(inputBar);
this.touchMode = touchMode;
this.downEvent = touchMode ? 'touchstart' : 'mousedown';
this.moveEvent = touchMode ? 'touchmove' : 'mousemove';
this.upEvent = touchMode ? 'touchend' : 'mouseup';
this.player.addEventListener(PlayerEvent.ready, () => {
if (this.player.isLive) {
this.currentTimeEl.innerHTML = '实时广播'
} else {
this.durationEl.innerHTML = '/' + this.parseTime(this.player.duration);
this.currentTimeEl.innerHTML = this.parseTime(this.player.currentTime)
}
});
this.player.addEventListener(PlayerEvent.timeupdate, this.updateTime.bind(this));
this.progressBar.addEventListener(ProgressBarEvent.startSeek, () => {
this.player.seek(this.progressBar.value * this.player.duration)
}, true);
this.progressBar.addEventListener(ProgressBarEvent.seeked, () => {
this.player.seek(this.progressBar.value * this.player.duration)
});
playIconElDiv.addEventListener(this.upEvent, e => {
e.preventDefault();
e.stopPropagation();
this.tooglePlay(e);
this.lastActive = Date.now();
}, true);
this.fullScreenIcon.addEventListener(this.upEvent, this.toogleFS.bind(this), true);
this.danmakuIconEl.addEventListener(this.upEvent, this.toogleDanmaku.bind(this), true);
// this.icon3DEl.addEventListener(this.upEvent, this.toogle3D.bind(this), true);
// this.vrIconEl.addEventListener(this.upEvent, this.toogleVR.bind(this), true);
this.player.addEventListener(PlayerEvent.play, () => {
if (this.player.isPlaying) {
this.playIconEl.classList.remove('fa-play');
this.playIconEl.classList.add('fa-pause');
}
this.durationEl.innerHTML = '/' + this.parseTime(!this.player.isLive ? this.player.duration : 0);
});
this.player.addEventListener(PlayerEvent.pause, () => {
this.playIconEl.classList.remove('fa-pause');
this.playIconEl.classList.add('fa-play')
});
this.element.addEventListener(this.upEvent, this.detectDbclick.bind(this), false);
if (!touchMode) {
this.element.addEventListener('mousemove', () => {
if (!this.player.isPlaying) {
return
}
this.lastActive = Date.now();
this.show();
//if(this.element.offsetHeight*0.68<e.clientY-this.element.offsetTop+window.pageYOffset){
// this.show();
// this.lastActive=Date.now();
//}else{
// this.hide()
//}
});
} else {
this.element.addEventListener('touchend', () => {
if (!this.player.isPlaying) {
return
}
if (this.visible) {
this.hide();
} else {
this.lastActive = Date.now();
this.show();
}
}, false)
}
setInterval(() => {
if (this.player.isPlaying == false) {
this.show();
return;
}
if (this.progressBar.touchDown) {
this.lastActive = Date.now();
return
}
if (Date.now() - this.lastActive > 2500) {
this.hide();
}
}, 500);
if (touchMode) {
} else {
}
setTimeout(() => {
this.element.classList.add('opacity')
}, 2000)
}
show() {
this.element.classList.remove('opacity');
this.visible = true;
}
hide() {
if (this.dmkInput == document.activeElement) {
return
}
this.element.classList.add('opacity');
this.visible = false
}
setliveMode() {
this.progressBar.hide();
}
private parseTime(time: number): string {
time = time || 0;
time = Math.round(time);
let ss = time % 60;
let ssstr = ss < 10 ? '0' + ss : '' + ss;
time = Math.floor(time / 60);
let mm = time % 60;
let mmstr = mm < 10 ? '0' + mm : '' + mm;
let hh = Math.floor(time / 60);
let result = mmstr + ':' + ssstr;
if (hh > 0) {
result = '' + hh + ':' + result
}
return result
}
lastClickTime = 0;
detectDbclick(e) {
let now = Date.now();
if (now - this.lastClickTime < 400) {
this.toogleFS(e)
} else {
this.lastClickTime = now
}
}
updateTime() {
const isLive = this.player.isLive;
if (!isLive) {
this.progressBar.currentValue = this.player.currentTime / this.player.duration;
this.progressBar.bufferRange = this.player.bufferRange;
this.currentTimeEl.innerHTML = this.parseTime(this.player.currentTime)
} else {
this.currentTimeEl.innerHTML = '实时广播'
}
}
tooglePlay(e) {
if (e) {
e.stopPropagation();
}
if (this.player.isPlaying) {
this.player.pause()
} else {
this.player.play()
}
}
toogleFS(e) {
if (e) {
e.stopPropagation();
}
if (this.player.fullscreenState) {
this.player.exitFullScreen()
} else {
this.player.enterFullScreen()
}
}
toogleDanmaku(e) {
if (e) {
e.stopPropagation();
}
this.player.toogleDanmaku();
if (this.player.danmakuManager.visible) {
this.danmakuIconEl.classList.add('icon-active')
} else {
this.danmakuIconEl.classList.remove('icon-active')
}
}
toogle3D(e) {
if (e) {
e.stopPropagation();
}
this.player.use3D = !this.player.use3D
}
toogleVR(e) {
if (e) {
e.stopPropagation();
}
this.player.useVR = !this.player.useVR;
if (this.player.useVR) {
this.vrIconEl.classList.add('icon-active')
} else {
this.vrIconEl.classList.remove('icon-active')
}
}
} | the_stack |
import {ResourceBase, ResourceTag} from '../resource'
import {Value, List} from '../dataTypes'
export class OwnershipControls {
Rules!: List<OwnershipControlsRule>
constructor(properties: OwnershipControls) {
Object.assign(this, properties)
}
}
export class ReplicaModifications {
Status!: Value<string>
constructor(properties: ReplicaModifications) {
Object.assign(this, properties)
}
}
export class CorsRule {
AllowedHeaders?: List<Value<string>>
AllowedMethods!: List<Value<string>>
AllowedOrigins!: List<Value<string>>
ExposedHeaders?: List<Value<string>>
Id?: Value<string>
MaxAge?: Value<number>
constructor(properties: CorsRule) {
Object.assign(this, properties)
}
}
export class Destination {
BucketAccountId?: Value<string>
BucketArn!: Value<string>
Format!: Value<string>
Prefix?: Value<string>
constructor(properties: Destination) {
Object.assign(this, properties)
}
}
export class OwnershipControlsRule {
ObjectOwnership?: Value<string>
constructor(properties: OwnershipControlsRule) {
Object.assign(this, properties)
}
}
export class AccessControlTranslation {
Owner!: Value<string>
constructor(properties: AccessControlTranslation) {
Object.assign(this, properties)
}
}
export class VersioningConfiguration {
Status!: Value<string>
constructor(properties: VersioningConfiguration) {
Object.assign(this, properties)
}
}
export class ReplicationTime {
Status!: Value<string>
Time!: ReplicationTimeValue
constructor(properties: ReplicationTime) {
Object.assign(this, properties)
}
}
export class ServerSideEncryptionByDefault {
KMSMasterKeyID?: Value<string>
SSEAlgorithm!: Value<string>
constructor(properties: ServerSideEncryptionByDefault) {
Object.assign(this, properties)
}
}
export class Tiering {
AccessTier!: Value<string>
Days!: Value<number>
constructor(properties: Tiering) {
Object.assign(this, properties)
}
}
export class SseKmsEncryptedObjects {
Status!: Value<string>
constructor(properties: SseKmsEncryptedObjects) {
Object.assign(this, properties)
}
}
export class QueueConfiguration {
Event!: Value<string>
Filter?: NotificationFilter
Queue!: Value<string>
constructor(properties: QueueConfiguration) {
Object.assign(this, properties)
}
}
export class ObjectLockConfiguration {
ObjectLockEnabled?: Value<string>
Rule?: ObjectLockRule
constructor(properties: ObjectLockConfiguration) {
Object.assign(this, properties)
}
}
export class AccelerateConfiguration {
AccelerationStatus!: Value<string>
constructor(properties: AccelerateConfiguration) {
Object.assign(this, properties)
}
}
export class IntelligentTieringConfiguration {
Id!: Value<string>
Prefix?: Value<string>
Status!: Value<string>
TagFilters?: List<TagFilter>
Tierings!: List<Tiering>
constructor(properties: IntelligentTieringConfiguration) {
Object.assign(this, properties)
}
}
export class AbortIncompleteMultipartUpload {
DaysAfterInitiation!: Value<number>
constructor(properties: AbortIncompleteMultipartUpload) {
Object.assign(this, properties)
}
}
export class DeleteMarkerReplication {
Status?: Value<string>
constructor(properties: DeleteMarkerReplication) {
Object.assign(this, properties)
}
}
export class PublicAccessBlockConfiguration {
BlockPublicAcls?: Value<boolean>
BlockPublicPolicy?: Value<boolean>
IgnorePublicAcls?: Value<boolean>
RestrictPublicBuckets?: Value<boolean>
constructor(properties: PublicAccessBlockConfiguration) {
Object.assign(this, properties)
}
}
export class ReplicationRule {
DeleteMarkerReplication?: DeleteMarkerReplication
Destination!: ReplicationDestination
Filter?: ReplicationRuleFilter
Id?: Value<string>
Prefix?: Value<string>
Priority?: Value<number>
SourceSelectionCriteria?: SourceSelectionCriteria
Status!: Value<string>
constructor(properties: ReplicationRule) {
Object.assign(this, properties)
}
}
export class SourceSelectionCriteria {
ReplicaModifications?: ReplicaModifications
SseKmsEncryptedObjects?: SseKmsEncryptedObjects
constructor(properties: SourceSelectionCriteria) {
Object.assign(this, properties)
}
}
export class StorageClassAnalysis {
DataExport?: DataExport
constructor(properties: StorageClassAnalysis) {
Object.assign(this, properties)
}
}
export class RedirectRule {
HostName?: Value<string>
HttpRedirectCode?: Value<string>
Protocol?: Value<string>
ReplaceKeyPrefixWith?: Value<string>
ReplaceKeyWith?: Value<string>
constructor(properties: RedirectRule) {
Object.assign(this, properties)
}
}
export class ObjectLockRule {
DefaultRetention?: DefaultRetention
constructor(properties: ObjectLockRule) {
Object.assign(this, properties)
}
}
export class Rule {
AbortIncompleteMultipartUpload?: AbortIncompleteMultipartUpload
ExpirationDate?: Value<string>
ExpirationInDays?: Value<number>
ExpiredObjectDeleteMarker?: Value<boolean>
Id?: Value<string>
NoncurrentVersionExpirationInDays?: Value<number>
NoncurrentVersionTransition?: NoncurrentVersionTransition
NoncurrentVersionTransitions?: List<NoncurrentVersionTransition>
Prefix?: Value<string>
Status!: Value<string>
TagFilters?: List<TagFilter>
Transition?: Transition
Transitions?: List<Transition>
constructor(properties: Rule) {
Object.assign(this, properties)
}
}
export class MetricsConfiguration {
Id!: Value<string>
Prefix?: Value<string>
TagFilters?: List<TagFilter>
constructor(properties: MetricsConfiguration) {
Object.assign(this, properties)
}
}
export class DataExport {
Destination!: Destination
OutputSchemaVersion!: Value<string>
constructor(properties: DataExport) {
Object.assign(this, properties)
}
}
export class ReplicationTimeValue {
Minutes!: Value<number>
constructor(properties: ReplicationTimeValue) {
Object.assign(this, properties)
}
}
export class FilterRule {
Name!: Value<string>
Value!: Value<string>
constructor(properties: FilterRule) {
Object.assign(this, properties)
}
}
export class ReplicationRuleAndOperator {
Prefix?: Value<string>
TagFilters?: List<TagFilter>
constructor(properties: ReplicationRuleAndOperator) {
Object.assign(this, properties)
}
}
export class BucketEncryption {
ServerSideEncryptionConfiguration!: List<ServerSideEncryptionRule>
constructor(properties: BucketEncryption) {
Object.assign(this, properties)
}
}
export class Metrics {
EventThreshold?: ReplicationTimeValue
Status!: Value<string>
constructor(properties: Metrics) {
Object.assign(this, properties)
}
}
export class RoutingRuleCondition {
HttpErrorCodeReturnedEquals?: Value<string>
KeyPrefixEquals?: Value<string>
constructor(properties: RoutingRuleCondition) {
Object.assign(this, properties)
}
}
export class LifecycleConfiguration {
Rules!: List<Rule>
constructor(properties: LifecycleConfiguration) {
Object.assign(this, properties)
}
}
export class NotificationConfiguration {
LambdaConfigurations?: List<LambdaConfiguration>
QueueConfigurations?: List<QueueConfiguration>
TopicConfigurations?: List<TopicConfiguration>
constructor(properties: NotificationConfiguration) {
Object.assign(this, properties)
}
}
export class RedirectAllRequestsTo {
HostName!: Value<string>
Protocol?: Value<string>
constructor(properties: RedirectAllRequestsTo) {
Object.assign(this, properties)
}
}
export class S3KeyFilter {
Rules!: List<FilterRule>
constructor(properties: S3KeyFilter) {
Object.assign(this, properties)
}
}
export class InventoryConfiguration {
Destination!: Destination
Enabled!: Value<boolean>
Id!: Value<string>
IncludedObjectVersions!: Value<string>
OptionalFields?: List<Value<string>>
Prefix?: Value<string>
ScheduleFrequency!: Value<string>
constructor(properties: InventoryConfiguration) {
Object.assign(this, properties)
}
}
export class ReplicationConfiguration {
Role!: Value<string>
Rules!: List<ReplicationRule>
constructor(properties: ReplicationConfiguration) {
Object.assign(this, properties)
}
}
export class CorsConfiguration {
CorsRules!: List<CorsRule>
constructor(properties: CorsConfiguration) {
Object.assign(this, properties)
}
}
export class ReplicationDestination {
AccessControlTranslation?: AccessControlTranslation
Account?: Value<string>
Bucket!: Value<string>
EncryptionConfiguration?: EncryptionConfiguration
Metrics?: Metrics
ReplicationTime?: ReplicationTime
StorageClass?: Value<string>
constructor(properties: ReplicationDestination) {
Object.assign(this, properties)
}
}
export class NoncurrentVersionTransition {
StorageClass!: Value<string>
TransitionInDays!: Value<number>
constructor(properties: NoncurrentVersionTransition) {
Object.assign(this, properties)
}
}
export class DefaultRetention {
Days?: Value<number>
Mode?: Value<string>
Years?: Value<number>
constructor(properties: DefaultRetention) {
Object.assign(this, properties)
}
}
export class NotificationFilter {
S3Key!: S3KeyFilter
constructor(properties: NotificationFilter) {
Object.assign(this, properties)
}
}
export class LambdaConfiguration {
Event!: Value<string>
Filter?: NotificationFilter
Function!: Value<string>
constructor(properties: LambdaConfiguration) {
Object.assign(this, properties)
}
}
export class ServerSideEncryptionRule {
BucketKeyEnabled?: Value<boolean>
ServerSideEncryptionByDefault?: ServerSideEncryptionByDefault
constructor(properties: ServerSideEncryptionRule) {
Object.assign(this, properties)
}
}
export class AnalyticsConfiguration {
Id!: Value<string>
Prefix?: Value<string>
StorageClassAnalysis!: StorageClassAnalysis
TagFilters?: List<TagFilter>
constructor(properties: AnalyticsConfiguration) {
Object.assign(this, properties)
}
}
export class LoggingConfiguration {
DestinationBucketName?: Value<string>
LogFilePrefix?: Value<string>
constructor(properties: LoggingConfiguration) {
Object.assign(this, properties)
}
}
export class RoutingRule {
RedirectRule!: RedirectRule
RoutingRuleCondition?: RoutingRuleCondition
constructor(properties: RoutingRule) {
Object.assign(this, properties)
}
}
export class EncryptionConfiguration {
ReplicaKmsKeyID!: Value<string>
constructor(properties: EncryptionConfiguration) {
Object.assign(this, properties)
}
}
export class WebsiteConfiguration {
ErrorDocument?: Value<string>
IndexDocument?: Value<string>
RedirectAllRequestsTo?: RedirectAllRequestsTo
RoutingRules?: List<RoutingRule>
constructor(properties: WebsiteConfiguration) {
Object.assign(this, properties)
}
}
export class TopicConfiguration {
Event!: Value<string>
Filter?: NotificationFilter
Topic!: Value<string>
constructor(properties: TopicConfiguration) {
Object.assign(this, properties)
}
}
export class TagFilter {
Key!: Value<string>
Value!: Value<string>
constructor(properties: TagFilter) {
Object.assign(this, properties)
}
}
export class Transition {
StorageClass!: Value<string>
TransitionDate?: Value<string>
TransitionInDays?: Value<number>
constructor(properties: Transition) {
Object.assign(this, properties)
}
}
export class ReplicationRuleFilter {
And?: ReplicationRuleAndOperator
Prefix?: Value<string>
TagFilter?: TagFilter
constructor(properties: ReplicationRuleFilter) {
Object.assign(this, properties)
}
}
export interface BucketProperties {
AccelerateConfiguration?: AccelerateConfiguration
AccessControl?: Value<string>
AnalyticsConfigurations?: List<AnalyticsConfiguration>
BucketEncryption?: BucketEncryption
BucketName?: Value<string>
CorsConfiguration?: CorsConfiguration
IntelligentTieringConfigurations?: List<IntelligentTieringConfiguration>
InventoryConfigurations?: List<InventoryConfiguration>
LifecycleConfiguration?: LifecycleConfiguration
LoggingConfiguration?: LoggingConfiguration
MetricsConfigurations?: List<MetricsConfiguration>
NotificationConfiguration?: NotificationConfiguration
ObjectLockConfiguration?: ObjectLockConfiguration
ObjectLockEnabled?: Value<boolean>
OwnershipControls?: OwnershipControls
PublicAccessBlockConfiguration?: PublicAccessBlockConfiguration
ReplicationConfiguration?: ReplicationConfiguration
Tags?: List<ResourceTag>
VersioningConfiguration?: VersioningConfiguration
WebsiteConfiguration?: WebsiteConfiguration
}
export default class Bucket extends ResourceBase<BucketProperties> {
static OwnershipControls = OwnershipControls
static ReplicaModifications = ReplicaModifications
static CorsRule = CorsRule
static Destination = Destination
static OwnershipControlsRule = OwnershipControlsRule
static AccessControlTranslation = AccessControlTranslation
static VersioningConfiguration = VersioningConfiguration
static ReplicationTime = ReplicationTime
static ServerSideEncryptionByDefault = ServerSideEncryptionByDefault
static Tiering = Tiering
static SseKmsEncryptedObjects = SseKmsEncryptedObjects
static QueueConfiguration = QueueConfiguration
static ObjectLockConfiguration = ObjectLockConfiguration
static AccelerateConfiguration = AccelerateConfiguration
static IntelligentTieringConfiguration = IntelligentTieringConfiguration
static AbortIncompleteMultipartUpload = AbortIncompleteMultipartUpload
static DeleteMarkerReplication = DeleteMarkerReplication
static PublicAccessBlockConfiguration = PublicAccessBlockConfiguration
static ReplicationRule = ReplicationRule
static SourceSelectionCriteria = SourceSelectionCriteria
static StorageClassAnalysis = StorageClassAnalysis
static RedirectRule = RedirectRule
static ObjectLockRule = ObjectLockRule
static Rule = Rule
static MetricsConfiguration = MetricsConfiguration
static DataExport = DataExport
static ReplicationTimeValue = ReplicationTimeValue
static FilterRule = FilterRule
static ReplicationRuleAndOperator = ReplicationRuleAndOperator
static BucketEncryption = BucketEncryption
static Metrics = Metrics
static RoutingRuleCondition = RoutingRuleCondition
static LifecycleConfiguration = LifecycleConfiguration
static NotificationConfiguration = NotificationConfiguration
static RedirectAllRequestsTo = RedirectAllRequestsTo
static S3KeyFilter = S3KeyFilter
static InventoryConfiguration = InventoryConfiguration
static ReplicationConfiguration = ReplicationConfiguration
static CorsConfiguration = CorsConfiguration
static ReplicationDestination = ReplicationDestination
static NoncurrentVersionTransition = NoncurrentVersionTransition
static DefaultRetention = DefaultRetention
static NotificationFilter = NotificationFilter
static LambdaConfiguration = LambdaConfiguration
static ServerSideEncryptionRule = ServerSideEncryptionRule
static AnalyticsConfiguration = AnalyticsConfiguration
static LoggingConfiguration = LoggingConfiguration
static RoutingRule = RoutingRule
static EncryptionConfiguration = EncryptionConfiguration
static WebsiteConfiguration = WebsiteConfiguration
static TopicConfiguration = TopicConfiguration
static TagFilter = TagFilter
static Transition = Transition
static ReplicationRuleFilter = ReplicationRuleFilter
constructor(properties?: BucketProperties) {
super('AWS::S3::Bucket', properties || {})
}
} | the_stack |
import { Bone, SkinnedMesh } from 'three'
import { Object3D, Quaternion, Skeleton, Vector3 } from 'three'
import { SkeletonUtils } from '../../avatar/SkeletonUtils'
import { DOWN, LEFT, RIGHT } from '../constants/Vector3Constants'
import { spinBoneForward, alignChain, alignBoneForward, worldToModel } from '../functions/IKFunctions'
import { Entity } from '../../ecs/classes/Entity'
import { transformAdd } from '../functions/IKSolvers'
export type PoseBoneTransform = {
position: Vector3
quaternion: Quaternion
scale: Vector3
}
export type PoseBoneLocalState = {
bone: Bone
parent: Bone | null
chg_state: number // If Local Has Been Updated
idx: number // Bone Index in Armature
p_idx: number | null // Parent Bone Index in Armature
length: number // Length of Bone
name: string
local: PoseBoneTransform // Local Transform, use Bind pose as default
world: PoseBoneTransform // Model Space Transform
}
class Pose {
static ROTATION = 1
static POSITION = 2
static SCALE = 4
entity: Entity
skeleton: Skeleton
bones: PoseBoneLocalState[]
rootOffset = {
quaternion: new Quaternion(),
position: new Vector3(0, 0, 0),
scale: new Vector3(1, 1, 1)
}
helper: any
align_leg(b_names: string[]) {
alignChain(this, DOWN, b_names)
return this
}
align_arm_left(b_names: string[]) {
alignChain(this, LEFT, b_names)
return this
}
align_arm_right(b_names: string[]) {
alignChain(this, RIGHT, b_names)
return this
}
align_foot(b_name: string) {
spinBoneForward(this, b_name)
alignBoneForward(this, b_name)
return this
}
spin_bone_forward(b_name: string) {
spinBoneForward(this, b_name)
return this
}
align_bone_forward(b_name: string) {
alignBoneForward(this, b_name)
return this
}
/**
*
* @param rootObject object containing skinnedMesh and it's bones
* @param clone make a cloned version of skeleton
*/
constructor(rootObject: Object3D, clone = false) {
this.bones = []
const parent: Object3D = clone ? SkeletonUtils.clone(rootObject) : rootObject
this.skeleton = this.get_skeleton(parent) // Recreation of Bone Hierarchy
if (!this.skeleton.bones[0]) {
debugger
}
// this.bones = this.skeleton.bones
this.rootOffset = new Object3D() // Parent Transform for Root Bone ( Skeletons from FBX imports need this to render right )
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Create Bone Transform Hierarchy to do transformations
// without changing the actual armature.
const skeletonTransform = {
position: new Vector3(),
quaternion: new Quaternion(),
invQuaternion: new Quaternion(),
scale: new Vector3()
}
const rootBone = this.skeleton.bones.find((b) => !(b.parent instanceof Bone))
if (rootBone.parent) {
rootBone.parent.getWorldPosition(skeletonTransform.position)
rootBone.parent.getWorldQuaternion(skeletonTransform.quaternion)
rootBone.parent.getWorldScale(skeletonTransform.scale)
skeletonTransform.invQuaternion.copy(skeletonTransform.quaternion).invert()
}
for (let i = 0; i < this.skeleton.bones.length; i++) {
const b = this.skeleton.bones[i]
let p_idx, boneParent
if (b.parent && b.parent instanceof Bone) {
p_idx = this.skeleton.bones.indexOf(b.parent)
boneParent = b.parent
}
const boneData = {
bone: b,
parent: boneParent,
chg_state: 0, // If Local Has Been Updated
idx: i, // Bone Index in Armature
p_idx: p_idx, // Parent Bone Index in Armature
length: 0.1, // Length of Bone
name: b.name,
local: {
position: b.position.clone(),
quaternion: b.quaternion.clone(),
scale: b.scale.clone()
}, // Local Transform, use Bind pose as default
world: {
position: new Vector3(),
quaternion: new Quaternion(),
invQuaternion: new Quaternion(),
scale: new Vector3()
} // Model Space Transform
}
b.getWorldPosition(boneData.world.position)
b.getWorldQuaternion(boneData.world.quaternion)
b.getWorldScale(boneData.world.scale)
// convert to model space
worldToModel(boneData.world.position, boneData.world.quaternion, boneData.world.scale, skeletonTransform)
// Calculate this once for tpose
boneData.world.invQuaternion.copy(boneData.world.quaternion).invert()
//b['index'] = i
if (b.children.length > 0) {
// b.getWorldPosition(bWorldPosition)
// b.children[0].getWorldPosition(bChildWorldPosition)
// bWorldPosition.divide(skeletonTransform.scale)
// bChildWorldPosition.divide(skeletonTransform.scale)
boneData.length = b.children[0].position.length()
}
this.bones[i] = boneData
}
this.skeleton.update()
}
get_skeleton(rootObject: Object3D): Skeleton | null {
let skeleton: Skeleton = null
rootObject.traverse((object) => {
if (object instanceof SkinnedMesh && object.skeleton != null) {
if (skeleton && skeleton.bones.length > object.skeleton.bones.length) {
return
}
skeleton = object.skeleton
}
})
return skeleton
}
setOffset(quaternion: Quaternion, position: Vector3, scale: Vector3) {
this.rootOffset.quaternion.copy(quaternion)
this.rootOffset.position.copy(position)
this.rootOffset.scale.copy(scale)
return this
}
setBone(index: number, quaternion?: Quaternion, position?: Vector3, scale?: Vector3) {
// TODO: check this out, they store this in separate structure that does not change original bone data
if (quaternion) this.bones[index].local.quaternion.copy(quaternion)
if (position) this.bones[index].local.position.copy(position)
if (scale) this.bones[index].local.scale.copy(scale)
return this
}
getBone(name: string): PoseBoneLocalState {
// TODO: replace with Map?
return this.bones.find((b) => b.name === name)
}
apply(): Pose {
// Copies modified LquatInverseocal Transforms of the Pose to the Bone Entities.
// const targetSkeleton: Skeleton = getComponent(this.entity, IKObj).ref.skeleton
let pb: PoseBoneLocalState, // Pose Bone
o: Bone // Bone Object
for (let i = 0; i < this.skeleton.bones.length; i++) {
pb = this.bones[i]
// Check if bone has been modified in the pose
o = this.skeleton.bones[i]
// Copy changes to Bone Entity
// o.setRotationFromQuaternion(pb.quaternion)
o.quaternion.copy(pb.local.quaternion)
o.position.copy(pb.local.position)
o.scale.copy(pb.local.scale)
}
this.skeleton.update()
// targetSkeleton.update()
return this
}
// If these are temp vars okay, but these might need to move to the bones?? Do we need these if we have world poses on bones?
parentQuaternion = new Quaternion()
parentScale = new Vector3(1, 1, 1)
parentPosition = new Vector3(0, 0, 0)
childQuaternion = new Quaternion()
childScale = new Vector3(1, 1, 1)
childPosition = new Vector3(0, 0, 0)
// Make sure this is properly named
setChildFromParent(parent: Object3D, child: Object3D): Pose {
console.log('parent, child', parent, child)
// POSITION - parent.position + ( parent.quaternion * ( parent.scale * child.position ) )
// TODO: Make sure this matrix isn't flipped
const v: Vector3 = new Vector3()
.copy(parent.scale)
.multiply(child.position) // parent.scale * child.position;
.applyQuaternion(parent.quaternion) //Vec3.transformQuat( v, tp.quaternion, v );
this.childPosition = new Vector3().copy(parent.position).add(v) // Vec3.add( tp.position, v, this.position );
console.log('v is', v)
console.log('this.childPosition', this.childPosition)
// SCALE - parent.scale * child.scale
// TODO: not flipped, right?
this.childScale = new Vector3().copy(parent.scale).multiply(child.scale)
// ROTATION - parent.quaternion * child.quaternion
this.childQuaternion = new Quaternion().copy(parent.quaternion).multiply(child.quaternion)
return this
}
getParentRotation(boneIndex: number): Quaternion {
// // ORIGINAL CODE
// // get_parent_rot( b_idx, q=null ){
// // let cbone = this.bones[ b_idx ];
// // q = q || new Quat();
//
// const bone = this.skeleton.bones[this.bones[boneIndex].idx]
// const q = new Quaternion()
//
// // ORIGINAL CODE
// //if( cbone.p_idx == null ) q.reset();
// // Child is a Root Bone, just reset since there is no parent.
// if (bone.parent == null) q.identity()
// else {
// // ORIGINAL CODE
// // let b = this.bones[ cbone.p_idx ];
// // q.copy( b.local.rot );
//
// // while( b.p_idx != null ){
// // b = this.bones[ b.p_idx ];
// // q.pmul( b.local.rot );
// // }
// // Parents Exist, loop till reaching the root
// let b = bone.parent
// q.copy(b.quaternion)
// while (b.parent != null && b.parent.type === 'Bone') {
// b = b.parent
// q.premultiply(b.quaternion)
// }
// }
// // ORIGINAL CODE
// // q.pmul( this.root_offset.rot ); // Add Starting Offset
// q.premultiply(this.rootOffset.quaternion) // Add Starting Offset
const cbone = this.bones[boneIndex]
const q = new Quaternion()
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Child is a Root Bone, just reset since there is no parent.
if (cbone.p_idx == null) q.identity()
else {
// Parents Exist, loop till reaching the root
let b = this.bones[cbone.p_idx]
q.copy(b.local.quaternion)
while (b.p_idx != null) {
b = this.bones[b.p_idx]
q.premultiply(b.local.quaternion)
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
q.premultiply(this.rootOffset.quaternion) // Add Starting Offset
return q
}
transformAdd_rev(pt: PoseBoneTransform, ct: PoseBoneTransform) {
pt.position.multiply(ct.scale).applyQuaternion(ct.quaternion).add(ct.position)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// SCALE - parent.scale * child.scale
pt.scale.multiply(ct.scale)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ROTATION - parent.rotation * child.rotation
pt.quaternion.premultiply(ct.quaternion) // Must Rotate from Parent->Child, need PMUL
}
get_parent_world(
b_idx: number,
pt: PoseBoneTransform = null,
ct: PoseBoneTransform = null,
t_offset: PoseBoneTransform = null
) {
const cbone = this.bones[b_idx]
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Child is a Root Bone, just reset since there is no parent.
if (cbone.p_idx == null) {
pt.position.set(0, 0, 0)
pt.scale.set(0, 0, 0)
pt.quaternion.set(0, 0, 0, 0)
} else {
// Parents Exist, loop till reaching the root
let b = this.bones[cbone.p_idx]
pt.position.copy(b.local.position)
pt.scale.copy(b.local.scale)
pt.quaternion.copy(b.local.quaternion)
while (b.p_idx != null) {
b = this.bones[b.p_idx]
this.transformAdd_rev(pt, b.local)
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
this.transformAdd_rev(pt, this.rootOffset) // Add Starting Offset
if (t_offset) {
this.transformAdd_rev(pt, t_offset) // Add Additional Starting Offset
}
if (ct) {
ct.position.copy(pt.position)
ct.scale.copy(pt.scale)
ct.quaternion.copy(pt.quaternion)
transformAdd(ct, cbone.local) // Requesting Child WS Info Too
// ct.from_add(pt, cbone.local) // Requesting Child WS Info Too
}
return pt
}
}
export default Pose | the_stack |
import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from "@angular/core";
import { forkJoin, Observable, throwError as observableThrowError } from "rxjs";
import { catchError, finalize, map } from "rxjs/operators";
import { TranslateService } from "@ngx-translate/core";
import { HelmChartMaintainer, HelmChartVersion } from "../../helm-chart.interface.service";
import { HelmChartService } from "../../helm-chart.service";
import {
LabelService as OldLabelService,
State,
SystemInfo,
SystemInfoService,
UserPermissionService,
USERSTATICPERMISSION
} from "../../../../../../shared/services";
import { DEFAULT_PAGE_SIZE, downloadFile } from "../../../../../../shared/units/utils";
import { ErrorHandler } from "../../../../../../shared/units/error-handler";
import { OperationService } from "../../../../../../shared/components/operation/operation.service";
import { operateChanges, OperateInfo, OperationState } from "../../../../../../shared/components/operation/operate";
import {
ConfirmationButtons,
ConfirmationState,
ConfirmationTargets,
DefaultHelmIcon,
ResourceType
} from "../../../../../../shared/entities/shared.const";
import { errorHandler } from "../../../../../../shared/units/shared.utils";
import { ConfirmationDialogComponent } from "../../../../../../shared/components/confirmation-dialog";
import { ConfirmationMessage } from "../../../../../global-confirmation-dialog/confirmation-message";
import { ConfirmationAcknowledgement } from "../../../../../global-confirmation-dialog/confirmation-state-message";
import { Label } from "../../../../../../../../ng-swagger-gen/models/label";
import { LabelService } from "../../../../../../../../ng-swagger-gen/services/label.service";
const PAGE_SIZE: number = 100;
@Component({
selector: "hbr-helm-chart-version",
templateUrl: "./helm-chart-version.component.html",
styleUrls: ["./helm-chart-version.component.scss"],
})
export class ChartVersionComponent implements OnInit {
signedCon: { [key: string]: any | string[] } = {};
@Input() projectId: number;
@Input() projectName: string;
@Input() chartName: string;
@Input() roleName: string;
@Input() hasSignedIn: boolean;
@Input() chartDefaultIcon: string = DefaultHelmIcon;
@Output() versionClickEvt = new EventEmitter<string>();
@Output() backEvt = new EventEmitter<any>();
lastFilteredVersionName: string;
chartVersions: HelmChartVersion[] = [];
systemInfo: SystemInfo;
selectedRows: HelmChartVersion[] = [];
labels: Label[] = [];
loading = true;
resourceType = ResourceType.CHART_VERSION;
isCardView: boolean;
cardHover = false;
listHover = false;
pageSize: number = DEFAULT_PAGE_SIZE;
currentPage = 1;
totalCount = 0;
currentState: State;
chartFile: File;
provFile: File;
addLabelHeaders = 'HELM_CHART.ADD_LABEL_TO_CHART_VERSION';
@ViewChild("confirmationDialog")
confirmationDialog: ConfirmationDialogComponent;
hasAddRemoveHelmChartVersionPermission: boolean;
hasDownloadHelmChartVersionPermission: boolean;
hasDeleteHelmChartVersionPermission: boolean;
constructor(
private errorHandlerEntity: ErrorHandler,
private systemInfoService: SystemInfoService,
private helmChartService: HelmChartService,
private labelService: LabelService,
private resrouceLabelService: OldLabelService,
public userPermissionService: UserPermissionService,
private operationService: OperationService,
private translateService: TranslateService,
) { }
public get registryUrl(): string {
return this.systemInfo ? this.systemInfo.registry_url : "";
}
ngOnInit(): void {
// Get system info for tag views
this.systemInfoService.getSystemInfo()
.subscribe(systemInfo => (this.systemInfo = systemInfo)
, error => this.errorHandlerEntity.error(error));
this.refresh();
this.getLabels();
this.lastFilteredVersionName = "";
this.getHelmChartVersionPermission(this.projectId);
}
updateFilterValue(value: string) {
this.lastFilteredVersionName = value;
this.refresh();
}
getLabels() {
// get all project labels
this.labelService.ListLabelsResponse({
pageSize: PAGE_SIZE,
page: 1,
scope: 'p',
projectId: this.projectId
}).subscribe(res => {
if (res.headers) {
const xHeader: string = res.headers.get("X-Total-Count");
const totalCount = parseInt(xHeader, 0);
let arr = res.body || [];
if (totalCount <= PAGE_SIZE) { // already gotten all project labels
if (arr && arr.length) {
this.labels = this.labels.concat(arr);
}
} else { // get all the project labels in specified times
const times: number = Math.ceil(totalCount / PAGE_SIZE);
const observableList: Observable<Label[]>[] = [];
for (let i = 2; i <= times; i++) {
observableList.push(this.labelService.ListLabels({
page: i,
pageSize: PAGE_SIZE,
scope: 'p',
projectId: this.projectId
}));
}
forkJoin(observableList).subscribe(response => {
if (response && response.length) {
response.forEach(item => {
arr = arr.concat(item);
});
this.labels = this.labels.concat(arr);
}
});
}
}
});
// get all global labels
this.labelService.ListLabelsResponse({
pageSize: PAGE_SIZE,
page: 1,
scope: 'g',
}).subscribe(res => {
if (res.headers) {
const xHeader: string = res.headers.get("X-Total-Count");
const totalCount = parseInt(xHeader, 0);
let arr = res.body || [];
if (totalCount <= PAGE_SIZE) { // already gotten all global labels
if (arr && arr.length) {
this.labels = this.labels.concat(arr);
}
} else { // get all the global labels in specified times
const times: number = Math.ceil(totalCount / PAGE_SIZE);
const observableList: Observable<Label[]>[] = [];
for (let i = 2; i <= times; i++) {
observableList.push(this.labelService.ListLabels({
page: i,
pageSize: PAGE_SIZE,
scope: 'g',
}));
}
forkJoin(observableList).subscribe(response => {
if (response && response.length) {
response.forEach(item => {
arr = arr.concat(item);
});
this.labels = this.labels.concat(arr);
}
});
}
}
});
}
refresh() {
this.loading = true;
this.helmChartService
.getChartVersions(this.projectName, this.chartName)
.pipe(finalize(() => {
this.selectedRows = [];
this.loading = false;
}))
.subscribe(
versions => {
this.chartVersions = versions.filter(x => x.version.includes(this.lastFilteredVersionName));
this.totalCount = versions.length;
},
err => {
this.errorHandlerEntity.error(err);
}
);
}
getMaintainerString(maintainers: HelmChartMaintainer[]) {
if (!maintainers || maintainers.length < 1) {
return "";
}
let maintainer_string = maintainers[0].name;
if (maintainers.length > 1) {
maintainer_string = `${maintainer_string} (${maintainers.length - 1} others)`;
}
return maintainer_string;
}
onVersionClick(version: HelmChartVersion) {
this.versionClickEvt.emit(version.version);
}
deleteVersion(version: HelmChartVersion): Observable<any> {
// init operation info
let operateMsg = new OperateInfo();
operateMsg.name = "OPERATION.DELETE_CHART_VERSION";
operateMsg.data.id = version.digest;
operateMsg.state = OperationState.progressing;
operateMsg.data.name = `${version.name}:${version.version}`;
this.operationService.publishInfo(operateMsg);
return this.helmChartService
.deleteChartVersion(this.projectName, this.chartName, version.version)
.pipe(map(
() => operateChanges(operateMsg, OperationState.success)),
catchError( error => {
const message = errorHandler(error);
this.translateService.get(message).subscribe(res =>
operateChanges(operateMsg, OperationState.failure, res)
);
return observableThrowError(error);
}
));
}
deleteVersions(versions: HelmChartVersion[]) {
if (versions && versions.length < 1) { return; }
let successCount: number;
let totalCount = this.chartVersions.length;
let versionObs = versions.map(v => this.deleteVersion(v));
forkJoin(versionObs).pipe(finalize(() => {
if (totalCount !== successCount) {
this.refresh();
}
})).subscribe(res => {
successCount = res.filter(r => r.state === OperationState.success).length;
if (totalCount === successCount) {
this.backEvt.emit();
}
}, error => {
this.errorHandlerEntity.error(error);
});
}
versionDownload(evt?: Event, item?: HelmChartVersion) {
if (evt) {
evt.stopPropagation();
}
let selectedVersion: HelmChartVersion;
if (item) {
selectedVersion = item;
} else {
// return if selected version less then 1
if (this.selectedRows.length < 1) {
return;
}
selectedVersion = this.selectedRows[0];
}
if (!selectedVersion) {
return;
}
let filename = selectedVersion.urls[0];
this.helmChartService.downloadChart(this.projectName, filename).subscribe(
res => {
downloadFile(res);
},
error => {
this.errorHandlerEntity.error(error);
}
);
}
showCard(cardView: boolean) {
if (this.isCardView === cardView) {
return;
}
this.isCardView = cardView;
}
mouseEnter(itemName: string) {
if (itemName === "card") {
this.cardHover = true;
} else {
this.listHover = true;
}
}
mouseLeave(itemName: string) {
if (itemName === "card") {
this.cardHover = false;
} else {
this.listHover = false;
}
}
isHovering(itemName: string) {
if (itemName === "card") {
return this.cardHover;
} else {
return this.listHover;
}
}
onChartFileChangeEvent(event) {
if (event.target.files && event.target.files.length > 0) {
this.chartFile = event.target.files[0];
}
}
onProvFileChangeEvent(event) {
if (event.target.files && event.target.files.length > 0) {
this.provFile = event.target.files[0];
}
}
deleteVersionCard(env: Event, version: HelmChartVersion) {
env.stopPropagation();
this.openVersionDeleteModal([version]);
}
openVersionDeleteModal(versions?: HelmChartVersion[]) {
if (!versions) {
versions = this.selectedRows;
}
let versionNames = versions.map(v => v.version).join(",");
let message = new ConfirmationMessage(
"HELM_CHART.DELETE_CHART_VERSION_TITLE",
"HELM_CHART.DELETE_CHART_VERSION",
versionNames,
versions,
ConfirmationTargets.HELM_CHART_VERSION,
ConfirmationButtons.DELETE_CANCEL
);
this.confirmationDialog.open(message);
}
confirmDeletion(message: ConfirmationAcknowledgement) {
if (
message &&
message.source === ConfirmationTargets.HELM_CHART_VERSION &&
message.state === ConfirmationState.CONFIRMED
) {
let versions = message.data;
this.deleteVersions(versions);
}
}
getImgLink(v: HelmChartVersion) {
if (v.icon) {
return v.icon;
} else {
return DefaultHelmIcon;
}
}
getDefaultIcon(v: HelmChartVersion) {
v.icon = this.chartDefaultIcon;
}
getStatusString(chartVersion: HelmChartVersion) {
if (chartVersion.deprecated) {
return "HELM_CHART.DEPRECATED";
} else {
return "HELM_CHART.ACTIVE";
}
}
onLabelChange(version: HelmChartVersion) {
this.resrouceLabelService.getChartVersionLabels(this.projectName, this.chartName, version.version)
.subscribe(labels => {
let versionIdx = this.chartVersions.findIndex(v => v.name === version.name);
this.chartVersions[versionIdx].labels = labels;
});
}
getHelmChartVersionPermission(projectId: number): void {
let hasAddRemoveHelmChartVersionPermission = this.userPermissionService.getPermission(projectId,
USERSTATICPERMISSION.HELM_CHART_VERSION_LABEL.KEY, USERSTATICPERMISSION.HELM_CHART_VERSION_LABEL.VALUE.CREATE);
let hasDownloadHelmChartVersionPermission = this.userPermissionService.getPermission(projectId,
USERSTATICPERMISSION.HELM_CHART_VERSION.KEY, USERSTATICPERMISSION.HELM_CHART_VERSION.VALUE.READ);
let hasDeleteHelmChartVersionPermission = this.userPermissionService.getPermission(projectId,
USERSTATICPERMISSION.HELM_CHART_VERSION.KEY, USERSTATICPERMISSION.HELM_CHART_VERSION.VALUE.DELETE);
forkJoin(hasAddRemoveHelmChartVersionPermission, hasDownloadHelmChartVersionPermission, hasDeleteHelmChartVersionPermission)
.subscribe(permissions => {
this.hasAddRemoveHelmChartVersionPermission = permissions[0] as boolean;
this.hasDownloadHelmChartVersionPermission = permissions[1] as boolean;
this.hasDeleteHelmChartVersionPermission = permissions[2] as boolean;
}, error => this.errorHandlerEntity.error(error));
}
} | the_stack |
import {
defineAsyncComponent,
defineCustomElement,
h,
inject,
nextTick,
Ref,
ref,
renderSlot,
VueElement
} from '../src'
describe('defineCustomElement', () => {
const container = document.createElement('div')
document.body.appendChild(container)
beforeEach(() => {
container.innerHTML = ''
})
describe('mounting/unmount', () => {
const E = defineCustomElement({
props: {
msg: {
type: String,
default: 'hello'
}
},
render() {
return h('div', this.msg)
}
})
customElements.define('my-element', E)
test('should work', () => {
container.innerHTML = `<my-element></my-element>`
const e = container.childNodes[0] as VueElement
expect(e).toBeInstanceOf(E)
expect(e._instance).toBeTruthy()
expect(e.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
})
test('should work w/ manual instantiation', () => {
const e = new E({ msg: 'inline' })
// should lazy init
expect(e._instance).toBe(null)
// should initialize on connect
container.appendChild(e)
expect(e._instance).toBeTruthy()
expect(e.shadowRoot!.innerHTML).toBe(`<div>inline</div>`)
})
test('should unmount on remove', async () => {
container.innerHTML = `<my-element></my-element>`
const e = container.childNodes[0] as VueElement
container.removeChild(e)
await nextTick()
expect(e._instance).toBe(null)
expect(e.shadowRoot!.innerHTML).toBe('')
})
test('should not unmount on move', async () => {
container.innerHTML = `<div><my-element></my-element></div>`
const e = container.childNodes[0].childNodes[0] as VueElement
const i = e._instance
// moving from one parent to another - this will trigger both disconnect
// and connected callbacks synchronously
container.appendChild(e)
await nextTick()
// should be the same instance
expect(e._instance).toBe(i)
expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div>')
})
})
describe('props', () => {
const E = defineCustomElement({
props: ['foo', 'bar', 'bazQux'],
render() {
return [
h('div', null, this.foo),
h('div', null, this.bazQux || (this.bar && this.bar.x))
]
}
})
customElements.define('my-el-props', E)
test('props via attribute', async () => {
// bazQux should map to `baz-qux` attribute
container.innerHTML = `<my-el-props foo="hello" baz-qux="bye"></my-el-props>`
const e = container.childNodes[0] as VueElement
expect(e.shadowRoot!.innerHTML).toBe('<div>hello</div><div>bye</div>')
// change attr
e.setAttribute('foo', 'changed')
await nextTick()
expect(e.shadowRoot!.innerHTML).toBe('<div>changed</div><div>bye</div>')
e.setAttribute('baz-qux', 'changed')
await nextTick()
expect(e.shadowRoot!.innerHTML).toBe(
'<div>changed</div><div>changed</div>'
)
})
test('props via properties', async () => {
const e = new E()
e.foo = 'one'
e.bar = { x: 'two' }
container.appendChild(e)
expect(e.shadowRoot!.innerHTML).toBe('<div>one</div><div>two</div>')
// reflect
// should reflect primitive value
expect(e.getAttribute('foo')).toBe('one')
// should not reflect rich data
expect(e.hasAttribute('bar')).toBe(false)
e.foo = 'three'
await nextTick()
expect(e.shadowRoot!.innerHTML).toBe('<div>three</div><div>two</div>')
expect(e.getAttribute('foo')).toBe('three')
e.foo = null
await nextTick()
expect(e.shadowRoot!.innerHTML).toBe('<div></div><div>two</div>')
expect(e.hasAttribute('foo')).toBe(false)
e.bazQux = 'four'
await nextTick()
expect(e.shadowRoot!.innerHTML).toBe('<div></div><div>four</div>')
expect(e.getAttribute('baz-qux')).toBe('four')
})
test('attribute -> prop type casting', async () => {
const E = defineCustomElement({
props: {
foo: Number,
bar: Boolean,
baz: String
},
render() {
return [
this.foo,
typeof this.foo,
this.bar,
typeof this.bar,
this.baz,
typeof this.baz
].join(' ')
}
})
customElements.define('my-el-props-cast', E)
container.innerHTML = `<my-el-props-cast foo="1" baz="12345"></my-el-props-cast>`
const e = container.childNodes[0] as VueElement
expect(e.shadowRoot!.innerHTML).toBe(
`1 number false boolean 12345 string`
)
e.setAttribute('bar', '')
await nextTick()
expect(e.shadowRoot!.innerHTML).toBe(`1 number true boolean 12345 string`)
e.setAttribute('foo', '2e1')
await nextTick()
expect(e.shadowRoot!.innerHTML).toBe(
`20 number true boolean 12345 string`
)
e.setAttribute('baz', '2e1')
await nextTick()
expect(e.shadowRoot!.innerHTML).toBe(`20 number true boolean 2e1 string`)
})
// #4772
test('attr casting w/ programmatic creation', () => {
const E = defineCustomElement({
props: {
foo: Number
},
render() {
return `foo type: ${typeof this.foo}`
}
})
customElements.define('my-element-programmatic', E)
const el = document.createElement('my-element-programmatic') as any
el.setAttribute('foo', '123')
container.appendChild(el)
expect(el.shadowRoot.innerHTML).toBe(`foo type: number`)
})
test('handling properties set before upgrading', () => {
const E = defineCustomElement({
props: {
foo: String,
dataAge: Number
},
setup(props) {
expect(props.foo).toBe('hello')
expect(props.dataAge).toBe(5)
},
render() {
return `foo: ${this.foo}`
}
})
const el = document.createElement('my-el-upgrade') as any
el.foo = 'hello'
el.dataset.age = 5
container.appendChild(el)
customElements.define('my-el-upgrade', E)
expect(el.shadowRoot.innerHTML).toBe(`foo: hello`)
})
})
describe('emits', () => {
const E = defineCustomElement({
setup(_, { emit }) {
emit('created')
return () =>
h('div', {
onClick: () => emit('my-click', 1)
})
}
})
customElements.define('my-el-emits', E)
test('emit on connect', () => {
const e = new E()
const spy = jest.fn()
e.addEventListener('created', spy)
container.appendChild(e)
expect(spy).toHaveBeenCalled()
})
test('emit on interaction', () => {
container.innerHTML = `<my-el-emits></my-el-emits>`
const e = container.childNodes[0] as VueElement
const spy = jest.fn()
e.addEventListener('my-click', spy)
e.shadowRoot!.childNodes[0].dispatchEvent(new CustomEvent('click'))
expect(spy).toHaveBeenCalled()
expect(spy.mock.calls[0][0]).toMatchObject({
detail: [1]
})
})
})
describe('slots', () => {
const E = defineCustomElement({
render() {
return [
h('div', null, [
renderSlot(this.$slots, 'default', undefined, () => [
h('div', 'fallback')
])
]),
h('div', null, renderSlot(this.$slots, 'named'))
]
}
})
customElements.define('my-el-slots', E)
test('default slot', () => {
container.innerHTML = `<my-el-slots><span>hi</span></my-el-slots>`
const e = container.childNodes[0] as VueElement
// native slots allocation does not affect innerHTML, so we just
// verify that we've rendered the correct native slots here...
expect(e.shadowRoot!.innerHTML).toBe(
`<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`
)
})
})
describe('provide/inject', () => {
const Consumer = defineCustomElement({
setup() {
const foo = inject<Ref>('foo')!
return () => h('div', foo.value)
}
})
customElements.define('my-consumer', Consumer)
test('over nested usage', async () => {
const foo = ref('injected!')
const Provider = defineCustomElement({
provide: {
foo
},
render() {
return h('my-consumer')
}
})
customElements.define('my-provider', Provider)
container.innerHTML = `<my-provider><my-provider>`
const provider = container.childNodes[0] as VueElement
const consumer = provider.shadowRoot!.childNodes[0] as VueElement
expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
foo.value = 'changed!'
await nextTick()
expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
})
test('over slot composition', async () => {
const foo = ref('injected!')
const Provider = defineCustomElement({
provide: {
foo
},
render() {
return renderSlot(this.$slots, 'default')
}
})
customElements.define('my-provider-2', Provider)
container.innerHTML = `<my-provider-2><my-consumer></my-consumer><my-provider-2>`
const provider = container.childNodes[0]
const consumer = provider.childNodes[0] as VueElement
expect(consumer.shadowRoot!.innerHTML).toBe(`<div>injected!</div>`)
foo.value = 'changed!'
await nextTick()
expect(consumer.shadowRoot!.innerHTML).toBe(`<div>changed!</div>`)
})
})
describe('styles', () => {
test('should attach styles to shadow dom', () => {
const Foo = defineCustomElement({
styles: [`div { color: red; }`],
render() {
return h('div', 'hello')
}
})
customElements.define('my-el-with-styles', Foo)
container.innerHTML = `<my-el-with-styles></my-el-with-styles>`
const el = container.childNodes[0] as VueElement
const style = el.shadowRoot?.querySelector('style')!
expect(style.textContent).toBe(`div { color: red; }`)
})
})
describe('async', () => {
test('should work', async () => {
const loaderSpy = jest.fn()
const E = defineCustomElement(
defineAsyncComponent(() => {
loaderSpy()
return Promise.resolve({
props: ['msg'],
styles: [`div { color: red }`],
render(this: any) {
return h('div', null, this.msg)
}
})
})
)
customElements.define('my-el-async', E)
container.innerHTML =
`<my-el-async msg="hello"></my-el-async>` +
`<my-el-async msg="world"></my-el-async>`
await new Promise(r => setTimeout(r))
// loader should be called only once
expect(loaderSpy).toHaveBeenCalledTimes(1)
const e1 = container.childNodes[0] as VueElement
const e2 = container.childNodes[1] as VueElement
// should inject styles
expect(e1.shadowRoot!.innerHTML).toBe(
`<style>div { color: red }</style><div>hello</div>`
)
expect(e2.shadowRoot!.innerHTML).toBe(
`<style>div { color: red }</style><div>world</div>`
)
// attr
e1.setAttribute('msg', 'attr')
await nextTick()
expect((e1 as any).msg).toBe('attr')
expect(e1.shadowRoot!.innerHTML).toBe(
`<style>div { color: red }</style><div>attr</div>`
)
// props
expect(`msg` in e1).toBe(true)
;(e1 as any).msg = 'prop'
expect(e1.getAttribute('msg')).toBe('prop')
expect(e1.shadowRoot!.innerHTML).toBe(
`<style>div { color: red }</style><div>prop</div>`
)
})
test('set DOM property before resolve', async () => {
const E = defineCustomElement(
defineAsyncComponent(() => {
return Promise.resolve({
props: ['msg'],
setup(props) {
expect(typeof props.msg).toBe('string')
},
render(this: any) {
return h('div', this.msg)
}
})
})
)
customElements.define('my-el-async-2', E)
const e1 = new E()
// set property before connect
e1.msg = 'hello'
const e2 = new E()
container.appendChild(e1)
container.appendChild(e2)
// set property after connect but before resolve
e2.msg = 'world'
await new Promise(r => setTimeout(r))
expect(e1.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
expect(e2.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
e1.msg = 'world'
expect(e1.shadowRoot!.innerHTML).toBe(`<div>world</div>`)
e2.msg = 'hello'
expect(e2.shadowRoot!.innerHTML).toBe(`<div>hello</div>`)
})
test('Number prop casting before resolve', async () => {
const E = defineCustomElement(
defineAsyncComponent(() => {
return Promise.resolve({
props: { n: Number },
setup(props) {
expect(props.n).toBe(20)
},
render(this: any) {
return h('div', this.n + ',' + typeof this.n)
}
})
})
)
customElements.define('my-el-async-3', E)
container.innerHTML = `<my-el-async-3 n="2e1"></my-el-async-3>`
await new Promise(r => setTimeout(r))
const e = container.childNodes[0] as VueElement
expect(e.shadowRoot!.innerHTML).toBe(`<div>20,number</div>`)
})
test('with slots', async () => {
const E = defineCustomElement(
defineAsyncComponent(() => {
return Promise.resolve({
render(this: any) {
return [
h('div', null, [
renderSlot(this.$slots, 'default', undefined, () => [
h('div', 'fallback')
])
]),
h('div', null, renderSlot(this.$slots, 'named'))
]
}
})
})
)
customElements.define('my-el-async-slots', E)
container.innerHTML = `<my-el-async-slots><span>hi</span></my-el-async-slots>`
await new Promise(r => setTimeout(r))
const e = container.childNodes[0] as VueElement
expect(e.shadowRoot!.innerHTML).toBe(
`<div><slot><div>fallback</div></slot></div><div><slot name="named"></slot></div>`
)
})
})
}) | the_stack |
import * as path from 'path'
import { basename } from 'path'
import * as util from 'util'
import generate from '@babel/generator'
import * as t from '@babel/types'
import { getStylesAtomic } from '@tamagui/core-node'
import { concatClassName } from '@tamagui/helpers'
import invariant from 'invariant'
import { getRemainingRequest } from 'loader-utils'
import { ViewStyle } from 'react-native'
import { ClassNameObject, StyleObject, TamaguiOptions } from '../types'
import { babelParse } from './babelParse'
import { buildClassName } from './buildClassName'
import { Extractor } from './createExtractor'
import { ensureImportingConcat } from './ensureImportingConcat'
import { isSimpleSpread } from './extractHelpers'
import { extractMediaStyle } from './extractMediaStyle'
import { hoistClassNames } from './hoistClassNames'
import { logLines } from './logLines'
export const CONCAT_CLASSNAME_IMPORT = 'concatClassName'
const mergeStyleGroups = {
shadowOpacity: true,
shadowRadius: true,
shadowColor: true,
shadowOffset: true,
}
export function extractToClassNames({
loader,
extractor,
source,
sourcePath,
options,
shouldPrintDebug,
threaded,
cssPath,
}: {
loader: any
extractor: Extractor
source: string | Buffer
sourcePath: string
options: TamaguiOptions
shouldPrintDebug: boolean
cssPath: string
threaded?: boolean
}): null | {
js: string | Buffer
styles: string
stylesPath?: string
ast: t.File
map: any // RawSourceMap from 'source-map'
} {
if (typeof source !== 'string') {
throw new Error('`source` must be a string of javascript')
}
invariant(
typeof sourcePath === 'string' && path.isAbsolute(sourcePath),
'`sourcePath` must be an absolute path to a .js file'
)
const shouldLogTiming = options.logTimings ?? true
const start = Date.now()
const mem = shouldLogTiming ? process.memoryUsage() : null
// Using a map for (officially supported) guaranteed insertion order
let ast: t.File
try {
// @ts-ignore
ast = babelParse(source)
} catch (err) {
console.error('babel parse error:', sourcePath)
throw err
}
const cssMap = new Map<string, { css: string; commentTexts: string[] }>()
const existingHoists: { [key: string]: t.Identifier } = {}
const res = extractor.parse(ast, {
sourcePath,
shouldPrintDebug,
...options,
getFlattenedNode: ({ tag }) => tag,
onExtractTag: ({
attrs,
node,
attemptEval,
jsxPath,
originalNodeName,
filePath,
lineNumbers,
programPath,
}) => {
let finalClassNames: ClassNameObject[] = []
let finalAttrs: (t.JSXAttribute | t.JSXSpreadAttribute)[] = []
let finalStyles: StyleObject[] = []
const viewStyles = {}
for (const attr of attrs) {
if (attr.type === 'style') {
Object.assign(viewStyles, attr.value)
}
}
const ensureNeededPrevStyle = (style: ViewStyle) => {
// ensure all group keys are merged
const keys = Object.keys(style)
if (!keys.some((key) => mergeStyleGroups[key])) {
return style
}
for (const k in mergeStyleGroups) {
if (k in viewStyles) {
style[k] = style[k] ?? viewStyles[k]
}
}
return style
}
const addStyles = (style: ViewStyle | null) => {
if (!style) return []
const styleWithPrev = ensureNeededPrevStyle(style)
const res = getStylesAtomic(styleWithPrev)
if (res.length) {
finalStyles = [...finalStyles, ...res]
}
return res
}
// 1 to start above any :hover styles
let lastMediaImportance = 1
for (const attr of attrs) {
switch (attr.type) {
case 'style':
const styles = addStyles(attr.value)
const newClassNames = concatClassName(styles.map((x) => x.identifier).join(' '))
// prettier-ignore
const existing = finalClassNames.find((x) => x.type == 'StringLiteral') as t.StringLiteral | null
if (existing) {
existing.value = `${existing.value} ${newClassNames}`
} else {
finalClassNames = [...finalClassNames, t.stringLiteral(newClassNames)]
}
if (shouldPrintDebug) {
// prettier-ignore
console.log(' classnames (after)\n', logLines(finalClassNames.map(x => x['value']).join(' ')))
}
break
case 'attr':
const val = attr.value
if (t.isJSXSpreadAttribute(val)) {
if (isSimpleSpread(val)) {
finalClassNames.push(
t.logicalExpression(
'&&',
val.argument,
t.memberExpression(val.argument, t.identifier('className'))
)
)
}
} else if (val.name.name === 'className') {
const value = val.value
if (value) {
try {
const evaluatedValue = attemptEval(value)
finalClassNames.push(t.stringLiteral(evaluatedValue))
} catch (e) {
finalClassNames.push(value['expression'])
}
}
continue
}
finalAttrs.push(val)
break
case 'ternary':
const mediaExtraction = extractMediaStyle(
attr.value,
jsxPath,
extractor.getTamagui(),
sourcePath,
lastMediaImportance,
shouldPrintDebug
)
if (mediaExtraction) {
lastMediaImportance++
finalStyles = [...finalStyles, ...mediaExtraction.mediaStyles]
finalClassNames = [
...finalClassNames,
...mediaExtraction.mediaStyles.map((x) => t.stringLiteral(x.identifier)),
]
if (!mediaExtraction.ternaryWithoutMedia) {
continue
}
}
const ternary = mediaExtraction?.ternaryWithoutMedia || attr.value
const consInfo = addStyles(ternary.consequent)
const altInfo = addStyles(ternary.alternate)
const cCN = consInfo.map((x) => x.identifier).join(' ')
const aCN = altInfo.map((x) => x.identifier).join(' ')
if (consInfo.length && altInfo.length) {
finalClassNames.push(
t.conditionalExpression(ternary.test, t.stringLiteral(cCN), t.stringLiteral(aCN))
)
} else {
finalClassNames.push(
t.conditionalExpression(
ternary.test,
t.stringLiteral(' ' + cCN),
t.stringLiteral(' ' + aCN)
)
)
}
break
}
}
node.attributes = finalAttrs
if (finalClassNames.length) {
// inserts the _cn variable and uses it for className
const names = buildClassName(finalClassNames)
const nameExpr = names ? hoistClassNames(jsxPath, existingHoists, names) : null
let expr = nameExpr
// if has some spreads, use concat helper
if (nameExpr && !t.isIdentifier(nameExpr)) {
ensureImportingConcat(programPath)
const simpleSpreads = attrs.filter(
(x) => t.isJSXSpreadAttribute(x.value) && isSimpleSpread(x.value)
)
expr = t.callExpression(t.identifier(CONCAT_CLASSNAME_IMPORT), [
expr,
...simpleSpreads.map((val) => val.value['argument']),
])
}
node.attributes.push(
t.jsxAttribute(t.jsxIdentifier('className'), t.jsxExpressionContainer(expr))
)
}
const comment = util.format('/* %s:%s (%s) */', filePath, lineNumbers, originalNodeName)
for (const { className, rules } of finalStyles) {
if (cssMap.has(className)) {
if (comment) {
const val = cssMap.get(className)!
val.commentTexts.push(comment)
cssMap.set(className, val)
}
} else if (rules.length) {
if (rules.length > 1) {
console.log(' rules error', { rules })
throw new Error(`Shouldn't have more than one rule`)
}
cssMap.set(className, {
css: rules[0],
commentTexts: [comment],
})
}
}
},
})
if (!res || (!res.modified && !res.optimized && !res.flattened)) {
if (shouldPrintDebug) {
console.log('no res or none modified', res)
}
return null
}
const styles = Array.from(cssMap.values())
.map((x) => x.css)
.join('\n')
.trim()
if (styles) {
const cssQuery = threaded
? `cssData=${Buffer.from(styles).toString('base64')}`
: `cssPath=${cssPath}`
const remReq = getRemainingRequest(loader)
const importPath = `${cssPath}!=!tamagui-loader?${cssQuery}!${remReq}`
ast.program.body.unshift(t.importDeclaration([], t.stringLiteral(importPath)))
}
const result = generate(
ast,
{
concise: false,
filename: sourcePath,
retainLines: false,
sourceFileName: sourcePath,
sourceMaps: true,
},
source
)
if (shouldPrintDebug) {
console.log(
'\n -------- output code ------- \n\n',
result.code
.split('\n')
.filter((x) => !x.startsWith('//'))
.join('\n')
)
console.log('\n -------- output style -------- \n\n', styles)
}
if (shouldLogTiming) {
const memUsed = mem
? Math.round(((process.memoryUsage().heapUsed - mem.heapUsed) / 1024 / 1204) * 10) / 10
: 0
const timing = `${Date.now() - start}`.padStart(3)
const path = basename(sourcePath).padStart(40)
const numOptimized = `${res.optimized}`.padStart(4)
const memory = memUsed > 10 ? `used ${memUsed}MB` : ''
console.log(
` 🥚 ${path} ${timing}ms ׁ· ${numOptimized} optimized · ${res.flattened} flattened ${memory}`
)
}
return {
ast,
styles,
js: result.code,
map: result.map,
}
} | the_stack |
// Copyright the Browserify authors. MIT License.
// Ported from https://github.com/browserify/path-browserify/
// This module is browser compatible.
import type { FormatInputPathObject, ParsedPath } from "./_interface.ts";
import { CHAR_DOT, CHAR_FORWARD_SLASH } from "./_constants.ts";
import {
_format,
assertPath,
encodeWhitespace,
isPosixPathSeparator,
normalizeString,
} from "./_util.ts";
export const sep = "/";
export const delimiter = ":";
// path.resolve([from ...], to)
/**
* Resolves `pathSegments` into an absolute path.
* @param pathSegments an array of path segments
*/
export function resolve(...pathSegments: string[]): string {
let resolvedPath = "";
let resolvedAbsolute = false;
for (let i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
let path: string;
if (i >= 0) path = pathSegments[i];
else {
// deno-lint-ignore no-explicit-any
const { Deno } = globalThis as any;
if (typeof Deno?.cwd !== "function") {
throw new TypeError("Resolved a relative path without a CWD.");
}
path = Deno.cwd();
}
assertPath(path);
// Skip empty entries
if (path.length === 0) {
continue;
}
resolvedPath = `${path}/${resolvedPath}`;
resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeString(
resolvedPath,
!resolvedAbsolute,
"/",
isPosixPathSeparator,
);
if (resolvedAbsolute) {
if (resolvedPath.length > 0) return `/${resolvedPath}`;
else return "/";
} else if (resolvedPath.length > 0) return resolvedPath;
else return ".";
}
/**
* Normalize the `path`, resolving `'..'` and `'.'` segments.
* @param path to be normalized
*/
export function normalize(path: string): string {
assertPath(path);
if (path.length === 0) return ".";
const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
const trailingSeparator =
path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH;
// Normalize the path
path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator);
if (path.length === 0 && !isAbsolute) path = ".";
if (path.length > 0 && trailingSeparator) path += "/";
if (isAbsolute) return `/${path}`;
return path;
}
/**
* Verifies whether provided path is absolute
* @param path to be verified as absolute
*/
export function isAbsolute(path: string): boolean {
assertPath(path);
return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH;
}
/**
* Join all given a sequence of `paths`,then normalizes the resulting path.
* @param paths to be joined and normalized
*/
export function join(...paths: string[]): string {
if (paths.length === 0) return ".";
let joined: string | undefined;
for (let i = 0, len = paths.length; i < len; ++i) {
const path = paths[i];
assertPath(path);
if (path.length > 0) {
if (!joined) joined = path;
else joined += `/${path}`;
}
}
if (!joined) return ".";
return normalize(joined);
}
/**
* Return the relative path from `from` to `to` based on current working directory.
* @param from path in current working directory
* @param to path in current working directory
*/
export function relative(from: string, to: string): string {
assertPath(from);
assertPath(to);
if (from === to) return "";
from = resolve(from);
to = resolve(to);
if (from === to) return "";
// Trim any leading backslashes
let fromStart = 1;
const fromEnd = from.length;
for (; fromStart < fromEnd; ++fromStart) {
if (from.charCodeAt(fromStart) !== CHAR_FORWARD_SLASH) break;
}
const fromLen = fromEnd - fromStart;
// Trim any leading backslashes
let toStart = 1;
const toEnd = to.length;
for (; toStart < toEnd; ++toStart) {
if (to.charCodeAt(toStart) !== CHAR_FORWARD_SLASH) break;
}
const toLen = toEnd - toStart;
// Compare paths to find the longest common path from root
const length = fromLen < toLen ? fromLen : toLen;
let lastCommonSep = -1;
let i = 0;
for (; i <= length; ++i) {
if (i === length) {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
// We get here if `from` is the exact base path for `to`.
// For example: from='/foo/bar'; to='/foo/bar/baz'
return to.slice(toStart + i + 1);
} else if (i === 0) {
// We get here if `from` is the root
// For example: from='/'; to='/foo'
return to.slice(toStart + i);
}
} else if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
// We get here if `to` is the exact base path for `from`.
// For example: from='/foo/bar/baz'; to='/foo/bar'
lastCommonSep = i;
} else if (i === 0) {
// We get here if `to` is the root.
// For example: from='/foo'; to='/'
lastCommonSep = 0;
}
}
break;
}
const fromCode = from.charCodeAt(fromStart + i);
const toCode = to.charCodeAt(toStart + i);
if (fromCode !== toCode) break;
else if (fromCode === CHAR_FORWARD_SLASH) lastCommonSep = i;
}
let out = "";
// Generate the relative path based on the path difference between `to`
// and `from`
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
if (out.length === 0) out += "..";
else out += "/..";
}
}
// Lastly, append the rest of the destination (`to`) path that comes after
// the common path parts
if (out.length > 0) return out + to.slice(toStart + lastCommonSep);
else {
toStart += lastCommonSep;
if (to.charCodeAt(toStart) === CHAR_FORWARD_SLASH) ++toStart;
return to.slice(toStart);
}
}
/**
* Resolves path to a namespace path
* @param path to resolve to namespace
*/
export function toNamespacedPath(path: string): string {
// Non-op on posix systems
return path;
}
/**
* Return the directory name of a `path`.
* @param path to determine name for
*/
export function dirname(path: string): string {
assertPath(path);
if (path.length === 0) return ".";
const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
let end = -1;
let matchedSlash = true;
for (let i = path.length - 1; i >= 1; --i) {
if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
if (!matchedSlash) {
end = i;
break;
}
} else {
// We saw the first non-path separator
matchedSlash = false;
}
}
if (end === -1) return hasRoot ? "/" : ".";
if (hasRoot && end === 1) return "//";
return path.slice(0, end);
}
/**
* Return the last portion of a `path`. Trailing directory separators are ignored.
* @param path to process
* @param ext of path directory
*/
export function basename(path: string, ext = ""): string {
if (ext !== undefined && typeof ext !== "string") {
throw new TypeError('"ext" argument must be a string');
}
assertPath(path);
let start = 0;
let end = -1;
let matchedSlash = true;
let i: number;
if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
if (ext.length === path.length && ext === path) return "";
let extIdx = ext.length - 1;
let firstNonSlashEnd = -1;
for (i = path.length - 1; i >= 0; --i) {
const code = path.charCodeAt(i);
if (code === CHAR_FORWARD_SLASH) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else {
if (firstNonSlashEnd === -1) {
// We saw the first non-path separator, remember this index in case
// we need it if the extension ends up not matching
matchedSlash = false;
firstNonSlashEnd = i + 1;
}
if (extIdx >= 0) {
// Try to match the explicit extension
if (code === ext.charCodeAt(extIdx)) {
if (--extIdx === -1) {
// We matched the extension, so mark this as the end of our path
// component
end = i;
}
} else {
// Extension does not match, so our result is the entire path
// component
extIdx = -1;
end = firstNonSlashEnd;
}
}
}
}
if (start === end) end = firstNonSlashEnd;
else if (end === -1) end = path.length;
return path.slice(start, end);
} else {
for (i = path.length - 1; i >= 0; --i) {
if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// path component
matchedSlash = false;
end = i + 1;
}
}
if (end === -1) return "";
return path.slice(start, end);
}
}
/**
* Return the extension of the `path`.
* @param path with extension
*/
export function extname(path: string): string {
assertPath(path);
let startDot = -1;
let startPart = 0;
let end = -1;
let matchedSlash = true;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
let preDotState = 0;
for (let i = path.length - 1; i >= 0; --i) {
const code = path.charCodeAt(i);
if (code === CHAR_FORWARD_SLASH) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === CHAR_DOT) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1) startDot = i;
else if (preDotState !== 1) preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (
startDot === -1 ||
end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
(preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
) {
return "";
}
return path.slice(startDot, end);
}
/**
* Generate a path from `FormatInputPathObject` object.
* @param pathObject with path
*/
export function format(pathObject: FormatInputPathObject): string {
if (pathObject === null || typeof pathObject !== "object") {
throw new TypeError(
`The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`,
);
}
return _format("/", pathObject);
}
/**
* Return a `ParsedPath` object of the `path`.
* @param path to process
*/
export function parse(path: string): ParsedPath {
assertPath(path);
const ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" };
if (path.length === 0) return ret;
const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH;
let start: number;
if (isAbsolute) {
ret.root = "/";
start = 1;
} else {
start = 0;
}
let startDot = -1;
let startPart = 0;
let end = -1;
let matchedSlash = true;
let i = path.length - 1;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
let preDotState = 0;
// Get non-dir info
for (; i >= start; --i) {
const code = path.charCodeAt(i);
if (code === CHAR_FORWARD_SLASH) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === CHAR_DOT) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1) startDot = i;
else if (preDotState !== 1) preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (
startDot === -1 ||
end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
(preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
) {
if (end !== -1) {
if (startPart === 0 && isAbsolute) {
ret.base = ret.name = path.slice(1, end);
} else {
ret.base = ret.name = path.slice(startPart, end);
}
}
} else {
if (startPart === 0 && isAbsolute) {
ret.name = path.slice(1, startDot);
ret.base = path.slice(1, end);
} else {
ret.name = path.slice(startPart, startDot);
ret.base = path.slice(startPart, end);
}
ret.ext = path.slice(startDot, end);
}
if (startPart > 0) ret.dir = path.slice(0, startPart - 1);
else if (isAbsolute) ret.dir = "/";
return ret;
}
/**
* Converts a file URL to a path string.
*
* fromFileUrl("file:///home/foo"); // "/home/foo"
* @param url of a file URL
*/
export function fromFileUrl(url: string | URL): string {
url = url instanceof URL ? url : new URL(url);
if (url.protocol != "file:") {
throw new TypeError("Must be a file URL.");
}
return decodeURIComponent(
url.pathname.replace(/%(?![0-9A-Fa-f]{2})/g, "%25"),
);
}
/**
* Converts a path string to a file URL.
*
* toFileUrl("/home/foo"); // new URL("file:///home/foo")
* @param path to convert to file URL
*/
export function toFileUrl(path: string): URL {
if (!isAbsolute(path)) {
throw new TypeError("Must be an absolute path.");
}
const url = new URL("file:///");
url.pathname = encodeWhitespace(
path.replace(/%/g, "%25").replace(/\\/g, "%5C"),
);
return url;
} | the_stack |
import {
Error as ErrorMsg,
GroupAgg,
HandleData, Histogram,
Message, ModifyStream,
QuantileBin, Sample, SampleN,
Select,
TableOp
} from "../data/messages";
import {DataType, DoubleType, LongType, NumericTypes, StructField, StructType, UnsafeLongType} from "../data/data_type";
import {DataReader, Pair} from "../data/codec";
import {Either} from "../data/codec_types";
import match from "../util/match";
import {StreamingDataRepr} from "../data/value_repr";
import {NotebookMessageDispatcher,} from "./dispatcher";
import {Disposable, IDisposable, removeKey, StateHandler} from "../state";
import {NotebookState, NotebookStateHandler} from "../state/notebook_state";
import {deepCopy, removeKeys} from "../util/helpers";
export const QuartilesType = new StructType([
new StructField("min", DoubleType),
new StructField("q1", DoubleType),
new StructField("median", DoubleType),
new StructField("mean", DoubleType),
new StructField("q3", DoubleType),
new StructField("max", DoubleType)
]);
/**
* An API for streaming data out of a StreamingDataRepr
*/
export class DataStream extends Disposable {
private readonly mods: TableOp[];
readonly dataType: DataType;
private batchSize = 50;
private receivedCount = 0;
terminated = false;
private stopAfter = Infinity;
private listener?: (batch: any[]) => void;
private runListener?: (batch: any[]) => void;
private onComplete?: <T>(value?: T | PromiseLike<T>) => void;
private _onError: (reason?: any) => void = _ => {};
private nextPromise?: {resolve: <T>(value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void}; // holds a Promise's `resolve` and `reject` inputs.
private setupPromise?: Promise<Message | void>;
private repr: StreamingDataRepr;
private activeStreams: StateHandler<NotebookState["activeStreams"]>;
private observer?: IDisposable;
constructor(
private readonly dispatcher: NotebookMessageDispatcher,
private readonly nbState: NotebookStateHandler,
private readonly originalRepr: StreamingDataRepr,
mods?: TableOp[],
currentDataType?: DataType,
private unsafeLongs: boolean = false
) {
super();
this.repr = originalRepr;
this.dataType = currentDataType ?? originalRepr.dataType;
this.mods = mods ?? [];
this.activeStreams = nbState.lens("activeStreams").disposeWith(this);
}
private attachListener() {
if (this.observer) {
this.observer.tryDispose();
}
this.observer = this.activeStreams.addObserver(handles => {
const data = handles[this.repr.handle];
if (data && data.length > 0) {
data.forEach(message => {
match(message)
.when(HandleData, (handleType, handleId, count, data) => {
if (handleType === StreamingDataRepr.handleTypeId && handleId === this.repr.handle) {
const succeed = (data: ArrayBuffer[]) => {
const batch = this.decodeValues(data);
if (this.nextPromise) {
this.nextPromise.resolve(batch);
this.nextPromise = undefined;
}
this.terminated = batch.length < count;
if (this.listener) this.listener(batch);
if (this.runListener) this.runListener(batch);
if (this.terminated) {
this.kill();
}
};
const fail = (err: ErrorMsg) => this._onError(err);
Either.fold(data, fail, succeed);
} else {
throw new Error(`Unexpected HandleData message! ${[handleType, handleId, count, data]}`)
}
})
.when(ModifyStream, (fromHandle, ops, newRepr) => {
if (newRepr) {
this.repr = newRepr
}
})
})
// clear messages now that they have been processed.
this.activeStreams.update(() => removeKey(this.repr.handle))
}
})
}
batch(batchSize: number) {
if (batchSize < 0) {
throw "Expected batch size > 0"
}
this.batchSize = batchSize;
return this;
}
to<T>(fn: (t: T[]) => void) {
this.listener = (batch: T[]) => {fn(batch)};
return this;
}
limit(n: number) {
this.stopAfter = n;
return this;
}
kill() {
this.terminated = true;
if (this.repr.handle != this.originalRepr.handle) {
this.dispatcher.stopDataStream(StreamingDataRepr.handleTypeId, this.repr.handle)
}
if (this.observer) {
this.observer.dispose();
}
if (this.onComplete) {
this.onComplete();
}
if (this.nextPromise) {
this.nextPromise.reject("Stream was terminated")
}
this.tryDispose();
}
private withOps(ops: TableOp[], forceUnsafeLongs?: boolean): DataStream {
const newType = DataStream.finalDataType(this.dataType, ops);
return new DataStream(this.dispatcher, this.nbState, this.originalRepr, [...this.mods, ...ops], newType, forceUnsafeLongs ?? this.unsafeLongs);
}
aggregate(groupCols: string[], aggregations: Record<string, string> | Record<string, string>[]): DataStream {
if (!(this.dataType instanceof StructType))
return this;
if (!(aggregations instanceof Array)) {
aggregations = [aggregations];
}
const fields = this.dataType.fields;
const aggPairs = aggregations.flatMap(agg => {
const pairs = [];
for (let key of Object.keys(agg)) {
if (!fields.find((field: StructField) => field.name === key)) {
throw new Error(`Field ${key} not present in data type`);
}
pairs.push(new Pair(key, agg[key]));
}
return pairs;
});
const mod = new GroupAgg(groupCols, aggPairs);
return this.withOps([mod]);
}
bin(col: string, binCount: number, err?: number) {
if (err === undefined) {
err = 1.0 / binCount;
}
const field = this.requireField(col);
if (NumericTypes.indexOf(field.dataType) < 0) {
throw new Error(`Field ${col} must be a numeric type to use bin()`);
}
const mod = new QuantileBin(col, binCount, err);
return this.withOps([mod]);
}
select(...cols: string[]) {
const fields = cols.map(col => this.requireField(col));
const mod = new Select(cols);
return this.withOps([mod]);
}
/**
* Sample (without replacement) at the given rate
* @param sampleRate sample rate, 0 < n < 1
*/
sample(sampleRate: number) {
return this.withOps([new Sample(sampleRate)]);
}
/**
* Sample (without replacement) approximately n items
* @param n The number of items to sample
*/
sampleN(n: number) {
return this.withOps([new SampleN(n)]);
}
histogram(field: string, binCount: number) {
binCount = Math.floor(binCount);
return this.withOps([new Histogram(field, binCount)]);
}
useUnsafeLongs() {
return this.withOps([], true);
}
onError(fn: (cause: any) => void) {
const prevOnError = this._onError;
this._onError = prevOnError ? (cause: any) => { prevOnError(cause); fn(cause); } : fn;
}
/**
* Run the stream until it's killed or it completes
*/
run() {
if (this.runListener) {
throw "Stream is already running";
}
this.runListener = <T>(batch: T[]) => {
this.receivedCount += batch.length;
if (this.receivedCount >= this.stopAfter) {
this.kill();
}
if (!this.terminated) {
this._requestNext();
}
};
return this.setupStream().then(() => new Promise((resolve, reject) => {
this.onComplete = resolve;
const prevOnError = this._onError;
this._onError = prevOnError ? (cause: any) => { prevOnError(cause); reject(cause) } : reject;
this._requestNext();
}));
}
abort() {
this.dispatcher.cancelTasks()
this.kill();
}
/**
* Fetch the next batch from the stream, for a stream that isn't being automatically run via run()
*/
requestNext() {
if (this.runListener) {
throw "Stream is already running";
}
if (this.nextPromise) {
throw "Next batch is already being awaited";
}
return this.setupStream().then(_ => new Promise(
(resolve, reject) => {
this.nextPromise = {resolve, reject};
this._requestNext();
}
));
}
private _requestNext() {
this.dispatcher.requestDataBatch(StreamingDataRepr.handleTypeId, this.repr.handle, this.batchSize)
}
private decodeValues(data: ArrayBuffer[]) {
return data.map(buf => this.repr.dataType.decodeBuffer(new DataReader(buf)));
}
private setupStream() {
if (!this.setupPromise) {
this.setupPromise = new Promise<ModifyStream>((resolve, reject) => {
const handleId = this.repr.handle;
this.dispatcher.modifyDataStream(handleId, this.mods)
const obs = this.activeStreams.addObserver(handles => {
const messages = handles[handleId]
if (messages.length > 0) {
messages.forEach(message => {
if (message instanceof ModifyStream && message.fromHandle === handleId) {
if (message.newRepr) {
if (this.unsafeLongs) {
let newDataType = message.newRepr.dataType;
if (newDataType instanceof StructType)
newDataType = newDataType.replaceType(typ => typ === LongType ? UnsafeLongType : undefined);
else if (newDataType === LongType)
newDataType = UnsafeLongType;
this.repr = new StreamingDataRepr(
message.newRepr.handle,
newDataType,
message.newRepr.knownSize)
} else {
this.repr = message.newRepr;
}
}
resolve(message)
obs.dispose();
}
})
}
})
}).then(message => {
this.attachListener();
return message;
})
}
return this.setupPromise;
}
private static finalDataType(type: DataType, mods: TableOp[]): DataType {
if (!(type instanceof StructType)) {
return type;
}
let dataType: StructType = type;
if (!mods || !mods.length)
return dataType;
for (let mod of mods) {
match(mod)
.when(GroupAgg, (groupCols: string[], aggregations: Pair<string, string>[]) => {
const groupFields = groupCols.map(name => DataStream.requireField(dataType, name));
const aggregateFields = aggregations.map(pair => {
const [name, agg] = Pair.unapply(pair);
let aggregatedType = DataStream.requireField(dataType, name).dataType;
switch (agg) {
case "count":
case "approx_count_distinct":
aggregatedType = LongType;
break;
case "quartiles":
aggregatedType = QuartilesType;
break;
case "mean":
aggregatedType = DoubleType;
break;
}
return new StructField(`${agg}(${name})`, aggregatedType);
});
dataType = new StructType([...groupFields, ...aggregateFields]);
})
.when(QuantileBin, (column: string, binCount: number, _) => {
dataType = new StructType([...dataType.fields, new StructField(`${column}_quantized`, DoubleType)]);
})
.when(Select, (columns: string[]) => {
const fields = columns.map(name => DataStream.requireField(dataType, name));
dataType = new StructType(fields);
})
.when(Histogram, () => Histogram.dataType);
}
return dataType;
}
private requireField(name: string) {
return DataStream.requireField(this.dataType, name);
}
private static requireField(dataType: DataType, name: string): StructField {
if (!(dataType instanceof StructType)) {
throw new Error(`Field ${name} not present in scalar type ${dataType.typeName()}`);
}
const path = name.indexOf('(') >= 0 ? [name] : name.split('.');
const fieldName = path.shift();
const field = dataType.fields.find((field: StructField) => field.name === fieldName);
if (!field) {
throw new Error(`Field ${name} not present in data type`);
}
if (!path.length) {
return field;
} else if (field.dataType instanceof StructType) {
return DataStream.requireField(field.dataType, path.join('.'));
} else {
throw new Error(`No field ${path[0]} in ${fieldName} (${field.dataType.typeName()} is not a struct)`)
}
}
} | the_stack |
import {
isDevMode,
ComponentFactoryResolver,
HostListener,
ViewContainerRef,
ElementRef,
Component,
OnInit,
OnDestroy,
ApplicationRef,
Optional,
Inject,
NgZone,
Injector,
ViewChild,
Input,
Output,
EventEmitter,
StaticProvider,
Type,
ComponentRef,
SkipSelf,
} from '@angular/core';
import GoldenLayout from 'golden-layout';
import { ComponentRegistryService } from './component-registry.service';
import { FallbackComponent, FailedComponent } from './fallback';
import { RootWindowService } from './root-window.service';
import { Observable, Subscription, BehaviorSubject, of, Subject } from 'rxjs';
import { switchMap, takeUntil, distinctUntilChanged } from 'rxjs/operators';
import {
implementsGlOnResize,
implementsGlOnShow,
implementsGlOnHide,
implementsGlOnTab,
implementsGlOnClose,
implementsGlOnPopin,
implementsGlOnUnload,
implementsGlOnPopout,
uuid,
} from './type-guards';
import { Deferred } from './deferred';
import { WindowSynchronizerService } from './window-sync.service';
import {
GoldenLayoutContainer,
GoldenLayoutComponentState,
GoldenLayoutEventHub,
GoldenLayoutComponentHost
} from './tokens';
import { IExtendedGoldenLayoutConfig } from './config';
interface ComponentInitCallback extends Function {
(container: GoldenLayout.Container, componentState: any): void;
}
// We need to wrap some golden layout internals, so we can intercept close and 'close stack'
// For close, the tab is wrapped and the close element to change the event handler to close the correct container.
const lm = GoldenLayout as any;
const isCloned = (contentItem: GoldenLayout.ContentItem) => contentItem.isComponent &&
contentItem.config &&
(contentItem.config as GoldenLayout.ComponentConfig).componentState &&
(contentItem.config as GoldenLayout.ComponentConfig).componentState.originalId;
export const GetComponentFromLayoutManager = (lm: GoldenLayout, id: string): GoldenLayout.ContentItem => {
const itemList = lm.root.getItemsById(id);
if (itemList.length !== 1) {
console.warn('non unique ID found: ' + id);
return undefined;
}
return itemList[0];
};
const originalComponent = (contentItem: GoldenLayout.ContentItem): any => {
const comp = GetComponentFromLayoutManager(
contentItem.layoutManager,
(contentItem.config as GoldenLayout.ComponentConfig).componentState.originalId,
);
if (!comp.isComponent) {
throw new Error('Expected component');
}
return comp;
};
const tabFromId = (contentItem: GoldenLayout.ContentItem) => {
const ci = originalComponent(contentItem);
return ci ? ci.tab : undefined;
};
// This code wraps the original golden-layout Tab
// A tab is instantiated by the golden-layout Header
// We rebind the close event listener to properly dispose the angular item container
// In order to destroy the angular component ref and be able to defer the close.
const originalTab = lm.__lm.controls.Tab;
const newTab = function(header, tabContentItem) {
const tab = new originalTab(header, tabContentItem);
/**
* This piece of code implements close functionality for the tab close.
* If we have a cloned tab, i.e. one which is contained in a maximised dummy stack
* we close the container backing the tab.
*/
tab.closeElement.off('click touchstart');
tab.closeElement.on('click touchstart', (ev) => {
ev.stopPropagation();
if (isCloned(tab.contentItem)) {
const c = originalComponent(tab.contentItem);
if (c && c.isComponent) {
// If we have a dummy tab, close the actual tab behind it.
c.container.close();
}
} else {
// Otherwise close our own tab.
tab.contentItem.container.close();
}
});
/**
* This script emits a tabActivated event for the correct content item
* when running in a maximised dummy stack.
*/
tab.element.on('mousedown touchstart', ev => {
let contentItem = tab.contentItem;
if (isCloned(contentItem)) {
contentItem = originalComponent(tab.contentItem);
}
contentItem.layoutManager.emit('tabActivated', contentItem);
});
if (isCloned(tab.contentItem) && tab._layoutManager.config.settings.reorderEnabled === true) {
// Reimplement tab drag start by redirecting the tab state.
tab.element.on('mousedown touchstart', (ev) => {
const originalTab = tabFromId(tab.contentItem);
if (originalTab && originalTab._dragListener) {
const dl = originalTab._dragListener;
const destroyDummy = () => {
dl.off('dragStart', destroyDummy, dl);
if (header.layoutManager._maximisedItem === tab.contentItem.parent) {
tab.contentItem.parent.toggleMaximise();
}
};
dl.off('dragStart', originalTab._onDragStart, originalTab);
dl.on('dragStart', destroyDummy, dl);
dl.on('dragStart', originalTab._onDragStart, originalTab);
dl._fDown(ev);
}
});
}
return tab;
};
newTab._template = '<li class="lm_tab"><i class="lm_left"></i>' +
'<span class="lm_title"></span><div class="lm_close_tab"></div>' +
'<i class="lm_right"></i></li>';
lm.__lm.controls.Tab = newTab;
// Header is wrapped to catch the maximise and close buttons.
const originalHeader = lm.__lm.controls.Header;
const newHeader = function(layoutManager, parent) {
const maximise = parent._header['maximise'];
const popout = parent._header['popout'];
if (maximise && layoutManager.config.settings.maximiseAllItems === true) {
// Check whether we should maximise all stacks and if so, force the header to
// not generate a maximise button.
delete parent._header['maximise'];
}
if (popout && layoutManager.config.settings.maximiseAllItems === true) {
delete parent._header['popout'];
}
// Generate the original header
const header = new originalHeader(layoutManager, parent);
// Check whether we should maximise all stacks, and if so, generate a custom popout button
// but keep the order with the maximise and close button
if (popout && layoutManager.config.settings.maximiseAllItems === true) {
header.popoutButton = new lm.__lm.controls.HeaderButton(header, popout, 'lm_popout', () => {
let contentItem = header.activeContentItem;
if (isCloned(contentItem)) {
// We are within the dummy stack, our component is a wrapper component
// and has a reference to the original (= wrapped) component.
// Therefore, popping out the whole stack would be stupid, because it wouldn't leave
// any item in this window.
contentItem = originalComponent(contentItem);
contentItem.popout();
} else if (layoutManager.config.settings.popoutWholeStack === true) {
// We have a regular stack, so honor the popoutWholeStack setting.
header.parent.popout();
} else {
contentItem.popout();
}
});
}
// Check whether we should maximise all stacks, and if so, generate a custom maximise button
// but keep the order with the close button.
if (maximise && layoutManager.config.settings.maximiseAllItems === true) {
header.maximiseButton = new lm.__lm.controls.HeaderButton(header, maximise, 'lm_maximise', () => {
// The maximise button was clicked, so create a dummy stack, containing a wrapper component for each opened component.
if (layoutManager._maximisedItem === parent) {
parent.toggleMaximise();
} else {
layoutManager.generateAndMaximiseDummyStack(parent);
}
});
}
if (header.closeButton) {
header.closeButton._$destroy();
const label = header._getHeaderSetting('close');
header.closeButton = new lm.__lm.controls.HeaderButton(header, label, 'lm_close', () => {
header.parent.contentItems.forEach(ci => {
ci.container.close();
});
});
}
return header;
};
newHeader._template = [
'<div class="lm_header">',
'<ul class="lm_tabs"></ul>',
'<ul class="lm_controls"></ul>',
'<ul class="lm_tabdropdown_list"></ul>',
'</div>'
].join( '' );
lm.__lm.controls.Header = newHeader;
// Patch the drag proxy in order to have an itemDragged event.
const origDragProxy = lm.__lm.controls.DragProxy;
const dragProxy = function(x, y, dragListener, layoutManager, contentItem, originalParent) {
layoutManager.emit('itemDragged', contentItem);
return new origDragProxy(x, y, dragListener, layoutManager, contentItem, originalParent);
}
dragProxy._template = origDragProxy._template;
lm.__lm.controls.DragProxy = dragProxy;
// Patch the stack in order to have an activeContentItemChanged$ observable
const origStack = lm.__lm.items.Stack;
function MyStack(lm, config, parent) {
origStack.call(this, lm, config, parent);
this.activeContentItem$ = new BehaviorSubject<any>(null);
const callback = (ci) => {
if (this.activeContentItem$) {
this.activeContentItem$.next(ci)
};
};
this.on('activeContentItemChanged', callback);
const origDestroy = this._$destroy;
this.___destroyed = false;
this._$destroy = () => {
if (this.___destroyed) {
return;
}
this.___destroyed = true;
this.off('activeContentItemChanged', callback);
this.activeContentItem$.complete();
this.activeContentItem$ = null;
origDestroy.call(this);
};
return this;
}
MyStack.prototype = Object.create(origStack.prototype);
// Force stacks to be flattened.
MyStack.prototype['addChild'] = function(contentItem: GoldenLayout.ItemConfig, index: number) {
if (contentItem.type === 'stack') {
// We try to pop in a stack into another stack (i.e. nested tab controls.)
// This breaks the other stuff in custom header components, therefore it's not recommended.
// So we add the items directly into this stack.
(contentItem.content || []).forEach((ci, idx) => origStack.prototype.addChild.call(this, ci, index + idx));
if (contentItem.content.length) {
this.setActiveContentItem(this.contentItems[index + (contentItem as any).activeItemIndex]);
}
} else {
origStack.prototype.addChild.call(this, contentItem, index);
}
};
MyStack.prototype['setSize'] = function() {
if (this.layoutManager._maximisedItem === this && this.layoutManager.config.settings.maximiseAllItems === true) {
// Actually enforce that this item will be the correct size
this.element.width(this.layoutManager.container.width());
this.element.height(this.layoutManager.container.height());
}
origStack.prototype.setSize.call(this);
};
lm.__lm.items.Stack = MyStack;
const origPopout = lm.__lm.controls.BrowserPopout;
const popout = function(config: GoldenLayout.ItemConfig[], dimensions, parent, index, lm) {
if (config.length !== 1) {
console.warn('This should not happen, permitting', config);
} else {
if (config[0].type === 'component') {
config = [{
type: 'stack',
title: config[0].title, // Required for adjustToWindowMode to work. (Line 1282 in 1.5.9)
content: [config[0]],
}];
}
}
return new origPopout(config, dimensions, parent, index, lm);
};
lm.__lm.controls.BrowserPopout = popout;
// Fixup for nested golden-layout instances.
// nested instances should be able to be docked out completely
// but the golden layout will recognize its query string and be incorrectly nested.
const getQueryStringParam = lm.__lm.utils.getQueryStringParam;
let firstQueryString = true;
lm.__lm.utils.getQueryStringParam = (param: string) => {
if (firstQueryString) {
firstQueryString = false;
return getQueryStringParam(param);
}
return null;
}
@Component({
selector: 'golden-layout-root',
styles: [`
.ng-golden-layout-root {
width:100%;
height:100%;
}`
],
template: `<div class="ng-golden-layout-root" #glroot></div>`
})
export class GoldenLayoutComponent implements OnInit, OnDestroy {
@Input() layout: Observable<IExtendedGoldenLayoutConfig>;
@Output() stateChanged = new EventEmitter<never>();
@Output() tabActivated = new EventEmitter<GoldenLayout.ContentItem>();
@ViewChild('glroot', { static: true }) private el: ElementRef;
private goldenLayout: GoldenLayout = null;
private onUnloaded = new Deferred<void>();
private stateChangePaused = false;
private stateChangeScheduled = false;
private tabsList = new BehaviorSubject<{ [tabId: string]: GoldenLayout.ContentItem }>({});
pushStateChange = () => {
// For each state change, we want to refresh the list of the opened components. At the moment, we only care about the keys.
this.tabsList.next((this.goldenLayout as any)._getAllComponents());
if (this.stateChangePaused || this.stateChangeScheduled) {
return;
}
this.stateChangeScheduled = true;
window.requestAnimationFrame(() => {
this.stateChangeScheduled = false;
this.stateChanged.emit()
});
};
resumeStateChange = () => this.stateChangePaused = false;
pauseStateChange = () => this.stateChangePaused = true;
pushTabActivated = (ci: GoldenLayout.ContentItem) => {
this.tabActivated.emit(ci);
}
private fallbackType: ComponentInitCallback = null;
private layoutSubscription: Subscription;
private openedComponents = [];
private poppedIn = false;
private _eventEmitter = new lm.__lm.utils.EventEmitter();
@HostListener('window:resize')
public onResize(): void {
if (this.goldenLayout) {
this.goldenLayout.updateSize();
}
}
constructor(
private rootService: RootWindowService,
private componentRegistry: ComponentRegistryService,
private viewContainer: ViewContainerRef,
private componentFactoryResolver: ComponentFactoryResolver,
private ngZone: NgZone,
private readonly injector: Injector,
private windowSync: WindowSynchronizerService,
@Optional() @SkipSelf() private parentGoldenLayout: GoldenLayoutComponent,
@Optional() @Inject(FallbackComponent) private readonly fallbackComponent: any
) {
console.log(parentGoldenLayout);
if (!!this.fallbackComponent) {
this.fallbackType = this.buildConstructor(this.fallbackComponent);
}
if (isDevMode()) console.log(`Create@${this.rootService.isChildWindow ? 'child' : 'root'}!`);
}
public ngOnInit(): void {
if (isDevMode()) console.log(`Init@${this.rootService.isChildWindow ? 'child' : 'root'}!`);
this.layoutSubscription = this.layout.subscribe(layout => {
this.destroyGoldenLayout();
this.initializeGoldenLayout(layout);
});
}
// Map beforeunload to onDestroy to simplify the handling
@HostListener('window:beforeunload')
public beforeUnload() {
if (this.poppedIn) {
this.onUnloaded.promise.then(() => this.ngOnDestroy());
this.onUnloaded.resolve();
this.windowSync.onUnload();
}
}
// Map beforeunload to onDestroy to simplify the handling
@HostListener('window:pagehide')
public pageHide() {
if (!this.poppedIn) {
this.openedComponents.forEach(c => {
if (implementsGlOnUnload(c)) {
c.glOnUnload();
}
});
}
this.onUnloaded.promise.then(() => this.ngOnDestroy());
this.onUnloaded.resolve();
this.windowSync.onUnload();
}
public ngOnDestroy(): void {
if (isDevMode()) {
console.log(`Destroy@${this.rootService.isChildWindow ? 'child' : 'root'}!`);
}
this.layoutSubscription.unsubscribe();
// restore the original tick method.
// this appens in two cases:
// either the window is closed, after that it's not important to restore the tick method
// or within the root window, where we HAVE to restore the original tick method
this.windowSync.restoreAppRefTick();
this.destroyGoldenLayout();
// Discard all previously made subscriptions.
this._eventEmitter._mSubscriptions = { [lm.__lm.utils.EventEmitter.ALL_EVENT]: [] };
}
public getGoldenLayoutInstance(): GoldenLayout {
if (!this.goldenLayout) {
throw new Error('Component is not initialized yet');
}
return this.goldenLayout;
}
public addEvent(kind: string, callback: Function, context?: any) {
this._eventEmitter.on(kind, callback, context);
}
public getSerializableState(): any {
if (this.goldenLayout) {
const configObj = this.goldenLayout.toConfig();
const wrapperMax = (this.goldenLayout as any).__wrapperMaximisedItemId;
if (wrapperMax) {
configObj.maximisedItemId = wrapperMax;
const filterContent = (ci) => {
if (ci.type === 'stack' && ci.isDummy) {
return false;
}
if (ci.type !== 'component') {
ci.content = ci.content.filter(filterContent);
}
return true;
}
configObj.content = configObj.content.filter(filterContent);
}
return configObj;
}
return null;
}
public getComponents(): { [id: string]: GoldenLayout.ContentItem } {
return (this.goldenLayout as any)._getAllComponents();
}
public closeComponent(component: string) {
const c = GetComponentFromLayoutManager(this.goldenLayout, component);
if (!c) {
return;
}
c.remove();
}
public focusComponent(component: string) {
const c = GetComponentFromLayoutManager(this.goldenLayout, component);
if (!c) {
return;
}
c.parent.setActiveContentItem(c);
}
public createNewComponent(config: GoldenLayout.ComponentConfig, componentToDock?: string): Promise<ComponentRef<any>> {
if (!this.goldenLayout) {
throw new Error("golden layout is not initialized");
}
let myConfig: GoldenLayout.ItemConfig = config;
const root = this.goldenLayout.root;
let element: GoldenLayout.ContentItem = null;
if (componentToDock) {
const c = GetComponentFromLayoutManager(this.goldenLayout, componentToDock);
if (c.parent.isStack) {
element = c.parent;
} else {
const stack = this.goldenLayout.createContentItem({
type: 'stack',
width: c.parent.config.width,
height: c.parent.config.height,
content: [],
}) as any;
(c.parent.replaceChild as any)(c, stack, false);
stack.addChild(c);
element = stack;
}
} else {
if (!root.contentItems || root.contentItems.length === 0) {
element = root;
// Ensure there is a stack when closing ALL items and creating a new item.
myConfig = {
type: 'stack',
content: [{
...myConfig,
type: 'component',
}],
};
} else {
element = this.findStack(root.contentItems);
}
}
if (element === null) {
throw new Error("this should never happen!");
}
const content = this.goldenLayout.createContentItem(myConfig) as any;
element.addChild(content);
if (content.isComponent) {
// Usually
return content.instance;
} else if (content.isStack && content.contentItems.length === 1) {
return content.contentItems[0].instance; // The case when this is the first component.
} else {
return content;
}
}
private findStack(contentItems: GoldenLayout.ContentItem[]): GoldenLayout.ContentItem {
if (!contentItems) {
return null;
}
for (const x of contentItems) {
if (x.isStack) {
if ((x.config as any).isDummy) {
continue;
}
return x;
}
const s = this.findStack(x.contentItems);
if (s !== null) {
return s;
}
}
}
private destroyGoldenLayout(): void {
if (!this.goldenLayout) {
return;
}
this.goldenLayout.off('stateChanged', this.pushStateChange);
this.goldenLayout.off('itemDropped', this.resumeStateChange);
this.goldenLayout.off('itemDragged', this.pauseStateChange);
this.goldenLayout.off('tabActivated', this.pushTabActivated);
this.goldenLayout.off('initialised');
this.goldenLayout.off(lm.__lm.utils.EventEmitter.ALL_EVENT, this._eventEmitter.emit, this._eventEmitter);
this.goldenLayout.destroy();
this.goldenLayout = null;
}
private initializeGoldenLayout(layout: any): void {
this.goldenLayout = new GoldenLayout(layout, $(this.el.nativeElement));
const origPopout = this.goldenLayout.createPopout.bind(this.goldenLayout);
this.goldenLayout.createPopout = (item: GoldenLayout.ContentItem, dim, parent, index) => {
/**
* Traverse the component tree below the item we're trying to pop out.
* This has basically two cases:
* a) we have a component to popout (or end up at a component somewhen)
* for components, contentItems is either undefined or empty, so ignore it
* during the children push.
* however, for components, we need to check for glOnPopout and call it.
* b) everything else, where contentItems is a non-empty array.
* For these parts, we need to consider all children recursively.
*
* Here, an iterative algorithm was chosen.
*/
const rec = [item];
while(rec.length) {
const itemToProcess = rec.shift();
if (itemToProcess.contentItems && itemToProcess.contentItems.length > 0) {
rec.push(...itemToProcess.contentItems);
}
if (itemToProcess.isComponent) {
const component = (itemToProcess as any).container.__ngComponent;
if (component && implementsGlOnPopout(component)) {
component.glOnPopout();
}
}
}
return origPopout(item, dim, parent, index);
}
/**
* buildComponentMap creates an object of all opened components below the given item.
* object keys are component IDs, object values the component with the ID.
*/
const buildComponentMap = (item: GoldenLayout.ContentItem) => {
let ret = {};
for (const ci of item.contentItems) {
if (ci.isComponent) {
if (ci.config && (ci.config as any).componentState && (ci.config as any).componentState.originalId) {
// Skip the dummy components
continue;
}
ret[ci.id] = ci;
} else {
ret = { ...ret, ...buildComponentMap(ci) };
}
}
return ret;
};
(this.goldenLayout as any)._getAllComponents = () => buildComponentMap(this.goldenLayout.root);
(this.goldenLayout as any).generateAndMaximiseDummyStack = (parent, item) => {
/**
* This function creates a dummy stack, which is being used if 'maximiseAllItems' is true.
* The dummy stack contains a dummy component for each component opened in the real layout.
* It will furthermore track component closes/spawns and create/close the dummy components accordingly.
* parent is the parent of the item we want to maximise
* item is the item which was active when we wanted to maximise it.
* required to set the active item index.
*/
const openedComponents = buildComponentMap(this.goldenLayout.root);
const componentIdList = Object.keys(openedComponents);
if (componentIdList.length === 0) {
return; // How did we get here?!
}
// We only have a single child, so we restore the original behavior
const rootContentItem = this.goldenLayout.root.contentItems[0];
if (rootContentItem.isStack) {
rootContentItem.toggleMaximise();
return;
}
/**
* At this point, there are at least two children, so use the dummy component.
*/
const config = {
type: 'stack',
content: componentIdList.map(k => ({
type: 'component',
componentName: 'gl-wrapper',
title: openedComponents[k].config.title,
reorderEnabled: false,
componentState: {
originalId: k, // pass in the ID of the original component as parameter.
},
})),
isClosable: false,
isDummy: true,
state: 'dummy',
activeItemIndex: componentIdList.findIndex(j => j === (item || parent._activeContentItem.id)),
}
// add this item as first child ever, causing golden-layout to create a stack object
rootContentItem.addChild(config, 0);
// Fetch the stack
const myStack = rootContentItem.contentItems[0] as GoldenLayout.ContentItem;
// Setup an __wrapperMaximisedItemId in order to setActiveContentItem on the underlying stack later.
(this.goldenLayout as any).__wrapperMaximisedItemId = parent._activeContentItem.id;
(myStack as any).activeContentItem$.subscribe((ci) => {
// Setup the __wrapperMaximisedItemId lateron.
(this.goldenLayout as any).__wrapperMaximisedItemId = ci.config.componentState.originalId;
});
const teardown$ = new Subject<void>();
myStack.on('minimised', () => {
// Dummy stack was minimised, so enforce all dummy components to be disposed
// and dispose the dummy stack as well.
(this.goldenLayout as any).__wrapperMaximisedItemId = null;
teardown$.next();
teardown$.complete();
myStack.remove()
});
// Maximise the dummy stack.
myStack.toggleMaximise();
// Whenever a tab is being created or closed, perform a diff algorithm
// on the active tabs list and create or delete the dummy tabs.
this.tabsList.pipe(
takeUntil(teardown$),
distinctUntilChanged((a, b) => {
const keysA = Object.keys(a);
const keysB = new Set(Object.keys(b));
return keysA.length === keysB.size && keysA.every(key => keysB.has(key));
}),
).subscribe(targetState => {
const workingCopy = { ...targetState };
const tabs = new Set(Object.keys(workingCopy));
// currently opened tabs
const openedTabs = new Set(myStack.contentItems.map(ci => {
return (ci.config as any).componentState.originalId;
}));
for (const key of tabs) {
if (openedTabs.has(key)) {
// item is both currently opened in dummy and background, nothing to do
openedTabs.delete(key);
} else {
// item is not opened in dummy, create a component
myStack.addChild({
type: 'component',
componentName: 'gl-wrapper',
title: targetState[key].config.title,
reorderEnabled: false,
componentState: {
originalId: key,
},
} as any)
}
}
// The remaining tabs are opened in the dummy but not in the background, so close the dummy.
for (const tab of openedTabs) {
const tabObj = myStack.contentItems.find(j => (j.config as any).componentState.originalId === tab);
tabObj.remove();
}
});
};
this.goldenLayout.on('popIn', () => {
this.poppedIn = true;
this.openedComponents.forEach(c => {
if (implementsGlOnPopin(c)) {
c.glOnPopin();
}
});
});
// Overwrite the 'getComponent' method to dynamically resolve JS components.
// We need to do this, because the component map is not flexible enough for us since we can dynamically chainload plugins.
this.goldenLayout.getComponent = (type) => {
if (isDevMode()) {
console.log(`Resolving component ${type}`);
}
return this.buildConstructor(type);
};
this.goldenLayout.on('stackCreated', (stack) => {
const customHeaderElement = document.createElement('li');
customHeaderElement.classList.add('custom-header');
customHeaderElement.style.display = 'none';
const ctr = stack.header.controlsContainer[0] as HTMLUListElement;
let element: ComponentRef<any> = null;
ctr.prepend(customHeaderElement);
const disposeControl = () => {
customHeaderElement.style.display = 'none';
if (element) {
customHeaderElement.childNodes.forEach(e => customHeaderElement.removeChild(e));
element.destroy();
element = null;
stack.header._updateTabSizes();
}
};
const bootstrapComponent = (ct: Type<any>, tokens: StaticProvider[], injector: Injector) => {
if (element) {
disposeControl();
}
customHeaderElement.style.display = '';
const factory = this.componentFactoryResolver.resolveComponentFactory(ct);
const headerInjector = Injector.create(tokens, injector);
element = this.viewContainer.createComponent(factory, undefined, headerInjector);
customHeaderElement.prepend(element.location.nativeElement);
stack.header._updateTabSizes();
};
// Wait until the content item is loaded and done
stack.activeContentItem$.pipe(
switchMap((contentItem: GoldenLayout.ContentItem) => {
if (!contentItem || !contentItem.isComponent) {
return of(null);
}
return (contentItem as any).instance || of(null);
}), switchMap((cr: ComponentRef<any> | null) => {
if (!cr) {
return Promise.all([null, null, null]);
}
const inst = cr.instance.headerComponent;
const tokens = cr.instance.additionalTokens;
return Promise.all([
Promise.resolve(inst),
Promise.resolve(tokens),
Promise.resolve(cr)
]);
})
).subscribe(([header, tokens, componentRef]) => {
// This is the currently visible content item, after it's loaded.
// Therefore, we can check whether (and what) to render as header component here.
if (!header || !componentRef) {
disposeControl();
} else {
bootstrapComponent(
header,
tokens || [],
componentRef.injector
);
}
}, disposeControl, disposeControl);
});
// Initialize the layout.
this.goldenLayout.on('initialised', () => {
window.requestAnimationFrame(() => {
if (layout.maximisedItemId) {
const c = GetComponentFromLayoutManager(this.goldenLayout, layout.maximisedItemId);
if (c) {
(this.goldenLayout as any).generateAndMaximiseDummyStack(c.parent, layout.maximisedItemId);
}
}
});
});
this.goldenLayout.init();
this.goldenLayout.on('stateChanged', this.pushStateChange);
this.goldenLayout.on('itemDragged', this.pauseStateChange);
this.goldenLayout.on('itemDropped', this.resumeStateChange);
this.goldenLayout.on('tabActivated', this.pushTabActivated);
this.goldenLayout.on(lm.__lm.utils.EventEmitter.ALL_EVENT, this._eventEmitter.emit, this._eventEmitter);
this._eventEmitter.emit('initialised');
}
/**
* Build a 'virtual' constructor which is used to pass the components to goldenLayout
* @param componentType
*/
private buildConstructor(componentName: string): ComponentInitCallback {
// Can't use an ES6 lambda here, since it is not a constructor
const self = this;
return function (container: GoldenLayout.Container, componentState: any) {
const glComponent = container.parent;
if (glComponent.config.id) {
glComponent.id = glComponent.config.id as string;
} else {
glComponent.id = uuid();
glComponent.config.id = glComponent.id;
}
const d = new Deferred<any>();
self.ngZone.run(() => {
// Wait until the component registry can provide a type for the component
// TBD: Maybe add a timeout here?
const componentPromise = self.componentRegistry.waitForComponent(componentName);
componentPromise.then((componentType) => {
// We got our component type
if (isDevMode()) {
console.log(`Component ${componentName} returned from componentRegistry`);
}
// Create an instance of the angular component.
const factory = self.componentFactoryResolver.resolveComponentFactory(componentType);
let failedComponent: string = null;
if (componentType === self.fallbackComponent) {
// Failed to find the component constructor **AND** we have a fallback component defined,
// so lookup the failed component's name and inject it into the fallback component.
failedComponent = (container as any)._config.componentName;
}
const injector = self._createComponentInjector(container, componentState, failedComponent);
const componentRef = self.viewContainer.createComponent(factory, undefined, injector);
// Bind the new component to container's client DOM element.
container.getElement().append($(componentRef.location.nativeElement));
self._bindEventHooks(container, componentRef.instance);
(container as any).__ngComponent = componentRef.instance;
self.openedComponents.push(componentRef.instance);
let destroyed = false;
const destroyFn = () => {
if (!destroyed) {
destroyed = true;
self.openedComponents = self.openedComponents.filter(i => i !== componentRef.instance);
$(componentRef.location.nativeElement).remove();
componentRef.destroy();
}
};
// Listen to containerDestroy and window beforeunload, preventing a double-destroy
container.on('destroy', destroyFn);
self.onUnloaded.promise.then(destroyFn);
d.resolve(componentRef);
});
});
return d.promise;
};
}
/**
* Creates an injector capable of injecting the GoldenLayout object,
* component container, and initial component state.
*/
private _createComponentInjector(
container: GoldenLayout.Container,
componentState: any,
failed: string | null,
): Injector {
const providers = [
{
provide: GoldenLayoutContainer,
useValue: container,
},
{
provide: GoldenLayoutComponentState,
useValue: componentState,
},
{
provide: GoldenLayoutEventHub,
useValue: this.goldenLayout.eventHub,
},
{
provide: GoldenLayoutComponentHost,
useValue: this,
}
];
if (!!failed) {
providers.push({
provide: FailedComponent,
useValue: failed,
});
}
return Injector.create(providers, this.injector);
}
/**
* Registers an event handler for each implemented hook.
* @param container Golden Layout component container.
* @param component Angular component instance.
*/
private _bindEventHooks(container: GoldenLayout.Container, component: any): void {
if (implementsGlOnResize(component)) {
container.on('resize', () => {
component.glOnResize();
});
}
if (implementsGlOnShow(component)) {
container.on('show', () => {
component.glOnShow();
});
}
if (implementsGlOnHide(component)) {
container.on('hide', () => {
component.glOnHide();
});
}
if (implementsGlOnTab(component)) {
container.on('tab', (tab) => {
component.glOnTab(tab);
});
}
if (implementsGlOnClose(component)) {
const containerClose = container.close.bind(container);
container.close = () => {
if (!(container as any)._config.isClosable) {
return false;
}
component.glOnClose().then(() => {
containerClose();
}, () => { /* Prevent close, don't care about rejections */ });
};
}
}
} | the_stack |
import * as angular from 'angular';
import { ListItemSelectModeEnum } from './listItemSelectModeEnum';
import { ListItemTypeEnum } from './listItemTypeEnum';
import { ListLayoutEnum } from './listLayoutEnum';
describe('listDirective: <uif-list />', () => {
let element: JQuery;
let scope: any;
beforeEach(() => {
angular.mock.module('officeuifabric.core');
angular.mock.module('officeuifabric.components.list');
});
beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: Function) => {
scope = $rootScope;
}));
it('should render list using a ul tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list></uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0).prop('tagName')).toEqual('UL');
}));
it(
'should set correct Office UI Fabric classes on the list',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list></uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0)).toHaveClass('ms-List');
expect(element.children().eq(0)).not.toHaveClass('ms-List--grid');
}));
it(
'should throw an error on an invalid value for the \'uif-layout\' attribute',
inject(($compile: Function, $rootScope: angular.IRootScopeService, $log: angular.ILogService) => {
element = angular.element('<div>\
<uif-list uif-layout="invalid"></uif-list>\
<uif-list uif-layout="grid"></uif-list>\
<uif-list uif-layout="list"></uif-list>\
</div>');
$compile(element)(scope);
scope.$digest();
expect($log.error.logs.length).toEqual(1);
}));
it(
'should use the list layout as default if no list layout has been specified',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list></uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0)).not.toHaveClass('ms-List--grid');
}));
it(
'should set correct Office UI Fabric classes on the list ' +
'displayed as grid',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list uif-layout="grid"></uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0)).toHaveClass('ms-List--grid');
}));
it(
'should throw an error on an invalid value for the \'uif-item-select-mode\' attribute',
inject(($compile: Function, $rootScope: angular.IRootScopeService, $log: angular.ILogService) => {
element = angular.element('<div>\
<uif-list uif-item-select-mode="invalid"></uif-list>\
<uif-list uif-item-select-mode="none"></uif-list>\
<uif-list uif-item-select-mode="single"></uif-list>\
<uif-list uif-item-select-mode="multiple"></uif-list>\
</div>');
$compile(element)(scope);
scope.$digest();
expect($log.error.logs.length).toEqual(1);
}));
it('should render the list item using a li tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list><uif-list-item></uif-list-item></uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0).children().eq(0).children().eq(0).prop('tagName')).toEqual('LI');
}));
it(
'should set correct Office UI Fabric classes on the list item',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list><uif-list-item></uif-list-item></uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0).children().eq(0).children().eq(0)).toHaveClass('ms-ListItem');
}));
it(
'should throw an error on an invalid value for the \'uif-selected\' attribute',
inject(($compile: Function, $rootScope: angular.IRootScopeService, $log: angular.ILogService) => {
element = angular.element('<uif-list><uif-list-item uif-selected="invalid"></uif-list-item></uif-list>');
$compile(element)(scope);
scope.$digest();
expect($log.error.logs.length).toEqual(1);
}));
it(
'should throw an error on an invalid value for the \'uif-type\' attribute',
inject(($compile: Function, $rootScope: angular.IRootScopeService, $log: angular.ILogService) => {
element = angular.element('<uif-list>\
<uif-list-item uif-type="invalid"></uif-list-item>\
<uif-list-item uif-type="item"></uif-list-item>\
<uif-list-item uif-type="itemWithIcon"></uif-list-item>\
<uif-list-item uif-type="itemWithImage"></uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
let numTypeErrors: number = 0;
for (let i: number = 0; i < $log.error.logs.length; i++) {
if ($log.error.logs[i][0].indexOf('uif-type') > -1) {
numTypeErrors++;
}
}
expect(numTypeErrors).toEqual(1);
}));
it(
'should set correct Office UI Fabric classes on list items with icon',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item uif-type="itemWithIcon"></uif-list-item>\
<uif-list-item uif-type="item"></uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.find('li').length).toEqual(2);
expect(element.find('li')[0]).toHaveClass('ms-ListItem--document');
expect(element.find('li')[1]).not.toHaveClass('ms-ListItem--document');
}));
it(
'should throw an error when using item of type itemWithIcon ' +
'without a child uif-list-item-icon directive',
inject(($compile: Function, $rootScope: angular.IRootScopeService, $log: angular.ILogService) => {
element = angular.element('<uif-list>\
<uif-list-item uif-type="itemWithIcon"></uif-list-item>\
<uif-list-item uif-type="itemWithIcon">\
<uif-list-item-icon></uif-list-item-icon>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
let numErrors: number = 0;
for (let i: number = 0; i < $log.error.logs.length; i++) {
if ($log.error.logs[i][0].indexOf('uif-list-item-icon') > -1) {
numErrors++;
}
}
expect(numErrors).toEqual(1);
}));
it(
'should set correct Office UI Fabric classes on list items with image',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item uif-type="itemWithImage"></uif-list-item>\
<uif-list-item uif-type="item"></uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.find('li').length).toEqual(2);
expect(element.find('li')[0]).toHaveClass('ms-ListItem--image');
expect(element.find('li')[1]).not.toHaveClass('ms-ListItem--image');
}));
it(
'should throw an error when using item of type itemWithImage ' +
'without a child uif-list-item-image directive',
inject(($compile: Function, $rootScope: angular.IRootScopeService, $log: angular.ILogService) => {
element = angular.element('<uif-list>\
<uif-list-item uif-type="itemWithImage"></uif-list-item>\
<uif-list-item uif-type="itemWithImage">\
<uif-list-item-image></uif-list-item-image>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
let numErrors: number = 0;
for (let i: number = 0; i < $log.error.logs.length; i++) {
if ($log.error.logs[i][0].indexOf('uif-list-item-image') > -1) {
numErrors++;
}
}
expect(numErrors).toEqual(1);
}));
it(
'should throw an error on an invalid value for the \'uif-unread\' attribute',
inject(($compile: Function, $rootScope: angular.IRootScopeService, $log: angular.ILogService) => {
element = angular.element('<uif-list><uif-list-item uif-unread="invalid"></uif-list-item></uif-list>');
$compile(element)(scope);
scope.$digest();
expect($log.error.logs.length).toEqual(1);
}));
it(
'should throw an error on an invalid value for the \'uif-unseen\' attribute',
inject(($compile: Function, $rootScope: angular.IRootScopeService, $log: angular.ILogService) => {
element = angular.element('<uif-list><uif-list-item uif-unseen="invalid"></uif-list-item></uif-list>');
$compile(element)(scope);
scope.$digest();
expect($log.error.logs.length).toEqual(1);
}));
it(
'should not allow to select items by default', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
scope.selectedItems = [];
element = angular.element('<uif-list uif-selected-items="selectedItems">\
<uif-list-item ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-list-item>\
</uif-list>');
$compile(element)(scope);
element = jQuery(element[0]);
scope.$digest();
let firstDataItem: JQuery = element.children().eq(0).children().eq(0);
firstDataItem.click();
expect(scope.selectedItems.length).toEqual(0);
}));
it('should allow to explicitly disable item selecting', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
scope.selectedItems = [];
element = angular.element('<uif-list uif-item-select-mode="none" uif-selected-items="selectedItems">\
<uif-list-item ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-list-item>\
</uif-list>');
$compile(element)(scope);
element = jQuery(element[0]);
scope.$digest();
let firstDataItem: JQuery = element.children().eq(0).children().eq(0);
firstDataItem.click();
expect(scope.selectedItems.length).toEqual(0);
}));
it(
'for item select mode \'single\' should allow to select single item',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
scope.selectedItems = [];
element = angular.element('<uif-list uif-item-select-mode="single" uif-selected-items="selectedItems">\
<uif-list-item ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-list-item>\
</uif-list>');
$compile(element)(scope);
element = jQuery(element[0]);
scope.$digest();
let firstDataItem: JQuery = element.children().eq(0).children().eq(0);
let secondDataItem: JQuery = element.children().eq(0).children().eq(1);
firstDataItem.click();
secondDataItem.click();
expect(scope.selectedItems.length).toEqual(1);
}));
it(
'for item select mode \'single\' should return the correct selected item',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
scope.selectedItems = [];
element = angular.element('<uif-list uif-item-select-mode="single" uif-selected-items="selectedItems">\
<uif-list-item ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-list-item>\
</uif-list>');
$compile(element)(scope);
element = jQuery(element[0]);
scope.$digest();
let secondDataItem: JQuery = element.children().eq(0).children().eq(1);
secondDataItem.click();
expect(scope.selectedItems[0]).toEqual(2);
}));
it(
'for item select mode \'single\' should preselect the correct item',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
scope.items = [1, 2, 3];
scope.selectedItems = [scope.items[1]];
element = angular.element('<uif-list uif-item-select-mode="single" uif-selected-items="selectedItems">\
<uif-list-item ng-repeat="n in items" uif-item="n"></uif-list-item>\
</uif-list>');
$compile(element)(scope);
element = jQuery(element[0]);
scope.$digest();
expect(scope.selectedItems.length).toEqual(1);
expect(scope.selectedItems[0]).toEqual(2);
}));
it(
'for item mode select \'multiple\' should allow to select multiple items',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
scope.selectedItems = [];
element = angular.element('<uif-list uif-item-select-mode="multiple" uif-selected-items="selectedItems">\
<uif-list-item ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-list-item>\
</uif-list>');
$compile(element)(scope);
element = jQuery(element[0]);
scope.$digest();
let firstDataItem: JQuery = element.children().eq(0).children().eq(0);
let secondDataItem: JQuery = element.children().eq(0).children().eq(1);
firstDataItem.click();
secondDataItem.click();
expect(scope.selectedItems.length).toEqual(2);
}));
it(
'for item select mode \'multiple\' should return the correct selected items',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
scope.selectedItems = [];
element = angular.element('<uif-list uif-item-select-mode="multiple" uif-selected-items="selectedItems">\
<uif-list-item ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-list-item>\
</uif-list>');
$compile(element)(scope);
element = jQuery(element[0]);
scope.$digest();
let firstDataItem: JQuery = element.children().eq(0).children().eq(0);
let secondDataItem: JQuery = element.children().eq(0).children().eq(1);
firstDataItem.click();
secondDataItem.click();
expect(scope.selectedItems[0]).toEqual(1);
expect(scope.selectedItems[1]).toEqual(2);
}));
it(
'for item select mode \'multiple\' should preselect the correct items',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
scope.items = [1, 2, 3];
scope.selectedItems = [scope.items[1]];
element = angular.element('<uif-list uif-item-select-mode="multiple" uif-selected-items="selectedItems">\
<uif-list-item ng-repeat="n in items" uif-item="n"></uif-list-item>\
</uif-list>');
$compile(element)(scope);
element = jQuery(element[0]);
scope.$digest();
expect(scope.selectedItems.length).toEqual(1);
expect(scope.selectedItems[0]).toEqual(2);
}));
it(
'should set correct Office UI Fabric classes on the selected and unselected list items',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list><uif-list-item></uif-list-item>\
<uif-list-item uif-selected="true"></uif-list-item><uif-list-item uif-selected="false"></uif-list-item></uif-list>');
$compile(element)(scope);
scope.$digest();
let items: JQuery = element.children().eq(0).children();
expect(items.length).toEqual(3);
expect(items.eq(0).children().eq(0)).not.toHaveClass('is-selected');
expect(items.eq(1).children().eq(0)).toHaveClass('is-selected');
expect(items.eq(2).children().eq(0)).not.toHaveClass('is-selected');
}));
it(
'should set correct Office UI Fabric classes on the read and unread list items',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list><uif-list-item></uif-list-item>\
<uif-list-item uif-unread="true"></uif-list-item><uif-list-item uif-unread="false"></uif-list-item></uif-list>');
$compile(element)(scope);
scope.$digest();
let items: JQuery = element.children().eq(0).children();
expect(items.length).toEqual(3);
expect(items.eq(0).children().eq(0)).not.toHaveClass('is-unread');
expect(items.eq(1).children().eq(0)).toHaveClass('is-unread');
expect(items.eq(2).children().eq(0)).not.toHaveClass('is-unread');
}));
it(
'should set correct Office UI Fabric classes on the seen and unseen list items',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list><uif-list-item></uif-list-item>\
<uif-list-item uif-unseen="true"></uif-list-item><uif-list-item uif-unseen="false"></uif-list-item></uif-list>');
$compile(element)(scope);
scope.$digest();
let items: JQuery = element.children().eq(0).children();
expect(items.length).toEqual(3);
expect(items.eq(0).children().eq(0)).not.toHaveClass('is-unseen');
expect(items.eq(1).children().eq(0)).toHaveClass('is-unseen');
expect(items.eq(2).children().eq(0)).not.toHaveClass('is-unseen');
}));
it(
'should set correct Office UI Fabric classes on list items that can be selected',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list uif-item-select-mode="single">\
<uif-list-item></uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
let items: JQuery = element.children().eq(0).children();
expect(items.length).toEqual(1);
expect(items.eq(0).children().eq(0)).toHaveClass('is-selectable');
}));
it(
'should render list item primary text using a span tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-primary-text></uif-list-item-primary-text>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-primary-text
.children().eq(0).prop('tagName')).toEqual('SPAN');
}));
it(
'should set correct Office UI Fabric classes on ' +
'list item primary text',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-primary-text></uif-list-item-primary-text>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-primary-text
.children().eq(0)).toHaveClass('ms-ListItem-primaryText');
}));
it('should render list item secondary text using a span tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-secondary-text></uif-list-item-secondary-text>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-secondary-text
.children().eq(0).prop('tagName')).toEqual('SPAN');
}));
it(
'should set correct Office UI Fabric classes on ' +
'list item secondary text',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-secondary-text></uif-list-item-secondary-text>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-secondary-text
.children().eq(0)).toHaveClass('ms-ListItem-secondaryText');
}));
it('should render list item tertiary text using a span tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-tertiary-text></uif-list-item-tertiary-text>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-tertiary-text
.children().eq(0).prop('tagName')).toEqual('SPAN');
}));
it(
'should set correct Office UI Fabric classes on ' +
'list item tertiary text',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-tertiary-text></uif-list-item-tertiary-text>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-tertiary-text
.children().eq(0)).toHaveClass('ms-ListItem-tertiaryText');
}));
it('should render list item meta text using a span tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-meta-text></uif-list-item-meta-text>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-meta-text
.children().eq(0).prop('tagName')).toEqual('SPAN');
}));
it(
'should set correct Office UI Fabric classes on ' +
'list item meta text',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-meta-text></uif-list-item-meta-text>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-meta-text
.children().eq(0)).toHaveClass('ms-ListItem-metaText');
}));
it('should render list item image using a div tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-image></uif-list-item-image>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-image
.children().eq(0).prop('tagName')).toEqual('DIV');
}));
it(
'should set correct Office UI Fabric classes on ' +
'list item image',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-image></uif-list-item-image>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-image
.children().eq(0)).toHaveClass('ms-ListItem-image');
}));
it('should render list item icon using a div tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-icon></uif-list-item-icon>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-icon
.children().eq(0).prop('tagName')).toEqual('DIV');
}));
it(
'should set correct Office UI Fabric classes on ' +
'list item icon',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-icon></uif-list-item-icon>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-icon
.children().eq(0)).toHaveClass('ms-ListItem-itemIcon');
}));
it('should render list item selection target using a div tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-selection-target></uif-list-item-selection-target>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-selection-target
.children().eq(0).prop('tagName')).toEqual('DIV');
}));
it(
'should set correct Office UI Fabric classes on ' +
'list item selection target',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-selection-target></uif-list-item-selection-target>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-selection-target
.children().eq(0)).toHaveClass('ms-ListItem-selectionTarget');
}));
it('should render list item actions using a div tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-actions></uif-list-item-actions>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-actions
.children().eq(0).prop('tagName')).toEqual('DIV');
}));
it(
'should set correct Office UI Fabric classes on ' +
'list item actions',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-actions></uif-list-item-actions>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-actions
.children().eq(0)).toHaveClass('ms-ListItem-actions');
}));
it('should render list item action using a div tag', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-actions>\
<uif-list-item-action></uif-list-item-action>\
</uif-list-item-actions>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-actions
.children().eq(0) // div.ms-ListItem-actions
.children().eq(0) // uif-list-item-action
.children().eq(0).prop('tagName')).toEqual('DIV');
}));
it(
'should set correct Office UI Fabric classes on ' +
'list item action',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
element = angular.element('<uif-list>\
<uif-list-item>\
<uif-list-item-actions>\
<uif-list-item-action></uif-list-item-action>\
</uif-list-item-actions>\
</uif-list-item>\
</uif-list>');
$compile(element)(scope);
scope.$digest();
expect(element.children().eq(0) // ul
.children().eq(0) // uif-list-item
.children().eq(0) // li
.children().eq(0) // uif-list-item-actions
.children().eq(0) // div.ms-ListItem-actions
.children().eq(0) // uif-list-item-action
.children().eq(0)).toHaveClass('ms-ListItem-action');
}));
/**
* test different selection modes: single / multiple
*/
it(
'should allow interpolation of list select mode value',
inject((
$compile: angular.ICompileService,
$rootScope: angular.IRootScopeService) => {
let subjectElement: JQuery,
firstListItem: JQuery,
secondListItem: JQuery = null;
let html: string = `
<uif-list uif-item-select-mode="{{type}}" uif-selected-items="selectedItems">
<uif-list-item ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-list-item>
</uif-list>`;
let ngElement: JQuery = angular.element(html);
let localScope: any = $rootScope.$new();
$compile(ngElement)(localScope);
// setup scope
localScope.type = undefined;
localScope.selectedItems = [];
// >>> test 1
localScope.type = ListItemSelectModeEnum[ListItemSelectModeEnum.single];
localScope.selectedItems = [];
// run digest cycle
localScope.$digest();
subjectElement = jQuery(ngElement[0]);
// test for correct setting
// >>>> try to select two+ items...
firstListItem = subjectElement.children().eq(0).children().eq(0);
firstListItem.click();
secondListItem = subjectElement.children().eq(0).children().eq(1);
secondListItem.click();
// >>>> ... test how many selected
expect(localScope.selectedItems.length).toEqual(1);
// >>> test 2
localScope.type = ListItemSelectModeEnum[ListItemSelectModeEnum.multiple];
localScope.selectedItems = [];
// run digest cycle
scope.$digest();
element = jQuery(ngElement[0]);
// test for correct setting
// >>>> try to select two+ items...
firstListItem = subjectElement.children().eq(0).children().eq(0);
firstListItem.click();
secondListItem = subjectElement.children().eq(0).children().eq(1);
secondListItem.click();
// >>>> ... test how many selected
expect(localScope.selectedItems.length).toEqual(2);
}));
/**
* test two layout types: grid / list
*/
it(
'should allow interpolation of list display mode value',
inject((
$compile: angular.ICompileService,
$rootScope: angular.IRootScopeService) => {
let subjectElement: JQuery = null;
let html: string = `
<uif-list uif-layout="{{type}}">
<uif-list-item ng-repeat="n in [1, 2, 3]" uif-item="n"></uif-list-item>
</uif-list>`;
let ngElement: JQuery = angular.element(html);
let localScope: any = $rootScope.$new();
$compile(ngElement)(localScope);
// >>> test 1
localScope.type = ListLayoutEnum[ListLayoutEnum.list];
// run digest cycle
localScope.$digest();
subjectElement = jQuery(ngElement[0]).find('ul');
// test for correct setting
expect(subjectElement).toHaveClass('ms-List');
expect(subjectElement).not.toHaveClass('ms-List--grid');
// >>> test 2
localScope.type = ListLayoutEnum[ListLayoutEnum.grid];
// run digest cycle
localScope.$digest();
subjectElement = jQuery(ngElement[0]).find('ul');
// test for correct setting
expect(subjectElement).toHaveClass('ms-List');
expect(subjectElement).toHaveClass('ms-List--grid');
}));
/**
* test different ways to render list items: with icon / image
*/
it(
'should allow interpolation of list item display mode value',
inject((
$compile: angular.ICompileService,
$rootScope: angular.IRootScopeService) => {
let subjectElement: JQuery = null;
let html: string = `
<uif-list>
<uif-list-item-image><img ng-src="image.png" /></uif-list-item-image>
<uif-list-item-icon><uif-icon uif-type="mail"></uif-icon></uif-list-item-icon>
<uif-list-item uif-type="{{type}}"></uif-list-item>
</uif-list>`;
let ngElement: JQuery = angular.element(html);
let localScope: any = $rootScope.$new();
$compile(ngElement)(localScope);
// >>> test 1
localScope.type = ListItemTypeEnum[ListItemTypeEnum.itemWithIcon];
// run digest cycle
localScope.$digest();
subjectElement = jQuery(ngElement[0]);
// test for correct setting
expect(subjectElement.find('li')).toHaveClass('ms-ListItem--document');
// >>> test 2
localScope.type = ListItemTypeEnum[ListItemTypeEnum.itemWithImage];
// run digest cycle
localScope.$digest();
subjectElement = jQuery(ngElement[0]);
// test for correct setting
expect(subjectElement.children().eq(0).children().eq(2).children().eq(0)).toHaveClass('ms-ListItem--image');
expect(subjectElement.find('li')).toHaveClass('ms-ListItem--image');
}));
}); | the_stack |
import React from 'react';
import {
ParallaxProps,
BgImageProp,
BgImageSrcSetProp,
BgImageSizesProp,
Parallax as ParallaxClass,
SplitChildrenResultType,
StyleObjectType,
} from '../../@types';
import {
getRelativePosition,
getSplitChildren,
getHasDynamicBlur,
getBlurValue,
} from '../utils/parallax';
import { getNodeHeight, canUseDOM, isScrolledIntoView } from '../utils/dom';
import ParallaxChildren from './ParallaxChildren';
const initialStyle = {
position: 'absolute',
left: '50%',
WebkitTransform: 'translate3d(-50%, 0, 0)',
transform: 'translate3d(-50%, 0, 0)',
WebkitTransformStyle: 'preserve-3d',
WebkitBackfaceVisibility: 'hidden',
MozBackfaceVisibility: 'hidden',
MsBackfaceVisibility: 'hidden',
};
class Parallax extends ParallaxClass {
bg: HTMLDivElement;
canUseDOM: boolean;
contentHeight: number;
contentWidth: number;
node: HTMLElement;
content: HTMLElement;
img: HTMLImageElement;
bgImageLoaded: boolean;
bgImageRef: HTMLImageElement;
parent: HTMLElement | Document;
parentHeight: number;
timestamp: number;
isDynamicBlur: boolean;
static defaultProps = {
bgClassName: 'react-parallax-bgimage',
bgImageAlt: '',
className: '',
contentClassName: '',
disabled: false,
strength: 100,
};
constructor(props: ParallaxProps) {
super(props);
this.state = {
bgImage: props.bgImage,
bgImageSrcSet: props.bgImageSrcSet,
bgImageSizes: props.bgImageSizes,
imgStyle: initialStyle,
bgStyle: {
...initialStyle,
...props.bgStyle,
},
percentage: 0,
splitChildren: getSplitChildren(props),
};
this.canUseDOM = canUseDOM();
this.node = null;
this.content = null;
this.bgImageLoaded = false;
this.bgImageRef = undefined;
this.parent = props.parent;
this.parentHeight = getNodeHeight(this.canUseDOM, this.parent);
this.timestamp = Date.now();
this.isDynamicBlur = getHasDynamicBlur(props.blur);
}
/**
* bind some eventlisteners for page load, scroll and resize
* save component ref after rendering, update all values and set static style values
*/
componentDidMount(): void {
const { parent } = this.props;
const { bgImage, bgImageSrcSet, bgImageSizes } = this.state;
this.parent = parent || document;
this.addListeners();
// ref to component itself
if (bgImage) {
this.loadImage(bgImage, bgImageSrcSet, bgImageSizes);
} else {
this.updatePosition();
}
}
static getDerivedStateFromProps(
props: ParallaxProps,
): {
splitChildren: SplitChildrenResultType;
} {
return {
splitChildren: getSplitChildren(props),
};
}
componentDidUpdate(prevProps: ParallaxProps): void {
const { parent, bgImage, bgImageSrcSet, bgImageSizes } = this.props;
const { bgImage: stateBgImage } = this.state;
if (prevProps.parent !== parent) {
this.removeListeners(this.parent);
this.parent = parent;
if (parent) {
this.addListeners();
}
}
this.parentHeight = getNodeHeight(this.canUseDOM, this.parent);
if (stateBgImage !== bgImage) {
this.loadImage(bgImage, bgImageSrcSet, bgImageSizes);
}
}
/**
* remove all eventlisteners before component is destroyed
*/
componentWillUnmount(): void {
this.removeListeners(this.parent);
this.releaseImage();
}
/**
* update window height and positions on window resize
*/
onWindowResize = (): void => {
this.parentHeight = getNodeHeight(this.canUseDOM, this.parent);
this.updatePosition();
};
onWindowLoad = (): void => {
this.updatePosition();
};
onScroll = (): void => {
if (!this.canUseDOM) {
return;
}
const stamp = Date.now();
if (stamp - this.timestamp >= 10 && isScrolledIntoView(this.node, 100, this.canUseDOM)) {
window.requestAnimationFrame(this.updatePosition);
this.timestamp = stamp;
}
};
onContentMount = (content: HTMLElement): void => {
this.content = content;
};
setBackgroundPosition(percentage: number): void {
const { disabled, strength } = this.props;
const bgStyle: StyleObjectType = {
...this.state.bgStyle,
};
if (!disabled) {
const inverse = strength < 0;
const pos = (inverse ? strength : 0) - strength * percentage;
const transform = `translate3d(-50%, ${pos}px, 0)`;
bgStyle.WebkitTransform = transform;
bgStyle.transform = transform;
}
this.setState({
bgStyle,
percentage,
});
}
/**
* sets position for the background image
*/
setImagePosition(percentage: number, autoHeight = false): void {
const { disabled, strength, blur } = this.props;
const height = autoHeight ? 'auto' : `${this.getImageHeight()}px`;
const width = !autoHeight ? 'auto' : `${this.contentWidth}px`;
const imgStyle: StyleObjectType = {
...this.state.imgStyle,
height,
width,
};
if (!disabled) {
const inverse = strength < 0;
const pos = (inverse ? strength : 0) - strength * percentage;
const transform = `translate3d(-50%, ${pos}px, 0)`;
let filter = 'none';
if (blur) {
filter = `blur(${getBlurValue(this.isDynamicBlur, blur, percentage)}px)`;
}
imgStyle.WebkitTransform = transform;
imgStyle.transform = transform;
imgStyle.WebkitFilter = filter;
imgStyle.filter = filter;
}
this.setState({
imgStyle,
percentage,
});
}
/**
* The image height depends on parallax direction. If strength value is negative we have to give it more height
* so there is no white space at start/end of container visiblility.
*/
getImageHeight(): number {
const { strength } = this.props;
const inverse = strength < 0;
const factor = inverse ? 2.5 : 1;
const strengthWithFactor = factor * Math.abs(strength);
return Math.floor(this.contentHeight + strengthWithFactor);
}
/**
* updates scroll position of this component and also its width and height.
* defines, if the background image should have autoHeight or autoWidth to
* fit the component space optimally
*/
updatePosition = (): void => {
if (!this.content) {
return;
}
let autoHeight = false;
this.contentHeight = this.content.getBoundingClientRect().height;
this.contentWidth = this.node.getBoundingClientRect().width;
// set autoHeight or autoWidth
if (
this.img &&
this.img.naturalWidth / this.img.naturalHeight <
this.contentWidth / this.getImageHeight()
) {
autoHeight = true;
}
// get relative scroll-y position of parallax component in percentage
const percentage = getRelativePosition(this.node, this.canUseDOM);
const hasBgImage = !!this.img;
const hasBgChildren = this.bg && this.state.splitChildren.bgChildren.length > 0;
// update bg image position if set
if (hasBgImage) {
this.setImagePosition(percentage, autoHeight);
}
// update position of Background children if exist
if (hasBgChildren) {
this.setBackgroundPosition(percentage);
}
// be sure to set the percentage if neither image nor bg component was set
if (!hasBgImage && !hasBgChildren) {
this.setState({ percentage });
}
};
/**
* Makes sure that the image was loaded before render
*/
loadImage(
bgImage: BgImageProp,
bgImageSrcSet: BgImageSrcSetProp,
bgImageSizes: BgImageSizesProp,
): void {
this.releaseImage();
this.bgImageRef = new Image();
this.bgImageRef.onload = (e) => {
this.setState(
{
bgImage,
bgImageSrcSet,
bgImageSizes,
},
() => this.updatePosition(),
);
if (this.props.onLoad) {
this.props.onLoad(e);
}
};
this.bgImageRef.onerror = this.bgImageRef.onload;
this.bgImageRef.src = bgImage;
this.bgImageRef.srcset = bgImageSrcSet || '';
this.bgImageRef.sizes = bgImageSizes || '';
}
/**
* Unbind eventlistener of bg image and delete it
*/
releaseImage(): void {
if (this.bgImageRef) {
this.bgImageRef.onload = null;
this.bgImageRef.onerror = null;
delete this.bgImageRef;
}
}
addListeners(): void {
if (this.canUseDOM && this.parent) {
this.parent.addEventListener('scroll', this.onScroll, false);
window.addEventListener('resize', this.onWindowResize, false);
window.addEventListener('load', this.onWindowLoad, false);
}
}
removeListeners(parent?: HTMLElement | Document): void {
if (this.canUseDOM) {
if (parent) {
parent.removeEventListener('scroll', this.onScroll, false);
}
window.removeEventListener('resize', this.onWindowResize, false);
window.removeEventListener('load', this.onWindowLoad, false);
}
}
render(): JSX.Element {
const {
className,
style,
bgClassName,
contentClassName,
bgImageAlt,
renderLayer,
bgImageStyle,
} = this.props;
const {
bgImage,
bgImageSrcSet,
bgImageSizes,
percentage,
imgStyle,
bgStyle,
splitChildren,
} = this.state;
return (
<div
className={`react-parallax ${className}`}
style={{ position: 'relative', overflow: 'hidden', ...style }}
ref={(node) => {
this.node = node;
}}
>
{bgImage ? (
<img
className={bgClassName}
src={bgImage}
srcSet={bgImageSrcSet}
sizes={bgImageSizes}
ref={(bg) => {
this.img = bg;
}}
alt={bgImageAlt}
style={{ ...imgStyle, ...bgImageStyle }}
/>
) : null}
{renderLayer ? renderLayer(-(percentage - 1)) : null}
{splitChildren.bgChildren.length > 0 ? (
<div
className="react-parallax-background-children"
ref={(bg) => {
this.bg = bg;
}}
style={bgStyle}
>
{splitChildren.bgChildren}
</div>
) : null}
<ParallaxChildren onMount={this.onContentMount} className={contentClassName}>
{splitChildren.children}
</ParallaxChildren>
</div>
);
}
}
export default Parallax; | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* Error response indicates Insights service is not able to process the incoming request. The
* reason is provided in the error message.
*/
export interface ErrorResponse {
/**
* Error code.
*/
code?: string;
/**
* Error message indicating why the operation failed.
*/
message?: string;
}
/**
* The object that represents the operation.
*/
export interface OperationDisplay {
/**
* Service provider: Microsoft.Cdn
*/
provider?: string;
/**
* Resource on which the operation is performed: Profile, endpoint, etc.
*/
resource?: string;
/**
* Operation type: Read, write, delete, etc.
*/
operation?: string;
}
/**
* CDN REST API operation
*/
export interface Operation {
/**
* Operation name: {provider}/{resource}/{operation}
*/
name?: string;
/**
* The object that represents the operation.
*/
display?: OperationDisplay;
}
/**
* Annotation associated with an application insights resource.
*/
export interface Annotation {
/**
* Name of annotation
*/
annotationName?: string;
/**
* Category of annotation, free form
*/
category?: string;
/**
* Time when event occurred
*/
eventTime?: Date;
/**
* Unique Id for annotation
*/
id?: string;
/**
* Serialized JSON object for detailed properties
*/
properties?: string;
/**
* Related parent annotation if any. Default value: 'null'.
*/
relatedAnnotation?: string;
}
/**
* Inner error
*/
export interface InnerError {
/**
* Provides correlation for request
*/
diagnosticcontext?: string;
/**
* Request time
*/
time?: Date;
}
/**
* Error associated with trying to create annotation with Id that already exist
*/
export interface AnnotationError {
/**
* Error detail code and explanation
*/
code?: string;
/**
* Error message
*/
message?: string;
innererror?: InnerError;
}
/**
* An Application Insights component API Key creation request definition.
*/
export interface APIKeyRequest {
/**
* The name of the API Key.
*/
name?: string;
/**
* The read access rights of this API Key.
*/
linkedReadProperties?: string[];
/**
* The write access rights of this API Key.
*/
linkedWriteProperties?: string[];
}
/**
* Properties that define an API key of an Application Insights Component.
*/
export interface ApplicationInsightsComponentAPIKey {
/**
* The unique ID of the API key inside an Application Insights component. It is auto generated
* when the API key is created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The API key value. It will be only return once when the API Key was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly apiKey?: string;
/**
* The create date of this API key.
*/
createdDate?: string;
/**
* The name of the API key.
*/
name?: string;
/**
* The read access rights of this API Key.
*/
linkedReadProperties?: string[];
/**
* The write access rights of this API Key.
*/
linkedWriteProperties?: string[];
}
/**
* An Application Insights component Continuous Export configuration request definition.
*/
export interface ApplicationInsightsComponentExportRequest {
/**
* The document types to be exported, as comma separated values. Allowed values include
* 'Requests', 'Event', 'Exceptions', 'Metrics', 'PageViews', 'PageViewPerformance', 'Rdd',
* 'PerformanceCounters', 'Availability', 'Messages'.
*/
recordTypes?: string;
/**
* The Continuous Export destination type. This has to be 'Blob'.
*/
destinationType?: string;
/**
* The SAS URL for the destination storage container. It must grant write permission.
*/
destinationAddress?: string;
/**
* Set to 'true' to create a Continuous Export configuration as enabled, otherwise set it to
* 'false'.
*/
isEnabled?: string;
/**
* Deprecated
*/
notificationQueueEnabled?: string;
/**
* Deprecated
*/
notificationQueueUri?: string;
/**
* The subscription ID of the destination storage container.
*/
destinationStorageSubscriptionId?: string;
/**
* The location ID of the destination storage container.
*/
destinationStorageLocationId?: string;
/**
* The name of destination storage account.
*/
destinationAccountId?: string;
}
/**
* Properties that define a Continuous Export configuration.
*/
export interface ApplicationInsightsComponentExportConfiguration {
/**
* The unique ID of the export configuration inside an Application Insights component. It is auto
* generated when the Continuous Export configuration is created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly exportId?: string;
/**
* The instrumentation key of the Application Insights component.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly instrumentationKey?: string;
/**
* This comma separated list of document types that will be exported. The possible values include
* 'Requests', 'Event', 'Exceptions', 'Metrics', 'PageViews', 'PageViewPerformance', 'Rdd',
* 'PerformanceCounters', 'Availability', 'Messages'.
*/
recordTypes?: string;
/**
* The name of the Application Insights component.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly applicationName?: string;
/**
* The subscription of the Application Insights component.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly subscriptionId?: string;
/**
* The resource group of the Application Insights component.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resourceGroup?: string;
/**
* The destination storage account subscription ID.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly destinationStorageSubscriptionId?: string;
/**
* The destination account location ID.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly destinationStorageLocationId?: string;
/**
* The name of destination account.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly destinationAccountId?: string;
/**
* The destination type.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly destinationType?: string;
/**
* This will be 'true' if the Continuous Export configuration is enabled, otherwise it will be
* 'false'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isUserEnabled?: string;
/**
* Last time the Continuous Export configuration was updated.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly lastUserUpdate?: string;
/**
* Deprecated
*/
notificationQueueEnabled?: string;
/**
* This indicates current Continuous Export configuration status. The possible values are
* 'Preparing', 'Success', 'Failure'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly exportStatus?: string;
/**
* The last time data was successfully delivered to the destination storage container for this
* Continuous Export configuration.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly lastSuccessTime?: string;
/**
* The last time the Continuous Export configuration started failing.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly lastGapTime?: string;
/**
* This is the reason the Continuous Export configuration started failing. It can be
* 'AzureStorageNotFound' or 'AzureStorageAccessDenied'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly permanentErrorReason?: string;
/**
* The name of the destination storage account.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly storageName?: string;
/**
* The name of the destination storage container.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly containerName?: string;
}
/**
* An Application Insights component daily data volume cap
*/
export interface ApplicationInsightsComponentDataVolumeCap {
/**
* Daily data volume cap in GB.
*/
cap?: number;
/**
* Daily data volume cap UTC reset hour.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resetTime?: number;
/**
* Reserved, not used for now.
*/
warningThreshold?: number;
/**
* Reserved, not used for now.
*/
stopSendNotificationWhenHitThreshold?: boolean;
/**
* Do not send a notification email when the daily data volume cap is met.
*/
stopSendNotificationWhenHitCap?: boolean;
/**
* Maximum daily data volume cap that the user can set for this component.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly maxHistoryCap?: number;
}
/**
* An Application Insights component billing features
*/
export interface ApplicationInsightsComponentBillingFeatures {
/**
* An Application Insights component daily data volume cap
*/
dataVolumeCap?: ApplicationInsightsComponentDataVolumeCap;
/**
* Current enabled pricing plan. When the component is in the Enterprise plan, this will list
* both 'Basic' and 'Application Insights Enterprise'.
*/
currentBillingFeatures?: string[];
}
/**
* An Application Insights component daily data volume cap status
*/
export interface ApplicationInsightsComponentQuotaStatus {
/**
* The Application ID for the Application Insights component.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly appId?: string;
/**
* The daily data volume cap is met, and data ingestion will be stopped.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly shouldBeThrottled?: boolean;
/**
* Date and time when the daily data volume cap will be reset, and data ingestion will resume.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly expirationTime?: string;
}
/**
* An Application Insights component feature capabilities
*/
export interface ApplicationInsightsComponentFeatureCapabilities {
/**
* Whether allow to use continuous export feature.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly supportExportData?: boolean;
/**
* Reserved, not used now.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly burstThrottlePolicy?: string;
/**
* Reserved, not used now.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly metadataClass?: string;
/**
* Reserved, not used now.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly liveStreamMetrics?: boolean;
/**
* Reserved, not used now.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly applicationMap?: boolean;
/**
* Whether allow to use work item integration feature.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly workItemIntegration?: boolean;
/**
* Reserved, not used now.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly powerBIIntegration?: boolean;
/**
* Reserved, not used now.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly openSchema?: boolean;
/**
* Reserved, not used now.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly proactiveDetection?: boolean;
/**
* Reserved, not used now.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly analyticsIntegration?: boolean;
/**
* Whether allow to use multiple steps web test feature.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly multipleStepWebTest?: boolean;
/**
* Reserved, not used now.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly apiAccessLevel?: string;
/**
* The application insights component used tracking type.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly trackingType?: string;
/**
* Daily data volume cap in GB.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly dailyCap?: number;
/**
* Daily data volume cap UTC reset hour.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly dailyCapResetTime?: number;
/**
* Reserved, not used now.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly throttleRate?: number;
}
/**
* An Application Insights component feature capability
*/
export interface ApplicationInsightsComponentFeatureCapability {
/**
* The name of the capability.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The description of the capability.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly description?: string;
/**
* The value of the capability.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly value?: string;
/**
* The unit of the capability.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly unit?: string;
/**
* The meter used for the capability.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly meterId?: string;
/**
* The meter rate of the meter.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly meterRateFrequency?: string;
}
/**
* An Application Insights component daily data volume cap status
*/
export interface ApplicationInsightsComponentFeature {
/**
* The pricing feature name.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly featureName?: string;
/**
* The meter id used for the feature.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly meterId?: string;
/**
* The meter rate for the feature's meter.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly meterRateFrequency?: string;
/**
* Reserved, not used now.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resouceId?: string;
/**
* Reserved, not used now.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isHidden?: boolean;
/**
* A list of Application Insights component feature capability.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly capabilities?: ApplicationInsightsComponentFeatureCapability[];
/**
* Display name of the feature.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly title?: string;
/**
* Whether can apply addon feature on to it.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isMainFeature?: boolean;
/**
* The add on features on main feature.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly supportedAddonFeatures?: string;
}
/**
* An Application Insights component available features.
*/
export interface ApplicationInsightsComponentAvailableFeatures {
/**
* A list of Application Insights component feature.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly result?: ApplicationInsightsComponentFeature[];
}
/**
* Static definitions of the ProactiveDetection configuration rule (same values for all
* components).
*/
export interface ApplicationInsightsComponentProactiveDetectionConfigurationRuleDefinitions {
/**
* The rule name
*/
name?: string;
/**
* The rule name as it is displayed in UI
*/
displayName?: string;
/**
* The rule description
*/
description?: string;
/**
* URL which displays additional info about the proactive detection rule
*/
helpUrl?: string;
/**
* A flag indicating whether the rule is hidden (from the UI)
*/
isHidden?: boolean;
/**
* A flag indicating whether the rule is enabled by default
*/
isEnabledByDefault?: boolean;
/**
* A flag indicating whether the rule is in preview
*/
isInPreview?: boolean;
/**
* A flag indicating whether email notifications are supported for detections for this rule
*/
supportsEmailNotifications?: boolean;
}
/**
* Properties that define a ProactiveDetection configuration.
*/
export interface ApplicationInsightsComponentProactiveDetectionConfiguration extends BaseResource {
/**
* The rule name
*/
name?: string;
/**
* A flag that indicates whether this rule is enabled by the user
*/
enabled?: boolean;
/**
* A flag that indicated whether notifications on this rule should be sent to subscription owners
*/
sendEmailsToSubscriptionOwners?: boolean;
/**
* Custom email addresses for this rule notifications
*/
customEmails?: string[];
/**
* The last time this rule was updated
*/
lastUpdatedTime?: string;
/**
* Static definitions of the ProactiveDetection configuration rule (same values for all
* components).
*/
ruleDefinitions?: ApplicationInsightsComponentProactiveDetectionConfigurationRuleDefinitions;
}
/**
* Work item configuration associated with an application insights resource.
*/
export interface WorkItemConfiguration {
/**
* Connector identifier where work item is created
*/
connectorId?: string;
/**
* Configuration friendly name
*/
configDisplayName?: string;
/**
* Boolean value indicating whether configuration is default
*/
isDefault?: boolean;
/**
* Unique Id for work item
*/
id?: string;
/**
* Serialized JSON object for detailed properties
*/
configProperties?: string;
}
/**
* Work item configuration creation payload
*/
export interface WorkItemCreateConfiguration {
/**
* Unique connector id
*/
connectorId?: string;
/**
* Serialized JSON object for detailed properties
*/
connectorDataConfiguration?: string;
/**
* Boolean indicating validate only
*/
validateOnly?: boolean;
/**
* Custom work item properties
*/
workItemProperties?: { [propertyName: string]: string };
}
/**
* Error associated with trying to get work item configuration or configurations
*/
export interface WorkItemConfigurationError {
/**
* Error detail code and explanation
*/
code?: string;
/**
* Error message
*/
message?: string;
innererror?: InnerError;
}
/**
* Properties that define a favorite that is associated to an Application Insights component.
*/
export interface ApplicationInsightsComponentFavorite {
/**
* The user-defined name of the favorite.
*/
name?: string;
/**
* Configuration of this particular favorite, which are driven by the Azure portal UX.
* Configuration data is a string containing valid JSON
*/
config?: string;
/**
* This instance's version of the data model. This can change as new features are added that can
* be marked favorite. Current examples include MetricsExplorer (ME) and Search.
*/
version?: string;
/**
* Internally assigned unique id of the favorite definition.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly favoriteId?: string;
/**
* Enum indicating if this favorite definition is owned by a specific user or is shared between
* all users with access to the Application Insights component. Possible values include:
* 'shared', 'user'
*/
favoriteType?: FavoriteType;
/**
* The source of the favorite definition.
*/
sourceType?: string;
/**
* Date and time in UTC of the last modification that was made to this favorite definition.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly timeModified?: string;
/**
* A list of 0 or more tags that are associated with this favorite definition
*/
tags?: string[];
/**
* Favorite category, as defined by the user at creation time.
*/
category?: string;
/**
* Flag denoting wether or not this favorite was generated from a template.
*/
isGeneratedFromTemplate?: boolean;
/**
* Unique user id of the specific user that owns this favorite.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly userId?: string;
}
/**
* Properties that define a web test location available to an Application Insights Component.
*/
export interface ApplicationInsightsComponentWebTestLocation {
/**
* The display name of the web test location.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly displayName?: string;
/**
* Internally defined geographic location tag.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly tag?: string;
}
/**
* An azure resource object
*/
export interface WebtestsResource extends BaseResource {
/**
* Azure resource Id
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Azure resource name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Azure resource type
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* Resource location
*/
location: string;
/**
* Resource tags
*/
tags?: { [propertyName: string]: string };
}
/**
* A container holding only the Tags for a resource, allowing the user to update the tags on a
* WebTest instance.
*/
export interface TagsResource {
/**
* Resource tags
*/
tags?: { [propertyName: string]: string };
}
/**
* Geo-physical location to run a web test from. You must specify one or more locations for the
* test to run from.
*/
export interface WebTestGeolocation {
/**
* Location ID for the webtest to run from.
*/
location?: string;
}
/**
* An XML configuration specification for a WebTest.
*/
export interface WebTestPropertiesConfiguration {
/**
* The XML specification of a WebTest to run against an application.
*/
webTest?: string;
}
/**
* An Application Insights web test definition.
*/
export interface WebTest extends WebtestsResource {
/**
* The kind of web test that this web test watches. Choices are ping and multistep. Possible
* values include: 'ping', 'multistep'. Default value: 'ping'.
*/
kind?: WebTestKind;
/**
* Unique ID of this WebTest. This is typically the same value as the Name field.
*/
syntheticMonitorId: string;
/**
* User defined name if this WebTest.
*/
webTestName: string;
/**
* Purpose/user defined descriptive test for this WebTest.
*/
description?: string;
/**
* Is the test actively being monitored.
*/
enabled?: boolean;
/**
* Interval in seconds between test runs for this WebTest. Default value is 300. Default value:
* 300.
*/
frequency?: number;
/**
* Seconds until this WebTest will timeout and fail. Default value is 30. Default value: 30.
*/
timeout?: number;
/**
* The kind of web test this is, valid choices are ping and multistep. Possible values include:
* 'ping', 'multistep'. Default value: 'ping'.
*/
webTestKind: WebTestKind;
/**
* Allow for retries should this WebTest fail.
*/
retryEnabled?: boolean;
/**
* A list of where to physically run the tests from to give global coverage for accessibility of
* your application.
*/
locations: WebTestGeolocation[];
/**
* An XML configuration specification for a WebTest.
*/
configuration?: WebTestPropertiesConfiguration;
/**
* Current state of this component, whether or not is has been provisioned within the resource
* group it is defined. Users cannot change this value but are able to read from it. Values will
* include Succeeded, Deploying, Canceled, and Failed.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
}
/**
* A set of properties that can be defined in the context of a specific item type. Each type may
* have its own properties.
*/
export interface ApplicationInsightsComponentAnalyticsItemProperties {
/**
* A function alias, used when the type of the item is Function
*/
functionAlias?: string;
}
/**
* Properties that define an Analytics item that is associated to an Application Insights
* component.
*/
export interface ApplicationInsightsComponentAnalyticsItem {
/**
* Internally assigned unique id of the item definition.
*/
id?: string;
/**
* The user-defined name of the item.
*/
name?: string;
/**
* The content of this item
*/
content?: string;
/**
* This instance's version of the data model. This can change as new features are added.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly version?: string;
/**
* Enum indicating if this item definition is owned by a specific user or is shared between all
* users with access to the Application Insights component. Possible values include: 'shared',
* 'user'
*/
scope?: ItemScope;
/**
* Enum indicating the type of the Analytics item. Possible values include: 'query', 'function',
* 'folder', 'recent'
*/
type?: ItemType;
/**
* Date and time in UTC when this item was created.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly timeCreated?: string;
/**
* Date and time in UTC of the last modification that was made to this item.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly timeModified?: string;
properties?: ApplicationInsightsComponentAnalyticsItemProperties;
}
/**
* An azure resource object
*/
export interface WorkbookResource extends BaseResource {
/**
* Azure resource Id
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Azure resource name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Azure resource type
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* Resource location
*/
location?: string;
/**
* Resource tags
*/
tags?: { [propertyName: string]: string };
}
/**
* An Application Insights workbook definition.
*/
export interface Workbook extends WorkbookResource {
/**
* The kind of workbook. Choices are user and shared. Possible values include: 'user', 'shared'
*/
kind?: SharedTypeKind;
/**
* The user-defined name of the workbook.
*/
workbookName: string;
/**
* Configuration of this particular workbook. Configuration data is a string containing valid
* JSON
*/
serializedData: string;
/**
* This instance's version of the data model. This can change as new features are added that can
* be marked workbook.
*/
version?: string;
/**
* Internally assigned unique id of the workbook definition.
*/
workbookId: string;
/**
* Enum indicating if this workbook definition is owned by a specific user or is shared between
* all users with access to the Application Insights component. Possible values include: 'user',
* 'shared'. Default value: 'shared'.
*/
sharedTypeKind: SharedTypeKind;
/**
* Date and time in UTC of the last modification that was made to this workbook definition.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly timeModified?: string;
/**
* Workbook category, as defined by the user at creation time.
*/
category: string;
/**
* A list of 0 or more tags that are associated with this workbook definition
*/
workbookTags?: string[];
/**
* Unique user id of the specific user that owns this workbook.
*/
userId: string;
/**
* Optional resourceId for a source resource.
*/
sourceResourceId?: string;
}
/**
* Contains a sourceId and workbook resource id to link two resources.
*/
export interface LinkProperties {
/**
* The source Azure resource id
*/
sourceId?: string;
/**
* The workbook Azure resource id
*/
targetId?: string;
/**
* The category of workbook
*/
category?: string;
}
/**
* Error Field contract.
*/
export interface ErrorFieldContract {
/**
* Property level error code.
*/
code?: string;
/**
* Human-readable representation of property-level error.
*/
message?: string;
/**
* Property name.
*/
target?: string;
}
/**
* Error message body that will indicate why the operation failed.
*/
export interface WorkbookError {
/**
* Service-defined error code. This code serves as a sub-status for the HTTP error code specified
* in the response.
*/
code?: string;
/**
* Human-readable representation of the error.
*/
message?: string;
/**
* The list of invalid fields send in request, in case of validation error.
*/
details?: ErrorFieldContract[];
}
/**
* An azure resource object
*/
export interface MyWorkbookResource extends BaseResource {
/**
* Azure resource Id
*/
id?: string;
/**
* Azure resource name
*/
name?: string;
/**
* Azure resource type
*/
type?: string;
/**
* Resource location
*/
location?: string;
/**
* Resource tags
*/
tags?: { [propertyName: string]: string };
}
/**
* An Application Insights private workbook definition.
*/
export interface MyWorkbook extends MyWorkbookResource {
/**
* The kind of workbook. Choices are user and shared. Possible values include: 'user', 'shared'
*/
kind?: SharedTypeKind;
/**
* The user-defined name of the private workbook.
*/
displayName: string;
/**
* Configuration of this particular private workbook. Configuration data is a string containing
* valid JSON
*/
serializedData: string;
/**
* This instance's version of the data model. This can change as new features are added that can
* be marked private workbook.
*/
version?: string;
/**
* Date and time in UTC of the last modification that was made to this private workbook
* definition.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly timeModified?: string;
/**
* Workbook category, as defined by the user at creation time.
*/
category: string;
/**
* A list of 0 or more tags that are associated with this private workbook definition
*/
myWorkbookTags?: string[];
/**
* Unique user id of the specific user that owns this private workbook.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly userId?: string;
/**
* Optional resourceId for a source resource.
*/
sourceId?: string;
}
/**
* Error message body that will indicate why the operation failed.
*/
export interface MyWorkbookError {
/**
* Service-defined error code. This code serves as a sub-status for the HTTP error code specified
* in the response.
*/
code?: string;
/**
* Human-readable representation of the error.
*/
message?: string;
/**
* The list of invalid fields send in request, in case of validation error.
*/
details?: ErrorFieldContract[];
}
/**
* An azure resource object
*/
export interface ComponentsResource extends BaseResource {
/**
* Azure resource Id
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Azure resource name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Azure resource type
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* Resource location
*/
location: string;
/**
* Resource tags
*/
tags?: { [propertyName: string]: string };
}
/**
* The private link scope resource reference.
*/
export interface PrivateLinkScopedResource {
/**
* The full resource Id of the private link scope resource.
*/
resourceId?: string;
/**
* The private link scope unique Identifier.
*/
scopeId?: string;
}
/**
* An Application Insights component definition.
*/
export interface ApplicationInsightsComponent extends ComponentsResource {
/**
* The kind of application that this component refers to, used to customize UI. This value is a
* freeform string, values should typically be one of the following: web, ios, other, store,
* java, phone.
*/
kind: string;
/**
* The unique ID of your application. This field mirrors the 'Name' field and cannot be changed.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly applicationId?: string;
/**
* Application Insights Unique ID for your Application.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly appId?: string;
/**
* Type of application being monitored. Possible values include: 'web', 'other'. Default value:
* 'web'.
*/
applicationType: ApplicationType;
/**
* Used by the Application Insights system to determine what kind of flow this component was
* created by. This is to be set to 'Bluefield' when creating/updating a component via the REST
* API. Possible values include: 'Bluefield'. Default value: 'Bluefield'.
*/
flowType?: FlowType;
/**
* Describes what tool created this Application Insights component. Customers using this API
* should set this to the default 'rest'. Possible values include: 'rest'. Default value: 'rest'.
*/
requestSource?: RequestSource;
/**
* Application Insights Instrumentation key. A read-only value that applications can use to
* identify the destination for all telemetry sent to Azure Application Insights. This value will
* be supplied upon construction of each new Application Insights component.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly instrumentationKey?: string;
/**
* Creation Date for the Application Insights component, in ISO 8601 format.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly creationDate?: Date;
/**
* Azure Tenant Id.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly tenantId?: string;
/**
* The unique application ID created when a new application is added to HockeyApp, used for
* communications with HockeyApp.
*/
hockeyAppId?: string;
/**
* Token used to authenticate communications with between Application Insights and HockeyApp.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly hockeyAppToken?: string;
/**
* Current state of this component: whether or not is has been provisioned within the resource
* group it is defined. Users cannot change this value but are able to read from it. Values will
* include Succeeded, Deploying, Canceled, and Failed.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* Percentage of the data produced by the application being monitored that is being sampled for
* Application Insights telemetry.
*/
samplingPercentage?: number;
/**
* Application Insights component connection string.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly connectionString?: string;
/**
* Retention period in days. Default value: 90.
*/
retentionInDays?: number;
/**
* Disable IP masking.
*/
disableIpMasking?: boolean;
/**
* Purge data immediately after 30 days.
*/
immediatePurgeDataOn30Days?: boolean;
/**
* List of linked private link scope resources.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly privateLinkScopedResources?: PrivateLinkScopedResource[];
/**
* The network access type for accessing Application Insights ingestion. Possible values include:
* 'Enabled', 'Disabled'. Default value: 'Enabled'.
*/
publicNetworkAccessForIngestion?: PublicNetworkAccessType;
/**
* The network access type for accessing Application Insights query. Possible values include:
* 'Enabled', 'Disabled'. Default value: 'Enabled'.
*/
publicNetworkAccessForQuery?: PublicNetworkAccessType;
/**
* Indicates the flow of the ingestion. Possible values include: 'ApplicationInsights',
* 'ApplicationInsightsWithDiagnosticSettings', 'LogAnalytics'. Default value:
* 'ApplicationInsights'.
*/
ingestionMode?: IngestionMode;
}
/**
* User-defined filters to return data which will be purged from the table.
*/
export interface ComponentPurgeBodyFilters {
/**
* The column of the table over which the given query should run
*/
column?: string;
/**
* A query operator to evaluate over the provided column and value(s). Supported operators are
* ==, =~, in, in~, >, >=, <, <=, between, and have the same behavior as they would in a KQL
* query.
*/
operator?: string;
/**
* the value for the operator to function over. This can be a number (e.g., > 100), a string
* (timestamp >= '2017-09-01') or array of values.
*/
value?: any;
/**
* When filtering over custom dimensions, this key will be used as the name of the custom
* dimension.
*/
key?: string;
}
/**
* Describes the body of a purge request for an App Insights component
*/
export interface ComponentPurgeBody {
/**
* Table from which to purge data.
*/
table: string;
/**
* The set of columns and filters (queries) to run over them to purge the resulting data.
*/
filters: ComponentPurgeBodyFilters[];
}
/**
* Response containing operationId for a specific purge action.
*/
export interface ComponentPurgeResponse {
/**
* Id to use when querying for status for a particular purge operation.
*/
operationId: string;
}
/**
* Response containing status for a specific purge operation.
*/
export interface ComponentPurgeStatusResponse {
/**
* Status of the operation represented by the requested Id. Possible values include: 'pending',
* 'completed'
*/
status: PurgeState;
}
/**
* An interface representing Resource.
*/
export interface Resource extends BaseResource {
/**
* Fully qualified resource Id for the resource. Ex -
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The name of the resource
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The type of the resource. Ex- Microsoft.Compute/virtualMachines or
* Microsoft.Storage/storageAccounts.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* The resource model definition for a ARM proxy resource. It will have everything other than
* required location and tags
*/
export interface ProxyResource extends Resource {
}
/**
* An Application Insights component linked storage accounts
*/
export interface ComponentLinkedStorageAccounts extends ProxyResource {
/**
* Linked storage account resource ID
*/
linkedStorageAccount?: string;
}
/**
* An Application Insights component linked storage accounts patch
*/
export interface ComponentLinkedStorageAccountsPatch {
/**
* Linked storage account resource ID
*/
linkedStorageAccount?: string;
}
/**
* The resource model definition for a ARM tracked top level resource
*/
export interface TrackedResource extends Resource {
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
/**
* The geo-location where the resource lives
*/
location: string;
}
/**
* The resource model definition for a Azure Resource Manager resource with an etag.
*/
export interface AzureEntityResource extends Resource {
/**
* Resource Etag.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly etag?: string;
}
/**
* The response to a live token query.
*/
export interface LiveTokenResponse {
/**
* JWT token for accessing live metrics stream data.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly liveToken?: string;
}
/**
* Information about an operation
*/
export interface OperationInfo {
/**
* Name of the provider
*/
provider?: string;
/**
* Name of the resource type
*/
resource?: string;
/**
* Name of the operation
*/
operation?: string;
/**
* Description of the operation
*/
description?: string;
}
/**
* Represents an operation returned by the GetOperations request
*/
export interface OperationLive {
/**
* Name of the operation
*/
name?: string;
/**
* Display name of the operation
*/
display?: OperationInfo;
/**
* Origin of the operation
*/
origin?: string;
/**
* Properties of the operation
*/
properties?: any;
}
/**
* Optional Parameters.
*/
export interface FavoritesListOptionalParams extends msRest.RequestOptionsBase {
/**
* The type of favorite. Value can be either shared or user. Possible values include: 'shared',
* 'user'. Default value: 'shared'.
*/
favoriteType?: FavoriteType;
/**
* Source type of favorite to return. When left out, the source type defaults to 'other' (not
* present in this enum). Possible values include: 'retention', 'notebook', 'sessions', 'events',
* 'userflows', 'funnel', 'impact', 'segmentation'
*/
sourceType?: FavoriteSourceType;
/**
* Flag indicating whether or not to return the full content for each applicable favorite. If
* false, only return summary content for favorites.
*/
canFetchContent?: boolean;
/**
* Tags that must be present on each favorite returned.
*/
tags?: string[];
}
/**
* Optional Parameters.
*/
export interface AnalyticsItemsListOptionalParams extends msRest.RequestOptionsBase {
/**
* Enum indicating if this item definition is owned by a specific user or is shared between all
* users with access to the Application Insights component. Possible values include: 'shared',
* 'user'. Default value: 'shared'.
*/
scope?: ItemScope;
/**
* Enum indicating the type of the Analytics item. Possible values include: 'none', 'query',
* 'function', 'folder', 'recent'. Default value: 'none'.
*/
type?: ItemTypeParameter;
/**
* Flag indicating whether or not to return the content of each applicable item. If false, only
* return the item information.
*/
includeContent?: boolean;
}
/**
* Optional Parameters.
*/
export interface AnalyticsItemsGetOptionalParams extends msRest.RequestOptionsBase {
/**
* The Id of a specific item defined in the Application Insights component
*/
id?: string;
/**
* The name of a specific item defined in the Application Insights component
*/
name?: string;
}
/**
* Optional Parameters.
*/
export interface AnalyticsItemsPutOptionalParams extends msRest.RequestOptionsBase {
/**
* Flag indicating whether or not to force save an item. This allows overriding an item if it
* already exists.
*/
overrideItem?: boolean;
}
/**
* Optional Parameters.
*/
export interface AnalyticsItemsDeleteMethodOptionalParams extends msRest.RequestOptionsBase {
/**
* The Id of a specific item defined in the Application Insights component
*/
id?: string;
/**
* The name of a specific item defined in the Application Insights component
*/
name?: string;
}
/**
* Optional Parameters.
*/
export interface WorkbooksListByResourceGroupOptionalParams extends msRest.RequestOptionsBase {
/**
* Tags presents on each workbook returned.
*/
tags?: string[];
/**
* Flag indicating whether or not to return the full content for each applicable workbook. If
* false, only return summary content for workbooks.
*/
canFetchContent?: boolean;
}
/**
* Optional Parameters.
*/
export interface MyWorkbooksListByResourceGroupOptionalParams extends msRest.RequestOptionsBase {
/**
* Tags presents on each workbook returned.
*/
tags?: string[];
/**
* Flag indicating whether or not to return the full content for each applicable workbook. If
* false, only return summary content for workbooks.
*/
canFetchContent?: boolean;
}
/**
* Optional Parameters.
*/
export interface MyWorkbooksListBySubscriptionOptionalParams extends msRest.RequestOptionsBase {
/**
* Tags presents on each workbook returned.
*/
tags?: string[];
/**
* Flag indicating whether or not to return the full content for each applicable workbook. If
* false, only return summary content for workbooks.
*/
canFetchContent?: boolean;
}
/**
* An interface representing ApplicationInsightsManagementClientOptions.
*/
export interface ApplicationInsightsManagementClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* @interface
* Result of the request to list CDN 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
* Result of the List Operations operation
* @extends Array<OperationLive>
*/
export interface OperationsListResult extends Array<OperationLive> {
/**
* URL to get the next set of operation list results if there are any.
*/
nextLink?: string;
}
/**
* @interface
* Annotations list result.
* @extends Array<Annotation>
*/
export interface AnnotationsListResult extends Array<Annotation> {
}
/**
* @interface
* Describes the list of API Keys of an Application Insights Component.
* @extends Array<ApplicationInsightsComponentAPIKey>
*/
export interface ApplicationInsightsComponentAPIKeyListResult extends Array<ApplicationInsightsComponentAPIKey> {
}
/**
* @interface
* Work item configuration list result.
* @extends Array<WorkItemConfiguration>
*/
export interface WorkItemConfigurationsListResult extends Array<WorkItemConfiguration> {
}
/**
* @interface
* Describes the list of web test locations available to an Application Insights Component.
* @extends Array<ApplicationInsightsComponentWebTestLocation>
*/
export interface ApplicationInsightsWebTestLocationsListResult extends Array<ApplicationInsightsComponentWebTestLocation> {
}
/**
* @interface
* A list of 0 or more Application Insights web test definitions.
* @extends Array<WebTest>
*/
export interface WebTestListResult extends Array<WebTest> {
/**
* The link to get the next part of the returned list of web tests, should the return set be too
* large for a single request. May be null.
*/
nextLink?: string;
}
/**
* @interface
* Workbook list result.
* @extends Array<Workbook>
*/
export interface WorkbooksListResult extends Array<Workbook> {
}
/**
* @interface
* Workbook list result.
* @extends Array<MyWorkbook>
*/
export interface MyWorkbooksListResult extends Array<MyWorkbook> {
}
/**
* @interface
* Describes the list of Application Insights Resources.
* @extends Array<ApplicationInsightsComponent>
*/
export interface ApplicationInsightsComponentListResult extends Array<ApplicationInsightsComponent> {
/**
* The URI to get the next set of Application Insights component definitions if too many
* components where returned in the result set.
*/
nextLink?: string;
}
/**
* Defines values for FavoriteType.
* Possible values include: 'shared', 'user'
* @readonly
* @enum {string}
*/
export type FavoriteType = 'shared' | 'user';
/**
* Defines values for WebTestKind.
* Possible values include: 'ping', 'multistep'
* @readonly
* @enum {string}
*/
export type WebTestKind = 'ping' | 'multistep';
/**
* Defines values for ItemScope.
* Possible values include: 'shared', 'user'
* @readonly
* @enum {string}
*/
export type ItemScope = 'shared' | 'user';
/**
* Defines values for ItemType.
* Possible values include: 'query', 'function', 'folder', 'recent'
* @readonly
* @enum {string}
*/
export type ItemType = 'query' | 'function' | 'folder' | 'recent';
/**
* Defines values for SharedTypeKind.
* Possible values include: 'user', 'shared'
* @readonly
* @enum {string}
*/
export type SharedTypeKind = 'user' | 'shared';
/**
* Defines values for ApplicationType.
* Possible values include: 'web', 'other'
* @readonly
* @enum {string}
*/
export type ApplicationType = 'web' | 'other';
/**
* Defines values for FlowType.
* Possible values include: 'Bluefield'
* @readonly
* @enum {string}
*/
export type FlowType = 'Bluefield';
/**
* Defines values for RequestSource.
* Possible values include: 'rest'
* @readonly
* @enum {string}
*/
export type RequestSource = 'rest';
/**
* Defines values for PublicNetworkAccessType.
* Possible values include: 'Enabled', 'Disabled'
* @readonly
* @enum {string}
*/
export type PublicNetworkAccessType = 'Enabled' | 'Disabled';
/**
* Defines values for IngestionMode.
* Possible values include: 'ApplicationInsights', 'ApplicationInsightsWithDiagnosticSettings',
* 'LogAnalytics'
* @readonly
* @enum {string}
*/
export type IngestionMode = 'ApplicationInsights' | 'ApplicationInsightsWithDiagnosticSettings' | 'LogAnalytics';
/**
* Defines values for PurgeState.
* Possible values include: 'pending', 'completed'
* @readonly
* @enum {string}
*/
export type PurgeState = 'pending' | 'completed';
/**
* Defines values for FavoriteSourceType.
* Possible values include: 'retention', 'notebook', 'sessions', 'events', 'userflows', 'funnel',
* 'impact', 'segmentation'
* @readonly
* @enum {string}
*/
export type FavoriteSourceType = 'retention' | 'notebook' | 'sessions' | 'events' | 'userflows' | 'funnel' | 'impact' | 'segmentation';
/**
* Defines values for ItemScopePath.
* Possible values include: 'analyticsItems', 'myanalyticsItems'
* @readonly
* @enum {string}
*/
export type ItemScopePath = 'analyticsItems' | 'myanalyticsItems';
/**
* Defines values for ItemTypeParameter.
* Possible values include: 'none', 'query', 'function', 'folder', 'recent'
* @readonly
* @enum {string}
*/
export type ItemTypeParameter = 'none' | 'query' | 'function' | 'folder' | 'recent';
/**
* Defines values for CategoryType.
* Possible values include: 'workbook', 'TSG', 'performance', 'retention'
* @readonly
* @enum {string}
*/
export type CategoryType = 'workbook' | 'TSG' | 'performance' | 'retention';
/**
* 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 list1 operation.
*/
export type OperationsList1Response = OperationsListResult & {
/**
* 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: OperationsListResult;
};
};
/**
* 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 list1Next operation.
*/
export type OperationsList1NextResponse = OperationsListResult & {
/**
* 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: OperationsListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type AnnotationsListResponse = AnnotationsListResult & {
/**
* 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: AnnotationsListResult;
};
};
/**
* Contains response data for the create operation.
*/
export type AnnotationsCreateResponse = Array<Annotation> & {
/**
* 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: Annotation[];
};
};
/**
* Contains response data for the get operation.
*/
export type AnnotationsGetResponse = Array<Annotation> & {
/**
* 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: Annotation[];
};
};
/**
* Contains response data for the list operation.
*/
export type APIKeysListResponse = ApplicationInsightsComponentAPIKeyListResult & {
/**
* 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: ApplicationInsightsComponentAPIKeyListResult;
};
};
/**
* Contains response data for the create operation.
*/
export type APIKeysCreateResponse = ApplicationInsightsComponentAPIKey & {
/**
* 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: ApplicationInsightsComponentAPIKey;
};
};
/**
* Contains response data for the deleteMethod operation.
*/
export type APIKeysDeleteMethodResponse = ApplicationInsightsComponentAPIKey & {
/**
* 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: ApplicationInsightsComponentAPIKey;
};
};
/**
* Contains response data for the get operation.
*/
export type APIKeysGetResponse = ApplicationInsightsComponentAPIKey & {
/**
* 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: ApplicationInsightsComponentAPIKey;
};
};
/**
* Contains response data for the list operation.
*/
export type ExportConfigurationsListResponse = Array<ApplicationInsightsComponentExportConfiguration> & {
/**
* 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: ApplicationInsightsComponentExportConfiguration[];
};
};
/**
* Contains response data for the create operation.
*/
export type ExportConfigurationsCreateResponse = Array<ApplicationInsightsComponentExportConfiguration> & {
/**
* 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: ApplicationInsightsComponentExportConfiguration[];
};
};
/**
* Contains response data for the deleteMethod operation.
*/
export type ExportConfigurationsDeleteMethodResponse = ApplicationInsightsComponentExportConfiguration & {
/**
* 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: ApplicationInsightsComponentExportConfiguration;
};
};
/**
* Contains response data for the get operation.
*/
export type ExportConfigurationsGetResponse = ApplicationInsightsComponentExportConfiguration & {
/**
* 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: ApplicationInsightsComponentExportConfiguration;
};
};
/**
* Contains response data for the update operation.
*/
export type ExportConfigurationsUpdateResponse = ApplicationInsightsComponentExportConfiguration & {
/**
* 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: ApplicationInsightsComponentExportConfiguration;
};
};
/**
* Contains response data for the get operation.
*/
export type ComponentCurrentBillingFeaturesGetResponse = ApplicationInsightsComponentBillingFeatures & {
/**
* 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: ApplicationInsightsComponentBillingFeatures;
};
};
/**
* Contains response data for the update operation.
*/
export type ComponentCurrentBillingFeaturesUpdateResponse = ApplicationInsightsComponentBillingFeatures & {
/**
* 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: ApplicationInsightsComponentBillingFeatures;
};
};
/**
* Contains response data for the get operation.
*/
export type ComponentQuotaStatusGetResponse = ApplicationInsightsComponentQuotaStatus & {
/**
* 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: ApplicationInsightsComponentQuotaStatus;
};
};
/**
* Contains response data for the get operation.
*/
export type ComponentFeatureCapabilitiesGetResponse = ApplicationInsightsComponentFeatureCapabilities & {
/**
* 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: ApplicationInsightsComponentFeatureCapabilities;
};
};
/**
* Contains response data for the get operation.
*/
export type ComponentAvailableFeaturesGetResponse = ApplicationInsightsComponentAvailableFeatures & {
/**
* 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: ApplicationInsightsComponentAvailableFeatures;
};
};
/**
* Contains response data for the list operation.
*/
export type ProactiveDetectionConfigurationsListResponse = Array<ApplicationInsightsComponentProactiveDetectionConfiguration> & {
/**
* 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: ApplicationInsightsComponentProactiveDetectionConfiguration[];
};
};
/**
* Contains response data for the get operation.
*/
export type ProactiveDetectionConfigurationsGetResponse = ApplicationInsightsComponentProactiveDetectionConfiguration & {
/**
* 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: ApplicationInsightsComponentProactiveDetectionConfiguration;
};
};
/**
* Contains response data for the update operation.
*/
export type ProactiveDetectionConfigurationsUpdateResponse = ApplicationInsightsComponentProactiveDetectionConfiguration & {
/**
* 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: ApplicationInsightsComponentProactiveDetectionConfiguration;
};
};
/**
* Contains response data for the list operation.
*/
export type WorkItemConfigurationsListResponse = WorkItemConfigurationsListResult & {
/**
* 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: WorkItemConfigurationsListResult;
};
};
/**
* Contains response data for the create operation.
*/
export type WorkItemConfigurationsCreateResponse = WorkItemConfiguration & {
/**
* 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: WorkItemConfiguration;
};
};
/**
* Contains response data for the getDefault operation.
*/
export type WorkItemConfigurationsGetDefaultResponse = WorkItemConfiguration & {
/**
* 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: WorkItemConfiguration;
};
};
/**
* Contains response data for the getItem operation.
*/
export type WorkItemConfigurationsGetItemResponse = WorkItemConfiguration & {
/**
* 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: WorkItemConfiguration;
};
};
/**
* Contains response data for the updateItem operation.
*/
export type WorkItemConfigurationsUpdateItemResponse = WorkItemConfiguration & {
/**
* 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: WorkItemConfiguration;
};
};
/**
* Contains response data for the list operation.
*/
export type FavoritesListResponse = Array<ApplicationInsightsComponentFavorite> & {
/**
* 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: ApplicationInsightsComponentFavorite[];
};
};
/**
* Contains response data for the get operation.
*/
export type FavoritesGetResponse = ApplicationInsightsComponentFavorite & {
/**
* 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: ApplicationInsightsComponentFavorite;
};
};
/**
* Contains response data for the add operation.
*/
export type FavoritesAddResponse = ApplicationInsightsComponentFavorite & {
/**
* 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: ApplicationInsightsComponentFavorite;
};
};
/**
* Contains response data for the update operation.
*/
export type FavoritesUpdateResponse = ApplicationInsightsComponentFavorite & {
/**
* 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: ApplicationInsightsComponentFavorite;
};
};
/**
* Contains response data for the list operation.
*/
export type WebTestLocationsListResponse = ApplicationInsightsWebTestLocationsListResult & {
/**
* 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: ApplicationInsightsWebTestLocationsListResult;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type WebTestsListByResourceGroupResponse = WebTestListResult & {
/**
* 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: WebTestListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type WebTestsGetResponse = WebTest & {
/**
* 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: WebTest;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type WebTestsCreateOrUpdateResponse = WebTest & {
/**
* 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: WebTest;
};
};
/**
* Contains response data for the updateTags operation.
*/
export type WebTestsUpdateTagsResponse = WebTest & {
/**
* 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: WebTest;
};
};
/**
* Contains response data for the list operation.
*/
export type WebTestsListResponse = WebTestListResult & {
/**
* 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: WebTestListResult;
};
};
/**
* Contains response data for the listByComponent operation.
*/
export type WebTestsListByComponentResponse = WebTestListResult & {
/**
* 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: WebTestListResult;
};
};
/**
* Contains response data for the listByResourceGroupNext operation.
*/
export type WebTestsListByResourceGroupNextResponse = WebTestListResult & {
/**
* 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: WebTestListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type WebTestsListNextResponse = WebTestListResult & {
/**
* 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: WebTestListResult;
};
};
/**
* Contains response data for the listByComponentNext operation.
*/
export type WebTestsListByComponentNextResponse = WebTestListResult & {
/**
* 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: WebTestListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type AnalyticsItemsListResponse = Array<ApplicationInsightsComponentAnalyticsItem> & {
/**
* 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: ApplicationInsightsComponentAnalyticsItem[];
};
};
/**
* Contains response data for the get operation.
*/
export type AnalyticsItemsGetResponse = ApplicationInsightsComponentAnalyticsItem & {
/**
* 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: ApplicationInsightsComponentAnalyticsItem;
};
};
/**
* Contains response data for the put operation.
*/
export type AnalyticsItemsPutResponse = ApplicationInsightsComponentAnalyticsItem & {
/**
* 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: ApplicationInsightsComponentAnalyticsItem;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type WorkbooksListByResourceGroupResponse = WorkbooksListResult & {
/**
* 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: WorkbooksListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type WorkbooksGetResponse = Workbook & {
/**
* 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: Workbook;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type WorkbooksCreateOrUpdateResponse = Workbook & {
/**
* 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: Workbook;
};
};
/**
* Contains response data for the update operation.
*/
export type WorkbooksUpdateResponse = Workbook & {
/**
* 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: Workbook;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type MyWorkbooksListByResourceGroupResponse = MyWorkbooksListResult & {
/**
* 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: MyWorkbooksListResult;
};
};
/**
* Contains response data for the listBySubscription operation.
*/
export type MyWorkbooksListBySubscriptionResponse = MyWorkbooksListResult & {
/**
* 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: MyWorkbooksListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type MyWorkbooksGetResponse = MyWorkbook & {
/**
* 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: MyWorkbook;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type MyWorkbooksCreateOrUpdateResponse = MyWorkbook & {
/**
* 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: MyWorkbook;
};
};
/**
* Contains response data for the update operation.
*/
export type MyWorkbooksUpdateResponse = MyWorkbook & {
/**
* 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: MyWorkbook;
};
};
/**
* Contains response data for the list operation.
*/
export type ComponentsListResponse = ApplicationInsightsComponentListResult & {
/**
* 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: ApplicationInsightsComponentListResult;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type ComponentsListByResourceGroupResponse = ApplicationInsightsComponentListResult & {
/**
* 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: ApplicationInsightsComponentListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type ComponentsGetResponse = ApplicationInsightsComponent & {
/**
* 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: ApplicationInsightsComponent;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type ComponentsCreateOrUpdateResponse = ApplicationInsightsComponent & {
/**
* 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: ApplicationInsightsComponent;
};
};
/**
* Contains response data for the updateTags operation.
*/
export type ComponentsUpdateTagsResponse = ApplicationInsightsComponent & {
/**
* 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: ApplicationInsightsComponent;
};
};
/**
* Contains response data for the purge operation.
*/
export type ComponentsPurgeResponse = ComponentPurgeResponse & {
/**
* 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: ComponentPurgeResponse;
};
};
/**
* Contains response data for the getPurgeStatus operation.
*/
export type ComponentsGetPurgeStatusResponse = ComponentPurgeStatusResponse & {
/**
* 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: ComponentPurgeStatusResponse;
};
};
/**
* Contains response data for the listNext operation.
*/
export type ComponentsListNextResponse = ApplicationInsightsComponentListResult & {
/**
* 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: ApplicationInsightsComponentListResult;
};
};
/**
* Contains response data for the listByResourceGroupNext operation.
*/
export type ComponentsListByResourceGroupNextResponse = ApplicationInsightsComponentListResult & {
/**
* 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: ApplicationInsightsComponentListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type ComponentLinkedStorageAccountsGetResponse = ComponentLinkedStorageAccounts & {
/**
* 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: ComponentLinkedStorageAccounts;
};
};
/**
* Contains response data for the createAndUpdate operation.
*/
export type ComponentLinkedStorageAccountsCreateAndUpdateResponse = ComponentLinkedStorageAccounts & {
/**
* 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: ComponentLinkedStorageAccounts;
};
};
/**
* Contains response data for the update operation.
*/
export type ComponentLinkedStorageAccountsUpdateResponse = ComponentLinkedStorageAccounts & {
/**
* 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: ComponentLinkedStorageAccounts;
};
};
/**
* Contains response data for the get operation.
*/
export type LiveTokenGetResponse = LiveTokenResponse & {
/**
* 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: LiveTokenResponse;
};
}; | the_stack |
declare class AmbientWeatherApi {
constructor(credentials: AmbientWeatherApi.Credentials);
/** Get all weather devices. */
userDevices(): Promise<AmbientWeatherApi.Device[]>;
/** Get data for a single device. */
deviceData(
macAddress: string,
options?: {
endDate?: string | undefined;
limit?: number | undefined;
},
): Promise<AmbientWeatherApi.DeviceData[]>;
/** Connect to the realtime API. */
connect(): void;
/** Disconect from the realtime API. */
disconnect(): void;
/** Subscribe to updates from your devices. */
subscribe(apiKeyOrApiKeys: string | ReadonlyArray<string>): void;
/** Unsubscribe from updates from your devices. */
unsubscribe(apiKeyOrApiKeys: string | ReadonlyArray<string>): void;
on(eventname: 'connect', callback: () => void): void;
on(eventname: 'subscribed', callback: (data: { devices: AmbientWeatherApi.Device[] }) => void): void;
on(
eventname: 'data',
callback: (data: AmbientWeatherApi.DeviceData & { device: AmbientWeatherApi.Device }) => void,
): void;
}
declare namespace AmbientWeatherApi {
interface Credentials {
apiKey: string;
applicationKey: string;
}
interface Device {
macAddress: string;
lastData: DeviceData;
info: DeviceInfo;
}
interface DeviceInfo {
name: string;
coords: DeviceLocation;
}
interface DeviceLocation {
geo: {
type: 'Point';
coordinates: [number, number];
};
elevation: number;
location: string;
address: string;
coords: GeoLocationCoordinate;
}
interface GeoLocationCoordinate {
lat: number;
lon: number;
}
// Docs pulled from: https://github.com/ambient-weather/api-docs/wiki/Device-Data-Specs
interface DeviceData {
/** instantaneous wind direction, 0-360º */
winddir?: number | undefined;
/** instantaneous wind speed, mph */
windspeedmph?: number | undefined;
/** max wind speed in the last 10 minutes, mph */
windgustmph?: number | undefined;
/** Maximum wind speed in last day, mph */
maxdailygust?: number | undefined;
/** Wind direction at which the wind gust occurred, 0-360º */
windgustdir?: number | undefined;
/** Average wind speed, 2 minute average, mph */
windspdmph_avg2m?: number | undefined;
/** Average wind direction, 2 minute average, mph */
winddir_avg2m?: number | undefined;
/** Average wind speed, 10 minute average, mph */
windspdmph_avg10m?: number | undefined;
/** Average wind direction, 10 minute average, 0-360º */
winddir_avg10m?: number | undefined;
/** Outdoor Humidity, 0-100% */
humidity?: number | undefined;
/** Humidity Sensor #1, 0-100% */
humidity1?: number | undefined;
/** Humidity Sensor #2, 0-100% */
humidity2?: number | undefined;
/** Humidity Sensor #3, 0-100% */
humidity3?: number | undefined;
/** Humidity Sensor #4, 0-100% */
humidity4?: number | undefined;
/** Humidity Sensor #5, 0-100% */
humidity5?: number | undefined;
/** Humidity Sensor #6, 0-100% */
humidity6?: number | undefined;
/** Humidity Sensor #7, 0-100% */
humidity7?: number | undefined;
/** Humidity Sensor #8, 0-100% */
humidity8?: number | undefined;
/** Humidity Sensor #9, 0-100% */
humidity9?: number | undefined;
/** Humidity Sensor #10, 0-100% */
humidity10?: number | undefined;
/** Indoor Humidity, 0-100% */
humidityin?: number | undefined;
/** Outdoor Temperature, ºF */
tempf?: number | undefined;
/** Temperature Sensor #1, ºF */
temp1f?: number | undefined;
/** Temperature Sensor #2, ºF */
temp2f?: number | undefined;
/** Temperature Sensor #3, ºF */
temp3f?: number | undefined;
/** Temperature Sensor #4, ºF */
temp4f?: number | undefined;
/** Temperature Sensor #5, ºF */
temp5f?: number | undefined;
/** Temperature Sensor #6, ºF */
temp6f?: number | undefined;
/** Temperature Sensor #7, ºF */
temp7f?: number | undefined;
/** Temperature Sensor #8, ºF */
temp8f?: number | undefined;
/** Temperature Sensor #9, ºF */
temp9f?: number | undefined;
/** Temperature Sensor #10, ºF */
temp10f?: number | undefined;
/** Soil Temperature Sensor #1, ºF */
soiltemp1f?: number | undefined;
/** Soil Temperature Sensor #2, ºF */
soiltemp2f?: number | undefined;
/** Soil Temperature Sensor #3, ºF */
soiltemp3f?: number | undefined;
/** Soil Temperature Sensor #4, ºF */
soiltemp4f?: number | undefined;
/** Soil Temperature Sensor #5, ºF */
soiltemp5f?: number | undefined;
/** Soil Temperature Sensor #6, ºF */
soiltemp6f?: number | undefined;
/** Soil Temperature Sensor #7, ºF */
soiltemp7f?: number | undefined;
/** Soil Temperature Sensor #8, ºF */
soiltemp8f?: number | undefined;
/** Soil Temperature Sensor #9, ºF */
soiltemp9f?: number | undefined;
/** Soil Temperature Sensor #10, ºF */
soiltemp10f?: number | undefined;
/** Soil Humidity Sensor #1, % */
soilhum1?: number | undefined;
/** Soil Humidity Sensor #2, % */
soilhum2?: number | undefined;
/** Soil Humidity Sensor #3, % */
soilhum3?: number | undefined;
/** Soil Humidity Sensor #4, % */
soilhum4?: number | undefined;
/** Soil Humidity Sensor #5, % */
soilhum5?: number | undefined;
/** Soil Humidity Sensor #6, % */
soilhum6?: number | undefined;
/** Soil Humidity Sensor #7, % */
soilhum7?: number | undefined;
/** Soil Humidity Sensor #8, % */
soilhum8?: number | undefined;
/** Soil Humidity Sensor #9, % */
soilhum9?: number | undefined;
/** Soil Humidity Sensor #10, % */
soilhum10?: number | undefined;
/** Indoor Temperature, ºF */
tempinf?: number | undefined;
/** OK/Low indication, Int, 1=OK, 0=Low (Meteobridge Users 1=Low, 0=OK) */
battout?: number | undefined;
/** OK/Low indication, Int, 1=OK, 0=Low (Meteobridge Users 1=Low, 0=OK) */
battin?: number | undefined;
/** OK/Low indication, Int, 1=OK, 0=Low (Meteobridge Users 1=Low, 0=OK) */
batt1?: number | undefined;
/** OK/Low indication, Int, 1=OK, 0=Low (Meteobridge Users 1=Low, 0=OK) */
batt2?: number | undefined;
/** OK/Low indication, Int, 1=OK, 0=Low (Meteobridge Users 1=Low, 0=OK) */
batt3?: number | undefined;
/** OK/Low indication, Int, 1=OK, 0=Low (Meteobridge Users 1=Low, 0=OK) */
batt4?: number | undefined;
/** OK/Low indication, Int, 1=OK, 0=Low (Meteobridge Users 1=Low, 0=OK) */
batt5?: number | undefined;
/** OK/Low indication, Int, 1=OK, 0=Low (Meteobridge Users 1=Low, 0=OK) */
batt6?: number | undefined;
/** OK/Low indication, Int, 1=OK, 0=Low (Meteobridge Users 1=Low, 0=OK) */
batt7?: number | undefined;
/** OK/Low indication, Int, 1=OK, 0=Low (Meteobridge Users 1=Low, 0=OK) */
batt8?: number | undefined;
/** OK/Low indication, Int, 1=OK, 0=Low (Meteobridge Users 1=Low, 0=OK) */
batt9?: number | undefined;
/** OK/Low indication, Int, 1=OK, 0=Low (Meteobridge Users 1=Low, 0=OK) */
batt10?: number | undefined;
/** PM2.5 Air Quality Sensor Battery indication, OK/Low indication, Int, 1=OK, 0=Low (Meteobridge Users 1=Low, 0=OK) */
batt_25?: number | undefined;
/** Hourly Rain Rate, in/hr */
hourlyrainin?: number | undefined;
/** Daily Rain, in */
dailyrainin?: number | undefined;
/** 24 Hour Rain, in */
'24hourrainin'?: number | undefined;
/** Weekly Rain, in */
weeklyrainin?: number | undefined;
/** Monthly Rain, in */
monthlyrainin?: number | undefined;
/** Yearly Rain, in */
yearlyrainin?: number | undefined;
/** Event Rain, in */
eventrainin?: number | undefined;
/** Total Rain, in (since last factory reset) */
totalrainin?: number | undefined;
/** Relative Pressure, inHg */
baromrelin?: number | undefined;
/** Absolute Pressure, inHg */
baromabsin?: number | undefined;
/** Ultra-Violet Radiation Index, integer on all devices EXCEPT WS-8478. */
uv?: number | undefined;
/** Solar Radiation, W/m^2 */
solarradiation?: number | undefined;
/** CO2 Meter, ppm */
co2?: number | undefined;
/** Relay 1, 0 or 1 */
relay1?: number | undefined;
/** Relay 2, 0 or 1 */
relay2?: number | undefined;
/** Relay 3, 0 or 1 */
relay3?: number | undefined;
/** Relay 4, 0 or 1 */
relay4?: number | undefined;
/** Relay 5, 0 or 1 */
relay5?: number | undefined;
/** Relay 6, 0 or 1 */
relay6?: number | undefined;
/** Relay 7, 0 or 1 */
relay7?: number | undefined;
/** Relay 8, 0 or 1 */
relay8?: number | undefined;
/** Relay 9, 0 or 1 */
relay9?: number | undefined;
/** Relay 10, 0 or 1 */
relay10?: number | undefined;
/** PM2.5 Air Quality, Float, µg/m^3 */
pm25?: number | undefined;
/** PM2.5 Air Quality 24 hour average, Float, µg/m^3 */
pm25_24h?: number | undefined;
/** PM2.5 Air Quality, Indoor, Float, µg/m^3 */
pm25_in?: number | undefined;
/** PM2.5 Air Quality 24 hour average, Indoor, Float, µg/m^3 */
pm25_in_24h?: number | undefined;
// No official documentation for this properties
feelsLike?: number | undefined;
dewPoint?: number | undefined;
feelsLikein?: number | undefined;
dewPointin?: number | undefined;
batt_co2?: string | undefined;
lastRain?: string | undefined;
/** IANA Time Zone, String */
tz: string;
/** Date, int (milliseconds from 01-01-1970, rounded down to nearest minute on server) */
dateutc: number;
date: string;
}
}
export = AmbientWeatherApi; | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type InboxOldQueryVariables = {};
export type InboxOldQueryResponse = {
readonly me: {
readonly " $fragmentRefs": FragmentRefs<"InboxOld_me">;
} | null;
};
export type InboxOldQuery = {
readonly response: InboxOldQueryResponse;
readonly variables: InboxOldQueryVariables;
};
/*
query InboxOldQuery {
me {
...InboxOld_me
id
}
}
fragment ActiveBid_bid on LotStanding {
is_leading_bidder: isLeadingBidder
sale {
href
is_live_open: isLiveOpen
id
}
most_recent_bid: mostRecentBid {
id
sale_artwork: saleArtwork {
artwork {
href
image {
url
}
artist_names: artistNames
id
}
counts {
bidder_positions: bidderPositions
}
highest_bid: highestBid {
display
}
lot_label: lotLabel
reserve_status: reserveStatus
id
}
}
}
fragment ActiveBids_me on Me {
lot_standings: lotStandings(live: true) {
most_recent_bid: mostRecentBid {
id
}
...ActiveBid_bid
}
}
fragment ConversationSnippet_conversation on Conversation {
internalID
to {
name
id
}
lastMessage
lastMessageAt
unread
items {
item {
__typename
... on Artwork {
date
title
artistNames
image {
url
}
}
... on Show {
fair {
name
id
}
name
coverImage {
url
}
}
... on Node {
__isNode: __typename
id
}
}
}
}
fragment Conversations_me on Me {
conversations: conversationsConnection(first: 10, after: "") {
pageInfo {
endCursor
hasNextPage
}
edges {
node {
internalID
last_message: lastMessage
...ConversationSnippet_conversation
items {
item {
__typename
... on Artwork {
internalID
partner {
internalID
id
}
}
... on Node {
__isNode: __typename
id
}
}
}
id
__typename
}
cursor
}
totalUnreadCount
}
}
fragment InboxOld_me on Me {
lot_standings: lotStandings(live: true) {
most_recent_bid: mostRecentBid {
id
}
}
conversations_existence_check: conversationsConnection(first: 1) {
edges {
node {
internalID
id
}
}
}
...Conversations_me
...ActiveBids_me
}
*/
const node: ConcreteRequest = (function(){
var v0 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v1 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "href",
"storageKey": null
},
v2 = [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "url",
"storageKey": null
}
],
v3 = {
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": (v2/*: any*/),
"storageKey": null
},
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
},
v5 = [
(v4/*: any*/),
(v0/*: any*/)
],
v6 = [
{
"kind": "Literal",
"name": "after",
"value": ""
},
{
"kind": "Literal",
"name": "first",
"value": 10
}
],
v7 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
v8 = [
(v7/*: any*/),
(v0/*: any*/)
],
v9 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
};
return {
"fragment": {
"argumentDefinitions": [],
"kind": "Fragment",
"metadata": null,
"name": "InboxOldQuery",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "InboxOld_me"
}
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": [],
"kind": "Operation",
"name": "InboxOldQuery",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"alias": "lot_standings",
"args": [
{
"kind": "Literal",
"name": "live",
"value": true
}
],
"concreteType": "LotStanding",
"kind": "LinkedField",
"name": "lotStandings",
"plural": true,
"selections": [
{
"alias": "most_recent_bid",
"args": null,
"concreteType": "BidderPosition",
"kind": "LinkedField",
"name": "mostRecentBid",
"plural": false,
"selections": [
(v0/*: any*/),
{
"alias": "sale_artwork",
"args": null,
"concreteType": "SaleArtwork",
"kind": "LinkedField",
"name": "saleArtwork",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "artwork",
"plural": false,
"selections": [
(v1/*: any*/),
(v3/*: any*/),
{
"alias": "artist_names",
"args": null,
"kind": "ScalarField",
"name": "artistNames",
"storageKey": null
},
(v0/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "SaleArtworkCounts",
"kind": "LinkedField",
"name": "counts",
"plural": false,
"selections": [
{
"alias": "bidder_positions",
"args": null,
"kind": "ScalarField",
"name": "bidderPositions",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": "highest_bid",
"args": null,
"concreteType": "SaleArtworkHighestBid",
"kind": "LinkedField",
"name": "highestBid",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "display",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": "lot_label",
"args": null,
"kind": "ScalarField",
"name": "lotLabel",
"storageKey": null
},
{
"alias": "reserve_status",
"args": null,
"kind": "ScalarField",
"name": "reserveStatus",
"storageKey": null
},
(v0/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
},
{
"alias": "is_leading_bidder",
"args": null,
"kind": "ScalarField",
"name": "isLeadingBidder",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Sale",
"kind": "LinkedField",
"name": "sale",
"plural": false,
"selections": [
(v1/*: any*/),
{
"alias": "is_live_open",
"args": null,
"kind": "ScalarField",
"name": "isLiveOpen",
"storageKey": null
},
(v0/*: any*/)
],
"storageKey": null
}
],
"storageKey": "lotStandings(live:true)"
},
{
"alias": "conversations_existence_check",
"args": [
{
"kind": "Literal",
"name": "first",
"value": 1
}
],
"concreteType": "ConversationConnection",
"kind": "LinkedField",
"name": "conversationsConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ConversationEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Conversation",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": (v5/*: any*/),
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "conversationsConnection(first:1)"
},
{
"alias": "conversations",
"args": (v6/*: any*/),
"concreteType": "ConversationConnection",
"kind": "LinkedField",
"name": "conversationsConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "PageInfo",
"kind": "LinkedField",
"name": "pageInfo",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endCursor",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "hasNextPage",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ConversationEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Conversation",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v4/*: any*/),
{
"alias": "last_message",
"args": null,
"kind": "ScalarField",
"name": "lastMessage",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ConversationResponder",
"kind": "LinkedField",
"name": "to",
"plural": false,
"selections": (v8/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "lastMessage",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "lastMessageAt",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "unread",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ConversationItem",
"kind": "LinkedField",
"name": "items",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "item",
"plural": false,
"selections": [
(v9/*: any*/),
{
"kind": "InlineFragment",
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "date",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "title",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "artistNames",
"storageKey": null
},
(v3/*: any*/),
(v4/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Partner",
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": (v5/*: any*/),
"storageKey": null
}
],
"type": "Artwork",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Fair",
"kind": "LinkedField",
"name": "fair",
"plural": false,
"selections": (v8/*: any*/),
"storageKey": null
},
(v7/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "coverImage",
"plural": false,
"selections": (v2/*: any*/),
"storageKey": null
}
],
"type": "Show",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": [
(v0/*: any*/)
],
"type": "Node",
"abstractKey": "__isNode"
}
],
"storageKey": null
}
],
"storageKey": null
},
(v0/*: any*/),
(v9/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cursor",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "totalUnreadCount",
"storageKey": null
}
],
"storageKey": "conversationsConnection(after:\"\",first:10)"
},
{
"alias": "conversations",
"args": (v6/*: any*/),
"filters": null,
"handle": "connection",
"key": "Conversations_conversations",
"kind": "LinkedHandle",
"name": "conversationsConnection"
},
(v0/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"id": "1994027d53b8324bb15e1dd49550558c",
"metadata": {},
"name": "InboxOldQuery",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = 'eae0abe64a27d2e666699ca914538dc3';
export default node; | the_stack |
import Conditions from '../../../../../resources/conditions';
import NetRegexes from '../../../../../resources/netregexes';
import Outputs from '../../../../../resources/outputs';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
export interface Data extends RaidbossData {
stackMarker?: string[];
}
// O9N - Alphascape 1.0
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.AlphascapeV10,
timelineFile: 'o9n.txt',
triggers: [
{
id: 'O9N Chaotic Dispersion',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '314F', source: 'Chaos' }),
netRegexDe: NetRegexes.startsUsing({ id: '314F', source: 'Chaos' }),
netRegexFr: NetRegexes.startsUsing({ id: '314F', source: 'Chaos' }),
netRegexJa: NetRegexes.startsUsing({ id: '314F', source: 'カオス' }),
netRegexCn: NetRegexes.startsUsing({ id: '314F', source: '卡奥斯' }),
netRegexKo: NetRegexes.startsUsing({ id: '314F', source: '카오스' }),
response: Responses.tankBuster(),
},
{
id: 'O9N Orbs Fiend',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '315C', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '315C', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '315C', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '315C', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '315C', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '315C', source: '카오스', capture: false }),
condition: (data) => data.role === 'tank',
alarmText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Orb Tethers',
de: 'Kugel-Verbindungen',
fr: 'Attrapez les orbes',
ja: '線',
cn: '连线',
ko: '구슬 줄',
},
},
},
{
id: 'O9N Entropy',
type: 'GainsEffect',
// This corresponds with an 0060 headmarker.
netRegex: NetRegexes.gainsEffect({ effectId: '640' }),
condition: Conditions.targetIsYou(),
// Entropy comes out with 8 and 14 seconds during the Fire phase, for two sets of spreads.
// During the midphase, it is only 14. To make this less complicated, add a delay that
// makes this work for all three cases.
delaySeconds: (_data, matches) => parseFloat(matches.duration) - 6,
response: Responses.spread(),
},
{
id: 'O9N Dynamic Fluid',
type: 'GainsEffect',
// This corresponds with an 0099 headmarker.
netRegex: NetRegexes.gainsEffect({ effectId: '641' }),
// Dynamic Fluid is 8 and 14 seconds during the Water phase. During midphase, it is 20.
// However, in all cases, there's no reason not to pre-position the donut stack.
condition: Conditions.targetIsYou(),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Stack for Donuts',
de: 'Für Donuts sammeln',
fr: 'Packez-vous pour l\'aoe en donut',
cn: '集合水环',
ko: '모여서 도넛장판 피하기',
},
},
},
{
id: 'O9N Blaze',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3165', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3165', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3165', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3165', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3165', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3165', source: '카오스', capture: false }),
response: Responses.aoe(),
},
{
id: 'O9N Tsunami',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3166', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3166', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3166', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3166', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3166', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3166', source: '카오스', capture: false }),
response: Responses.aoe(),
},
{
id: 'O9N Cyclone',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3167', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3167', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3167', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3167', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3167', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3167', source: '카오스', capture: false }),
response: Responses.aoe(),
},
{
id: 'O9N Earthquake',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3168', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3168', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3168', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3168', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3168', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3168', source: '카오스', capture: false }),
response: Responses.aoe(),
},
{
id: 'O9N Bowels of Agony',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3169', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3169', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3169', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3169', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3169', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3169', source: '카오스', capture: false }),
response: Responses.bigAoe(),
},
{
id: 'O9N Knockdown',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0057' }),
condition: Conditions.targetIsYou(),
alarmText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
// This isn't quite "flare on you", because there's a follow-up large ground
// "Big Bang" circle that appears from where this is dropped, on top of the
// proximity damage. So this is trying to communicate more of a GTFO.
en: 'Drop Flare Away',
de: 'Flare weit weg ablegen',
fr: 'Déposez les Brasiers au loin',
cn: '核爆放在远处',
ko: '플레어 바깥으로 유도',
},
},
},
{
id: 'O9N Stack Collect',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '003E' }),
// these stack markers come out in pairs, so collect them.
run: (data, matches) => (data.stackMarker ??= []).push(matches.target),
},
{
id: 'O9N Stack',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '003E', capture: false }),
delaySeconds: 0.5,
suppressSeconds: 1,
alertText: (data, _matches, output) => {
if (data.stackMarker?.includes(data.me))
return output.stackOnYou!();
return output.stackGroups!();
},
run: (data) => delete data.stackMarker,
outputStrings: {
stackOnYou: Outputs.stackOnYou,
stackGroups: {
en: 'Split into stack groups',
de: 'In Sammel-Gruppen aufteilen',
fr: 'Séparez les groupes et packez-vous',
cn: '分组分摊',
ko: '쉐어징끼리 떨어지기',
},
},
},
{
id: 'O9N Earthquake Knockback',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3148', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3148', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3148', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3148', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3148', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3148', source: '카오스', capture: false }),
response: Responses.knockback(),
},
{
id: 'O9N Cyclone Knockback',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '316D', source: 'Chaos', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '316D', source: 'Chaos', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '316D', source: 'Chaos', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '316D', source: 'カオス', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '316D', source: '卡奥斯', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '316D', source: '카오스', capture: false }),
response: Responses.knockback(),
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'Chaos': 'Chaos',
'YOU DARE!': 'Wie könnt ihr es wagen?!',
},
'replaceText': {
'Big Bang': 'Quantengravitation',
'Blaze': 'Flamme',
'Bowels of Agony': 'Quälende Eingeweide',
'Chaosphere': 'Chaossphäre',
'Chaotic Dispersion': 'Chaos-Dispersion',
'Cyclone': 'Tornado',
'Damning Edict': 'Verdammendes Edikt',
'Earthquake': 'Erdbeben',
'Fiendish Orbs': 'Höllenkugeln',
'Knock(?! )': 'Einschlag',
'Long/Lat Implosion': 'Horizontale/Vertikale Implosion',
'Soul of Chaos': 'Chaosseele',
'Stray Flames': 'Chaosflammen',
'Stray Spray': 'Chaosspritzer',
'Tsunami': 'Tsunami',
},
},
{
'locale': 'fr',
'replaceSync': {
'Chaos': 'Chaos',
'YOU DARE!': '... Mon cristal !? Impossible !',
},
'replaceText': {
'Big Bang': 'Saillie',
'Blaze': 'Flammes',
'Bowels of Agony': 'Entrailles de l\'agonie',
'Chaosphere': 'Sphère de chaos',
'Chaotic Dispersion': 'Dispersion chaotique',
'Cyclone': 'Tornade',
'Damning Edict': 'Décret accablant',
'Earthquake': 'Grand séisme',
'Fiendish Orbs': 'Ordre de poursuite',
'Knock(?! )': 'Impact',
'Long/Lat Implosion': 'Implosion Hz/Vert',
'Soul of Chaos': 'Âme du chaos',
'Stray Flames': 'Flammes du chaos',
'Stray Spray': 'Eaux du chaos',
'Tsunami': 'Raz-de-marée',
},
},
{
'locale': 'ja',
'replaceSync': {
'Chaos': 'カオス',
'YOU DARE!': 'まさか……黒水晶を……!?',
},
'replaceText': {
'Big Bang': '突出せよ',
'Blaze': 'ほのお',
'Bowels of Agony': 'バウル・オブ・アゴニー',
'Chaosphere': 'カオススフィア',
'Chaotic Dispersion': 'カオティックディスパーション',
'Cyclone': 'たつまき',
'Damning Edict': 'ダミングイーディクト',
'Earthquake': 'じしん',
'Fiendish Orbs': '追尾せよ',
'Knock(?! )': '着弾',
'Long/Lat Implosion': 'インプロージョン 横/縦',
'Soul of Chaos': 'ソウル・オブ・カオス',
'Stray Flames': '混沌の炎',
'Stray Spray': '混沌の水',
'Tsunami': 'つなみ',
},
},
{
'locale': 'cn',
'replaceSync': {
'Chaos': '卡奥斯',
'YOU DARE!': '居然……把黑水晶给……',
},
'replaceText': {
'Big Bang': '顶起',
'Blaze': '烈焰',
'Bowels of Agony': '深层痛楚',
'Chaosphere': '混沌晶球',
'Chaotic Dispersion': '散布混沌',
'Cyclone': '龙卷风',
'Damning Edict': '诅咒敕令',
'Earthquake': '大地震',
'Fiendish Orbs': '追踪',
'Knock(?! )': '中弹',
'Long/Lat Implosion': '经/纬度聚爆',
'Soul of Chaos': '混沌之魂',
'Stray Flames': '混沌之炎',
'Stray Spray': '混沌之水',
'Tsunami': '海啸',
},
},
{
'locale': 'ko',
'replaceSync': {
'Chaos': '카오스',
'YOU DARE!': '네 이노오오옴',
},
'replaceText': {
'Big Bang': '돌출하라',
'Blaze': '화염',
'Bowels of Agony': '고통의 심핵',
'Chaosphere': '혼돈의 구체',
'Chaotic Dispersion': '혼돈 유포',
'Cyclone': '회오리',
'Damning Edict': '파멸 포고',
'Earthquake': '대지진',
'Fiendish Orbs': '추격하라',
'Knock': '착탄',
'Long/Lat Implosion': '가로/세로 내파',
'Soul of Chaos': '혼돈의 영혼',
'Stray Flames': '혼돈의 불',
'Stray Spray': '혼돈의 물',
'Tsunami': '해일',
},
},
],
};
export default triggerSet; | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [workdocs](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonworkdocs.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Workdocs extends PolicyStatement {
public servicePrefix = 'workdocs';
/**
* Statement provider for service [workdocs](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonworkdocs.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to abort the upload of the specified document version that was previously initiated by InitiateDocumentVersionUpload.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_AbortDocumentVersionUpload.html
*/
public toAbortDocumentVersionUpload() {
return this.to('AbortDocumentVersionUpload');
}
/**
* Grants permission to activate the specified user. Only active users can access Amazon WorkDocs.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_ActivateUser.html
*/
public toActivateUser() {
return this.to('ActivateUser');
}
/**
* Grants permission to create a set of permissions for the specified folder or document.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_AddResourcePermissions.html
*/
public toAddResourcePermissions() {
return this.to('AddResourcePermissions');
}
/**
* Grants permission to add a user to a group.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/adminguide/manage_set_admin.html
*/
public toAddUserToGroup() {
return this.to('AddUserToGroup');
}
/**
* Grants permission to check an alias.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/workdocs/latest/adminguide/cloud_quick_start.html
*/
public toCheckAlias() {
return this.to('CheckAlias');
}
/**
* Grants permission to add a new comment to the specified document version.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_CreateComment.html
*/
public toCreateComment() {
return this.to('CreateComment');
}
/**
* Grants permission to add one or more custom properties to the specified resource.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_CreateCustomMetadata.html
*/
public toCreateCustomMetadata() {
return this.to('CreateCustomMetadata');
}
/**
* Grants permission to create a folder with the specified name and parent folder.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_CreateFolder.html
*/
public toCreateFolder() {
return this.to('CreateFolder');
}
/**
* Grants permission to create an instance.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/adminguide/getting_started.html
*/
public toCreateInstance() {
return this.to('CreateInstance');
}
/**
* Grants permission to add labels to the given resource.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_CreateLabels.html
*/
public toCreateLabels() {
return this.to('CreateLabels');
}
/**
* Grants permission to configure WorkDocs to use Amazon SNS notifications.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_CreateNotificationSubscription.html
*/
public toCreateNotificationSubscription() {
return this.to('CreateNotificationSubscription');
}
/**
* Grants permission to create a user in a Simple AD or Microsoft AD directory.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_CreateUser.html
*/
public toCreateUser() {
return this.to('CreateUser');
}
/**
* Grants permission to deactivate the specified user, which revokes the user's access to Amazon WorkDocs.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DeactivateUser.html
*/
public toDeactivateUser() {
return this.to('DeactivateUser');
}
/**
* Grants permission to delete the specified comment from the document version.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DeleteComment.html
*/
public toDeleteComment() {
return this.to('DeleteComment');
}
/**
* Grants permission to delete custom metadata from the specified resource.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DeleteCustomMetadata.html
*/
public toDeleteCustomMetadata() {
return this.to('DeleteCustomMetadata');
}
/**
* Grants permission to permanently delete the specified document and its associated metadata.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DeleteDocument.html
*/
public toDeleteDocument() {
return this.to('DeleteDocument');
}
/**
* Grants permission to permanently delete the specified folder and its contents.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DeleteFolder.html
*/
public toDeleteFolder() {
return this.to('DeleteFolder');
}
/**
* Grants permission to delete the contents of the specified folder.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DeleteFolderContents.html
*/
public toDeleteFolderContents() {
return this.to('DeleteFolderContents');
}
/**
* Grants permission to delete an instance.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/adminguide/manage-sites.html#delete_site
*/
public toDeleteInstance() {
return this.to('DeleteInstance');
}
/**
* Grants permission to delete one or more labels from a resource.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DeleteLabels.html
*/
public toDeleteLabels() {
return this.to('DeleteLabels');
}
/**
* Grants permission to delete the specified subscription from the specified organization.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DeleteNotificationSubscription.html
*/
public toDeleteNotificationSubscription() {
return this.to('DeleteNotificationSubscription');
}
/**
* Grants permission to delete the specified user from a Simple AD or Microsoft AD directory.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DeleteUser.html
*/
public toDeleteUser() {
return this.to('DeleteUser');
}
/**
* Grants permission to deregister a directory.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/adminguide/manage-sites.html#delete_site
*/
public toDeregisterDirectory() {
return this.to('DeregisterDirectory');
}
/**
* Grants permission to fetch user activities in a specified time period.
*
* Access Level: List
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DescribeActivities.html
*/
public toDescribeActivities() {
return this.to('DescribeActivities');
}
/**
* Grants permission to describe available directories.
*
* Access Level: List
*
* https://docs.aws.amazon.com/workdocs/latest/adminguide/getting_started.html
*/
public toDescribeAvailableDirectories() {
return this.to('DescribeAvailableDirectories');
}
/**
* Grants permission to list all the comments for the specified document version.
*
* Access Level: List
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DescribeComments.html
*/
public toDescribeComments() {
return this.to('DescribeComments');
}
/**
* Grants permission to retrieve the document versions for the specified document.
*
* Access Level: List
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DescribeDocumentVersions.html
*/
public toDescribeDocumentVersions() {
return this.to('DescribeDocumentVersions');
}
/**
* Grants permission to describe the contents of the specified folder, including its documents and sub-folders.
*
* Access Level: List
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DescribeFolderContents.html
*/
public toDescribeFolderContents() {
return this.to('DescribeFolderContents');
}
/**
* Grants permission to describe the user groups.
*
* Access Level: List
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DescribeGroups.html
*/
public toDescribeGroups() {
return this.to('DescribeGroups');
}
/**
* Grants permission to describe instances.
*
* Access Level: List
*
* https://docs.aws.amazon.com/workdocs/latest/adminguide/getting_started.html
*/
public toDescribeInstances() {
return this.to('DescribeInstances');
}
/**
* Grants permission to list the specified notification subscriptions.
*
* Access Level: List
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DescribeNotificationSubscriptions.html
*/
public toDescribeNotificationSubscriptions() {
return this.to('DescribeNotificationSubscriptions');
}
/**
* Grants permission to view a description of a specified resource's permissions.
*
* Access Level: List
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DescribeResourcePermissions.html
*/
public toDescribeResourcePermissions() {
return this.to('DescribeResourcePermissions');
}
/**
* Grants permission to describe the root folders.
*
* Access Level: List
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DescribeRootFolders.html
*/
public toDescribeRootFolders() {
return this.to('DescribeRootFolders');
}
/**
* Grants permission to view a description of the specified users. You can describe all users or filter the results (for example, by status or organization).
*
* Access Level: List
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_DescribeUsers.html
*/
public toDescribeUsers() {
return this.to('DescribeUsers');
}
/**
* Grants permission to download a specified document version.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_GetDocumentVersion.html
*/
public toDownloadDocumentVersion() {
return this.to('DownloadDocumentVersion');
}
/**
* Grants permission to retrieve the details of the current user.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_GetCurrentUser.html
*/
public toGetCurrentUser() {
return this.to('GetCurrentUser');
}
/**
* Grants permission to retrieve the specified document object.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_GetDocument.html
*/
public toGetDocument() {
return this.to('GetDocument');
}
/**
* Grants permission to retrieve the path information (the hierarchy from the root folder) for the requested document.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_GetDocumentPath.html
*/
public toGetDocumentPath() {
return this.to('GetDocumentPath');
}
/**
* Grants permission to retrieve version metadata for the specified document.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_GetDocumentVersion.html
*/
public toGetDocumentVersion() {
return this.to('GetDocumentVersion');
}
/**
* Grants permission to retrieve the metadata of the specified folder.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_GetFolder.html
*/
public toGetFolder() {
return this.to('GetFolder');
}
/**
* Grants permission to retrieve the path information (the hierarchy from the root folder) for the specified folder.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_GetFolderPath.html
*/
public toGetFolderPath() {
return this.to('GetFolderPath');
}
/**
* Grants permission to retrieve details for the specified group.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_Operations.html
*/
public toGetGroup() {
return this.to('GetGroup');
}
/**
* Grants permission to get a collection of resources.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_GetResources.html
*/
public toGetResources() {
return this.to('GetResources');
}
/**
* Grants permission to create a new document object and version object.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_InitiateDocumentVersionUpload.html
*/
public toInitiateDocumentVersionUpload() {
return this.to('InitiateDocumentVersionUpload');
}
/**
* Grants permission to register a directory.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/adminguide/existing-dir-setup.html
*/
public toRegisterDirectory() {
return this.to('RegisterDirectory');
}
/**
* Grants permission to remove all the permissions from the specified resource.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_RemoveAllResourcePermissions.html
*/
public toRemoveAllResourcePermissions() {
return this.to('RemoveAllResourcePermissions');
}
/**
* Grants permission to remove the permission for the specified principal from the specified resource.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_RemoveResourcePermission.html
*/
public toRemoveResourcePermission() {
return this.to('RemoveResourcePermission');
}
/**
* Grants permission to update the specified attributes of the specified document.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_UpdateDocument.html
*/
public toUpdateDocument() {
return this.to('UpdateDocument');
}
/**
* Grants permission to change the status of the document version to ACTIVE.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_UpdateDocumentVersion.html
*/
public toUpdateDocumentVersion() {
return this.to('UpdateDocumentVersion');
}
/**
* Grants permission to update the specified attributes of the specified folder.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_UpdateFolder.html
*/
public toUpdateFolder() {
return this.to('UpdateFolder');
}
/**
* Grants permission to update an instance alias.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/adminguide/getting_started.html
*/
public toUpdateInstanceAlias() {
return this.to('UpdateInstanceAlias');
}
/**
* Grants permission to update the specified attributes of the specified user, and grants or revokes administrative privileges to the Amazon WorkDocs site.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/workdocs/latest/APIReference/API_UpdateUser.html
*/
public toUpdateUser() {
return this.to('UpdateUser');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AbortDocumentVersionUpload",
"ActivateUser",
"AddResourcePermissions",
"AddUserToGroup",
"CreateComment",
"CreateCustomMetadata",
"CreateFolder",
"CreateInstance",
"CreateLabels",
"CreateNotificationSubscription",
"CreateUser",
"DeactivateUser",
"DeleteComment",
"DeleteCustomMetadata",
"DeleteDocument",
"DeleteFolder",
"DeleteFolderContents",
"DeleteInstance",
"DeleteLabels",
"DeleteNotificationSubscription",
"DeleteUser",
"DeregisterDirectory",
"InitiateDocumentVersionUpload",
"RegisterDirectory",
"RemoveAllResourcePermissions",
"RemoveResourcePermission",
"UpdateDocument",
"UpdateDocumentVersion",
"UpdateFolder",
"UpdateInstanceAlias",
"UpdateUser"
],
"Read": [
"CheckAlias",
"DownloadDocumentVersion",
"GetCurrentUser",
"GetDocument",
"GetDocumentPath",
"GetDocumentVersion",
"GetFolder",
"GetFolderPath",
"GetGroup",
"GetResources"
],
"List": [
"DescribeActivities",
"DescribeAvailableDirectories",
"DescribeComments",
"DescribeDocumentVersions",
"DescribeFolderContents",
"DescribeGroups",
"DescribeInstances",
"DescribeNotificationSubscriptions",
"DescribeResourcePermissions",
"DescribeRootFolders",
"DescribeUsers"
]
};
} | the_stack |
import { BehaviorSubject } from "rxjs";
import { debounceTime, distinctUntilChanged } from "rxjs/operators";
import { IProjectEnv } from "src/app/config/types";
import { TeamService } from "src/app/services/team.service";
import { isNotPercentageRollout, isSingleOperator } from "src/app/utils";
import { ruleType, ruleValueConfig } from "../components/find-rule/ruleConfig";
import { IFfParams, IFfpParams, IFftuwmtrParams, IJsonContent, IPrequisiteFeatureFlag, IRulePercentageRollout, IUserType, IVariationOption } from "./switch-new";
export enum InstructionKindEnum {
UpdateStatus = 'updateStatus',
AddUserTargets = 'addUserTargets',
RemoveUserTargets = 'removeUserTargets',
AddRule = 'addRule',
RemoveRule = 'removeRule',
UpdateRuleClause = 'updateRuleClause',
UpdateRuleVariationOrRollout = 'updateRuleVariationOrRollout',
UpdateOffVariation = 'updateOffVariation',
UpdateFallthroughVariationOrRollout = "updateFallthroughVariationOrRollout",
AddPrerequisiteFeature = 'addPrerequisiteFeature',
RemovePrerequisiteFeature = 'removePrerequisiteFeature',
UpdatePrerequisiteFeature = 'updatePrerequisiteFeature'
}
export interface IPendingChange {
id: string;
featureFlagId: string;
envId: number;
projectId: number;
updatedAt: string;
createdAt: string;
instructions: IInstruction[];
}
export interface IInstruction {
kind: InstructionKindEnum;
variationOptionId?: number;
ruleId?: string;
featureFlagId?: string;
clauses?: IJsonContent[];
rolloutWeights?: {[key: string]: number};
rolloutVariationPercentage?: any[]; // dont't need to push to server
targetUsers?: string[];
status?: string;
extra?: any; // dont't need to push to server
}
interface IOriginalFFData {
status: string,
targetIndividuals: {[key: string]: IUserType[]};
fftuwmtr: IFftuwmtrParams[];
fallThroughVariations: IRulePercentageRollout[];
variationOptionWhenDisabled: IVariationOption;
prerequisiteFeatures: IFfpParams[]
}
export class PendingChange {
private data: IPendingChange;
private originalFFData: IOriginalFFData;
private variationOptions = {};
private ffList = [];
public categorizedInstructions: any = [];
constructor(private teamService: TeamService, private accountId: number, public projectEnv: IProjectEnv, public featureFlag: IFfParams, variationOptions: IVariationOption[], private parentUrl: string){
this.data = {
projectId: projectEnv.projectId,
envId: projectEnv.projectId,
featureFlagId: featureFlag.id,
instructions: []
} as IPendingChange;
variationOptions.forEach(v => {
this.variationOptions[v.localId] = v;
})
this.searchChange$.pipe(
debounceTime(500),
distinctUntilChanged()
).subscribe(searchText => {
this.teamService.searchMembers(this.accountId, searchText).subscribe((result) => {
this.reviewerList = result;
this.isReviewersLoading = false;
}, error => {
this.isReviewersLoading = false;
});
});
}
public hasInstruction(): boolean {
return this.data.instructions.length > 0;
}
canSubmit() {
return this.hasInstruction();
}
public setFeatureFlagList(ffList: IPrequisiteFeatureFlag[]) {
this.ffList = ffList;
}
public initialize(
targetIndividuals: {[key: string]: IUserType[]},
variationOptionWhenDisabled: IVariationOption,
fallThroughVariations: IRulePercentageRollout[],
fftuwmtr: IFftuwmtrParams[],
prerequisiteFeatures: IFfpParams[],
status: string
) {
this.originalFFData = {
targetIndividuals: Object.assign({}, targetIndividuals),
fallThroughVariations: fallThroughVariations.map(f => Object.assign({}, f)),
variationOptionWhenDisabled: Object.assign({}, variationOptionWhenDisabled),
fftuwmtr: this.preprocessFftuwmtr(fftuwmtr),
prerequisiteFeatures: prerequisiteFeatures.map(f => Object.assign({}, f)),
status: status
};
}
comment: string = '';
selectedReviewers: any[] = [];
searchChange$ = new BehaviorSubject('');
isReviewersLoading = false;
reviewerList: string[];
onSearchReviewers(value: string): void {
if (value.length > 0) {
this.isReviewersLoading = true;
this.searchChange$.next(value);
}
}
private getVariationValue(variationOptionId: number) {
return this.variationOptions[variationOptionId].variationValue;
}
private generateRuleChanges(ins: IInstruction): string {
const serveStr = `serve ${!!ins.variationOptionId ? this.getVariationValue(ins.variationOptionId) : ins.rolloutVariationPercentage.reduce((acc, cur, idx) => { acc += cur.valueOption.variationValue + ` (${ins.rolloutWeights[cur.valueOption.localId] * 100}%)</span>`; acc += idx === ins.rolloutVariationPercentage.length - 1? '</span>' : '<span>'; return acc;}, '<span>')}`;
const clauseStr = '<ul class="no-style"><li class="clause">'
+ ins.clauses.map(c => `if ${c.property} ${c.operation} ${!isSingleOperator(c.type)? '<span class="ant-tag">' + (c.type === "multi" ? c.multipleValue.join('</span><span class="ant-tag">') : c.value) + '</span>' : ''}`)
.join(`</li> <li class="and">AND</li> <li class="clause">`) + `</li><li>${serveStr}</li></ul>`;
return clauseStr;
}
private getStatusLabel(status: string): string {
if (status === 'Enabled') return '开';
if (status === 'Disabled') return '关';
return '';
}
private categorizeInstructions() {
const categories = {
'status': {
'category': '状态',
'changes': []
},
'prerequisite': {
'category': '上游开关',
'changes': []
},
'individualUsers': {
'category': '目标用户',
'changes': []
},
'rules': {
'category': '匹配规则',
'changes': []
},
'fallThrough': {
'category': '默认返回值',
'changes': []
},
'off': {
'category': '开关关闭时的返回值',
'changes': []
}
};
this.data.instructions.forEach(ins => {
switch(ins.kind) {
case InstructionKindEnum.UpdateStatus:
categories['prerequisite'].changes.push(`更新开关状态到 <span class="ant-tag">${this.getStatusLabel(ins.status)}</span>`);
break;
case InstructionKindEnum.AddPrerequisiteFeature:
categories['prerequisite'].changes.push(`添加上游开关 <a target="_blank" href="${this.parentUrl + ins.extra.selectedFeatureFlag.id}">${ins.extra.selectedFeatureFlag.name}</a>`);
break;
case InstructionKindEnum.RemovePrerequisiteFeature:
categories['prerequisite'].changes.push(`移除上游开关 <a target="_blank" href="${this.parentUrl + ins.extra.selectedFeatureFlag.id}">${ins.extra.selectedFeatureFlag.name}</a>`);
break;
case InstructionKindEnum.UpdatePrerequisiteFeature:
let ff = ins.extra;
categories['prerequisite'].changes.push(`将上游开关 <a target="_blank" href="${this.parentUrl + ff.selectedFeatureFlag.id}">${ff.selectedFeatureFlag.name}</a> 的返回值设置为 <span class="ant-tag"> ${ff.valueOptionsVariationValue.variationValue}</span>`);
break;
case InstructionKindEnum.AddUserTargets:
categories['individualUsers'].changes.push(`向 <span class="ant-tag">${this.getVariationValue(ins.variationOptionId)}</span>添加 ${'<span class="ant-tag">' + ins.targetUsers.join('</span><span class="ant-tag">') + '</span>'}`);
break;
case InstructionKindEnum.RemoveUserTargets:
categories['individualUsers'].changes.push(`从 <span class="ant-tag">${this.getVariationValue(ins.variationOptionId)}</span>移除 ${'<span class="ant-tag">' + ins.targetUsers.join('</span><span class="ant-tag">') + '</span>'}`);
break;
case InstructionKindEnum.AddRule:
categories['rules'].changes.push(`添加: ${ins.extra.ruleName} ${this.generateRuleChanges(ins)}`);
break;
case InstructionKindEnum.RemoveRule:
categories['rules'].changes.push(`移除: ${ins.extra.ruleName} ${this.generateRuleChanges(ins)}`);
break;
// case InstructionKindEnum.UpdateRuleClause: // never happen
// categories['rules'].changes.push(`更新: ${ins.extra.ruleName} ${this.generateRuleChanges(ins)}`);
// break;
case InstructionKindEnum.UpdateRuleVariationOrRollout:
categories['rules'].changes.push(`更新: ${ins.extra.ruleName} ${this.generateRuleChanges(ins)}`);
break;
case InstructionKindEnum.UpdateFallthroughVariationOrRollout:
const defaultStr = `${!!ins.variationOptionId ? this.getVariationValue(ins.variationOptionId) : ins.rolloutVariationPercentage.reduce((acc, cur, idx) => { acc += cur.valueOption.variationValue + ` (${ins.rolloutWeights[cur.valueOption.localId]})</span>`; idx === ins.rolloutVariationPercentage.length - 1? '</span>' : '<span>'; return acc;}, '<span>')}`;
categories['fallThrough'].changes.push(`设置为 ${defaultStr}`);
break;
case InstructionKindEnum.UpdateOffVariation:
categories['off'].changes.push(`设置为 ${this.getVariationValue(ins.variationOptionId)}`);
break;
}
});
this.categorizedInstructions = [
categories['status'],
categories['prerequisite'], categories['individualUsers'], categories['rules'], categories['fallThrough'], categories['off']
];
}
public generateInstructions(
newTargetIndividuals: {[key: string]: IUserType[]},
variationOptionWhenDisabled: IVariationOption,
fallThroughVariations: IRulePercentageRollout[],
fftuwmtr: IFftuwmtrParams[],
prerequisiteFeatures: IFfpParams[],
status: string
) {
this.data.instructions = [];
this.generateUserTargetsInstructions(newTargetIndividuals);
this.generateOffVariationInstruction(variationOptionWhenDisabled);
this.generateFallThroughVariationInstruction(fallThroughVariations);
this.generateFftuwmtrInstruction(fftuwmtr);
this.generatePrerequisiteFeaturesInstruction(prerequisiteFeatures);
this.generateStatusInstruction(status);
this.categorizeInstructions();
}
private generateStatusInstruction(status: string) {
if (this.originalFFData.status !== status) {
this.upInsertInstruction({
kind: InstructionKindEnum.UpdateStatus,
status
});
}
}
private upInsertInstruction(instruction: IInstruction, compareFun?: (a: IInstruction, b: IInstruction) => boolean) {
let idx = -1;
if (!!compareFun) {
idx = this.data.instructions.findIndex(i => compareFun(i, instruction));
} else {
idx = this.data.instructions.findIndex(i => i.kind === instruction.kind && i.variationOptionId === instruction.variationOptionId);
}
if (idx !== -1) {
this.data.instructions.splice(idx, 1);
}
this.data.instructions.push(instruction);
}
private generatePrerequisiteFeaturesInstruction(prerequisiteFeatures: IFfpParams[]) {
this.originalFFData.prerequisiteFeatures.forEach(p => {
const found = prerequisiteFeatures.find(f => p.prerequisiteFeatureFlagId === f.prerequisiteFeatureFlagId);
if (found) {
if (found.valueOptionsVariationValue?.localId !== p.valueOptionsVariationValue?.localId) {
this.upInsertInstruction({
kind: InstructionKindEnum.UpdatePrerequisiteFeature,
featureFlagId: found.prerequisiteFeatureFlagId,
variationOptionId: found.valueOptionsVariationValue.localId,
extra: found
});
}
} else {
const removedFF = this.ffList.find(f => f.id === p.prerequisiteFeatureFlagId);
this.upInsertInstruction({
kind: InstructionKindEnum.RemovePrerequisiteFeature,
featureFlagId: p.prerequisiteFeatureFlagId,
extra: Object.assign({}, p, {selectedFeatureFlag: removedFF})
});
}
});
prerequisiteFeatures.filter(f => !this.originalFFData.prerequisiteFeatures.find(t => t.prerequisiteFeatureFlagId === f.prerequisiteFeatureFlagId))
.forEach(p => {
this.upInsertInstruction({
kind: InstructionKindEnum.AddPrerequisiteFeature,
featureFlagId: p.prerequisiteFeatureFlagId,
variationOptionId: p.valueOptionsVariationValue?.localId,
extra: p
});
})
}
private preprocessFftuwmtr(fftuwmtr: IFftuwmtrParams[]): IFftuwmtrParams[] {
return fftuwmtr.map(f => {
const result = {
ruleJsonContent: f.ruleJsonContent.map(item => {
let result: ruleType = ruleValueConfig.find((rule: ruleType) => rule.value === item.operation);
let multipleValue: string[] = [];
if(result.type === 'multi' && item.multipleValue === undefined) {
multipleValue = JSON.parse(item.value);
}
return Object.assign({ multipleValue: multipleValue, type: result.type }, item);
})
};
return Object.assign({}, f, result);
});
}
private generateFftuwmtrInstruction(fftuwmtr: IFftuwmtrParams[]) {
fftuwmtr = this.preprocessFftuwmtr(fftuwmtr);
this.originalFFData.fftuwmtr.forEach((t, idx) => {
const found = fftuwmtr.find(f => t.ruleId === f.ruleId);
if (found) {
// if (JSON.stringify(found.ruleJsonContent) !== JSON.stringify(t.ruleJsonContent)) {
// this.upInsertInstruction({
// kind: InstructionKindEnum.UpdateRuleClause,
// ruleId: found.ruleId,
// clauses: found.ruleJsonContent
// });
// }
if (JSON.stringify(found.ruleJsonContent) !== JSON.stringify(t.ruleJsonContent) || JSON.stringify(found.valueOptionsVariationRuleValues) !== JSON.stringify(t.valueOptionsVariationRuleValues)) {
this.upInsertInstruction(this.generateRuleInstruction(InstructionKindEnum.UpdateRuleVariationOrRollout, found, idx))
// let instruction;
// if (isNotPercentageRollout(found.valueOptionsVariationRuleValues)) { // single value
// instruction = {
// kind: InstructionKindEnum.UpdateRuleVariationOrRollout,
// variationOptionId: found.valueOptionsVariationRuleValues[0].valueOption.localId,
// };
// } else { // percentage rollout
// instruction = {
// kind: InstructionKindEnum.UpdateRuleVariationOrRollout,
// variationOptionId: null,
// rolloutVariationPercentage: [...found.valueOptionsVariationRuleValues],
// rolloutWeights: found.valueOptionsVariationRuleValues.reduce((acc, curr: IRulePercentageRollout) => {
// acc[curr.valueOption.localId] = parseFloat((curr.rolloutPercentage[1] - curr.rolloutPercentage[0]).toFixed(2));
// return acc;
// }, {})
// };
// }
// this.upInsertInstruction(instruction);
}
} else {
this.upInsertInstruction(this.generateRuleInstruction(InstructionKindEnum.RemoveRule, t, idx))
}
});
fftuwmtr.filter(f => !this.originalFFData.fftuwmtr.find(t => t.ruleId === f.ruleId))
.forEach((r, idx) => this.upInsertInstruction(this.generateRuleInstruction(InstructionKindEnum.AddRule, r, this.originalFFData.fftuwmtr.length + idx)));
}
private generateRuleInstruction(kind: InstructionKindEnum, rule: IFftuwmtrParams, idx: number): IInstruction {
const instruction: IInstruction = {
kind,
ruleId: rule.ruleId,
clauses: rule.ruleJsonContent,
extra: {
ruleName: `规则${idx + 1}`
}
};
if (isNotPercentageRollout(rule.valueOptionsVariationRuleValues)) {
instruction['variationOptionId'] = rule.valueOptionsVariationRuleValues[0].valueOption.localId;
} else {
instruction['rolloutVariationPercentage'] = [...rule.valueOptionsVariationRuleValues];
instruction['rolloutWeights'] = rule.valueOptionsVariationRuleValues.reduce((acc, curr: IRulePercentageRollout) => {
acc[curr.valueOption.localId] = parseFloat((curr.rolloutPercentage[1] - curr.rolloutPercentage[0]).toFixed(2));
return acc;
}, {});
}
return instruction;
}
private generateFallThroughVariationInstruction(fallThroughVariations: IRulePercentageRollout[]) {
if (JSON.stringify(fallThroughVariations) !== JSON.stringify(this.originalFFData.fallThroughVariations)) {
let instruction: IInstruction = null;
if (isNotPercentageRollout(fallThroughVariations)) { // single value
instruction = {
kind: InstructionKindEnum.UpdateFallthroughVariationOrRollout,
variationOptionId: fallThroughVariations[0].valueOption.localId,
};
} else { // percentage rollout
instruction = {
kind: InstructionKindEnum.UpdateFallthroughVariationOrRollout,
variationOptionId: null,
rolloutVariationPercentage: [...fallThroughVariations],
rolloutWeights: fallThroughVariations.reduce((acc, curr: IRulePercentageRollout) => {
acc[curr.valueOption.localId] = parseFloat((curr.rolloutPercentage[1] - curr.rolloutPercentage[0]).toFixed(2));
return acc;
}, {})
};
}
this.upInsertInstruction(instruction, (a: IInstruction, b: IInstruction) => a.kind === b.kind);
}
}
private generateOffVariationInstruction(variationOptionWhenDisabled: IVariationOption) {
if (variationOptionWhenDisabled.localId !== this.originalFFData.variationOptionWhenDisabled.localId) {
this.upInsertInstruction({
kind: InstructionKindEnum.UpdateOffVariation,
variationOptionId: variationOptionWhenDisabled.localId,
});
}
}
private generateUserTargetsInstructions(newTargetIndividuals: {[key: string]: IUserType[]}) {
for(let key in newTargetIndividuals) {
const addedUsers = newTargetIndividuals[key].filter(d => !this.originalFFData.targetIndividuals[key].find(t => t.id === d.id)).map(t => t.name);
const removedUsers = this.originalFFData.targetIndividuals[key].filter(t => !newTargetIndividuals[key].find(d => t.id === d.id)).map(t => t.name);
const variationOptionId: number = parseInt(key);
if (addedUsers.length > 0) {
this.upInsertInstruction({
kind: InstructionKindEnum.AddUserTargets,
variationOptionId,
targetUsers: addedUsers
});
}
if (removedUsers.length > 0) {
this.upInsertInstruction({
kind: InstructionKindEnum.RemoveUserTargets,
variationOptionId,
targetUsers: removedUsers
});
}
}
}
} | the_stack |
export type BGPConfiguration = object;
// BGPConfigurationList is a list of BGPConfiguration
export class BGPConfigurationList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of bgpconfigurations. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: BGPConfiguration[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: BGPConfigurationList.Metadata;
constructor(desc: BGPConfigurationList) {
this.apiVersion = BGPConfigurationList.apiVersion;
this.items = desc.items;
this.kind = BGPConfigurationList.kind;
this.metadata = desc.metadata;
}
}
export function isBGPConfigurationList(o: any): o is BGPConfigurationList {
return (
o &&
o.apiVersion === BGPConfigurationList.apiVersion &&
o.kind === BGPConfigurationList.kind
);
}
export namespace BGPConfigurationList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'BGPConfigurationList';
// BGPConfigurationList is a list of BGPConfiguration
export interface Interface {
// List of bgpconfigurations. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: BGPConfiguration[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: BGPConfigurationList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type BGPPeer = object;
// BGPPeerList is a list of BGPPeer
export class BGPPeerList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of bgppeers. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: BGPPeer[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: BGPPeerList.Metadata;
constructor(desc: BGPPeerList) {
this.apiVersion = BGPPeerList.apiVersion;
this.items = desc.items;
this.kind = BGPPeerList.kind;
this.metadata = desc.metadata;
}
}
export function isBGPPeerList(o: any): o is BGPPeerList {
return (
o && o.apiVersion === BGPPeerList.apiVersion && o.kind === BGPPeerList.kind
);
}
export namespace BGPPeerList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'BGPPeerList';
// BGPPeerList is a list of BGPPeer
export interface Interface {
// List of bgppeers. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: BGPPeer[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: BGPPeerList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type BlockAffinity = object;
// BlockAffinityList is a list of BlockAffinity
export class BlockAffinityList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of blockaffinities. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: BlockAffinity[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: BlockAffinityList.Metadata;
constructor(desc: BlockAffinityList) {
this.apiVersion = BlockAffinityList.apiVersion;
this.items = desc.items;
this.kind = BlockAffinityList.kind;
this.metadata = desc.metadata;
}
}
export function isBlockAffinityList(o: any): o is BlockAffinityList {
return (
o &&
o.apiVersion === BlockAffinityList.apiVersion &&
o.kind === BlockAffinityList.kind
);
}
export namespace BlockAffinityList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'BlockAffinityList';
// BlockAffinityList is a list of BlockAffinity
export interface Interface {
// List of blockaffinities. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: BlockAffinity[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: BlockAffinityList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type ClusterInformation = object;
// ClusterInformationList is a list of ClusterInformation
export class ClusterInformationList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of clusterinformations. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: ClusterInformation[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: ClusterInformationList.Metadata;
constructor(desc: ClusterInformationList) {
this.apiVersion = ClusterInformationList.apiVersion;
this.items = desc.items;
this.kind = ClusterInformationList.kind;
this.metadata = desc.metadata;
}
}
export function isClusterInformationList(o: any): o is ClusterInformationList {
return (
o &&
o.apiVersion === ClusterInformationList.apiVersion &&
o.kind === ClusterInformationList.kind
);
}
export namespace ClusterInformationList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'ClusterInformationList';
// ClusterInformationList is a list of ClusterInformation
export interface Interface {
// List of clusterinformations. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: ClusterInformation[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: ClusterInformationList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type FelixConfiguration = object;
// FelixConfigurationList is a list of FelixConfiguration
export class FelixConfigurationList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of felixconfigurations. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: FelixConfiguration[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: FelixConfigurationList.Metadata;
constructor(desc: FelixConfigurationList) {
this.apiVersion = FelixConfigurationList.apiVersion;
this.items = desc.items;
this.kind = FelixConfigurationList.kind;
this.metadata = desc.metadata;
}
}
export function isFelixConfigurationList(o: any): o is FelixConfigurationList {
return (
o &&
o.apiVersion === FelixConfigurationList.apiVersion &&
o.kind === FelixConfigurationList.kind
);
}
export namespace FelixConfigurationList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'FelixConfigurationList';
// FelixConfigurationList is a list of FelixConfiguration
export interface Interface {
// List of felixconfigurations. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: FelixConfiguration[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: FelixConfigurationList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type GlobalBGPConfig = object;
// GlobalBGPConfigList is a list of GlobalBGPConfig
export class GlobalBGPConfigList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of globalbgpconfigs. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: GlobalBGPConfig[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: GlobalBGPConfigList.Metadata;
constructor(desc: GlobalBGPConfigList) {
this.apiVersion = GlobalBGPConfigList.apiVersion;
this.items = desc.items;
this.kind = GlobalBGPConfigList.kind;
this.metadata = desc.metadata;
}
}
export function isGlobalBGPConfigList(o: any): o is GlobalBGPConfigList {
return (
o &&
o.apiVersion === GlobalBGPConfigList.apiVersion &&
o.kind === GlobalBGPConfigList.kind
);
}
export namespace GlobalBGPConfigList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'GlobalBGPConfigList';
// GlobalBGPConfigList is a list of GlobalBGPConfig
export interface Interface {
// List of globalbgpconfigs. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: GlobalBGPConfig[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: GlobalBGPConfigList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type GlobalFelixConfig = object;
// GlobalFelixConfigList is a list of GlobalFelixConfig
export class GlobalFelixConfigList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of globalfelixconfigs. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: GlobalFelixConfig[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: GlobalFelixConfigList.Metadata;
constructor(desc: GlobalFelixConfigList) {
this.apiVersion = GlobalFelixConfigList.apiVersion;
this.items = desc.items;
this.kind = GlobalFelixConfigList.kind;
this.metadata = desc.metadata;
}
}
export function isGlobalFelixConfigList(o: any): o is GlobalFelixConfigList {
return (
o &&
o.apiVersion === GlobalFelixConfigList.apiVersion &&
o.kind === GlobalFelixConfigList.kind
);
}
export namespace GlobalFelixConfigList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'GlobalFelixConfigList';
// GlobalFelixConfigList is a list of GlobalFelixConfig
export interface Interface {
// List of globalfelixconfigs. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: GlobalFelixConfig[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: GlobalFelixConfigList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type GlobalNetworkPolicy = object;
// GlobalNetworkPolicyList is a list of GlobalNetworkPolicy
export class GlobalNetworkPolicyList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of globalnetworkpolicies. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: GlobalNetworkPolicy[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: GlobalNetworkPolicyList.Metadata;
constructor(desc: GlobalNetworkPolicyList) {
this.apiVersion = GlobalNetworkPolicyList.apiVersion;
this.items = desc.items;
this.kind = GlobalNetworkPolicyList.kind;
this.metadata = desc.metadata;
}
}
export function isGlobalNetworkPolicyList(
o: any
): o is GlobalNetworkPolicyList {
return (
o &&
o.apiVersion === GlobalNetworkPolicyList.apiVersion &&
o.kind === GlobalNetworkPolicyList.kind
);
}
export namespace GlobalNetworkPolicyList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'GlobalNetworkPolicyList';
// GlobalNetworkPolicyList is a list of GlobalNetworkPolicy
export interface Interface {
// List of globalnetworkpolicies. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: GlobalNetworkPolicy[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: GlobalNetworkPolicyList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type GlobalNetworkSet = object;
// GlobalNetworkSetList is a list of GlobalNetworkSet
export class GlobalNetworkSetList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of globalnetworksets. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: GlobalNetworkSet[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: GlobalNetworkSetList.Metadata;
constructor(desc: GlobalNetworkSetList) {
this.apiVersion = GlobalNetworkSetList.apiVersion;
this.items = desc.items;
this.kind = GlobalNetworkSetList.kind;
this.metadata = desc.metadata;
}
}
export function isGlobalNetworkSetList(o: any): o is GlobalNetworkSetList {
return (
o &&
o.apiVersion === GlobalNetworkSetList.apiVersion &&
o.kind === GlobalNetworkSetList.kind
);
}
export namespace GlobalNetworkSetList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'GlobalNetworkSetList';
// GlobalNetworkSetList is a list of GlobalNetworkSet
export interface Interface {
// List of globalnetworksets. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: GlobalNetworkSet[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: GlobalNetworkSetList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type HostEndpoint = object;
// HostEndpointList is a list of HostEndpoint
export class HostEndpointList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of hostendpoints. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: HostEndpoint[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: HostEndpointList.Metadata;
constructor(desc: HostEndpointList) {
this.apiVersion = HostEndpointList.apiVersion;
this.items = desc.items;
this.kind = HostEndpointList.kind;
this.metadata = desc.metadata;
}
}
export function isHostEndpointList(o: any): o is HostEndpointList {
return (
o &&
o.apiVersion === HostEndpointList.apiVersion &&
o.kind === HostEndpointList.kind
);
}
export namespace HostEndpointList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'HostEndpointList';
// HostEndpointList is a list of HostEndpoint
export interface Interface {
// List of hostendpoints. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: HostEndpoint[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: HostEndpointList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type IPAMBlock = object;
// IPAMBlockList is a list of IPAMBlock
export class IPAMBlockList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of ipamblocks. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: IPAMBlock[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: IPAMBlockList.Metadata;
constructor(desc: IPAMBlockList) {
this.apiVersion = IPAMBlockList.apiVersion;
this.items = desc.items;
this.kind = IPAMBlockList.kind;
this.metadata = desc.metadata;
}
}
export function isIPAMBlockList(o: any): o is IPAMBlockList {
return (
o &&
o.apiVersion === IPAMBlockList.apiVersion &&
o.kind === IPAMBlockList.kind
);
}
export namespace IPAMBlockList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'IPAMBlockList';
// IPAMBlockList is a list of IPAMBlock
export interface Interface {
// List of ipamblocks. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: IPAMBlock[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: IPAMBlockList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type IPAMConfig = object;
// IPAMConfigList is a list of IPAMConfig
export class IPAMConfigList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of ipamconfigs. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: IPAMConfig[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: IPAMConfigList.Metadata;
constructor(desc: IPAMConfigList) {
this.apiVersion = IPAMConfigList.apiVersion;
this.items = desc.items;
this.kind = IPAMConfigList.kind;
this.metadata = desc.metadata;
}
}
export function isIPAMConfigList(o: any): o is IPAMConfigList {
return (
o &&
o.apiVersion === IPAMConfigList.apiVersion &&
o.kind === IPAMConfigList.kind
);
}
export namespace IPAMConfigList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'IPAMConfigList';
// IPAMConfigList is a list of IPAMConfig
export interface Interface {
// List of ipamconfigs. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: IPAMConfig[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: IPAMConfigList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type IPAMHandle = object;
// IPAMHandleList is a list of IPAMHandle
export class IPAMHandleList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of ipamhandles. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: IPAMHandle[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: IPAMHandleList.Metadata;
constructor(desc: IPAMHandleList) {
this.apiVersion = IPAMHandleList.apiVersion;
this.items = desc.items;
this.kind = IPAMHandleList.kind;
this.metadata = desc.metadata;
}
}
export function isIPAMHandleList(o: any): o is IPAMHandleList {
return (
o &&
o.apiVersion === IPAMHandleList.apiVersion &&
o.kind === IPAMHandleList.kind
);
}
export namespace IPAMHandleList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'IPAMHandleList';
// IPAMHandleList is a list of IPAMHandle
export interface Interface {
// List of ipamhandles. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: IPAMHandle[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: IPAMHandleList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type IPPool = object;
// IPPoolList is a list of IPPool
export class IPPoolList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of ippools. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: IPPool[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: IPPoolList.Metadata;
constructor(desc: IPPoolList) {
this.apiVersion = IPPoolList.apiVersion;
this.items = desc.items;
this.kind = IPPoolList.kind;
this.metadata = desc.metadata;
}
}
export function isIPPoolList(o: any): o is IPPoolList {
return (
o && o.apiVersion === IPPoolList.apiVersion && o.kind === IPPoolList.kind
);
}
export namespace IPPoolList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'IPPoolList';
// IPPoolList is a list of IPPool
export interface Interface {
// List of ippools. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: IPPool[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: IPPoolList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type NetworkPolicy = object;
// NetworkPolicyList is a list of NetworkPolicy
export class NetworkPolicyList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of networkpolicies. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: NetworkPolicy[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: NetworkPolicyList.Metadata;
constructor(desc: NetworkPolicyList) {
this.apiVersion = NetworkPolicyList.apiVersion;
this.items = desc.items;
this.kind = NetworkPolicyList.kind;
this.metadata = desc.metadata;
}
}
export function isNetworkPolicyList(o: any): o is NetworkPolicyList {
return (
o &&
o.apiVersion === NetworkPolicyList.apiVersion &&
o.kind === NetworkPolicyList.kind
);
}
export namespace NetworkPolicyList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'NetworkPolicyList';
// NetworkPolicyList is a list of NetworkPolicy
export interface Interface {
// List of networkpolicies. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: NetworkPolicy[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: NetworkPolicyList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
}
export type NetworkSet = object;
// NetworkSetList is a list of NetworkSet
export class NetworkSetList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
public apiVersion: string;
// List of networksets. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
public items: NetworkSet[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public kind: string;
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
public metadata?: NetworkSetList.Metadata;
constructor(desc: NetworkSetList) {
this.apiVersion = NetworkSetList.apiVersion;
this.items = desc.items;
this.kind = NetworkSetList.kind;
this.metadata = desc.metadata;
}
}
export function isNetworkSetList(o: any): o is NetworkSetList {
return (
o &&
o.apiVersion === NetworkSetList.apiVersion &&
o.kind === NetworkSetList.kind
);
}
export namespace NetworkSetList {
export const apiVersion = 'crd.projectcalico.org/v1';
export const group = 'crd.projectcalico.org';
export const version = 'v1';
export const kind = 'NetworkSetList';
// NetworkSetList is a list of NetworkSet
export interface Interface {
// List of networksets. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md
items: NetworkSet[];
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
metadata?: NetworkSetList.Metadata;
}
// ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
export class Metadata {
// continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.
public continue?: string;
// remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.
public remainingItemCount?: number;
// String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
public resourceVersion?: string;
// selfLink is a URL representing this object. Populated by the system. Read-only.
//
// DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release.
public selfLink?: string;
}
} | the_stack |
import assert from 'assert';
import { r } from '../src';
import config from './config';
import { uuid } from './util/common';
describe('transformations', () => {
let dbName: string;
let tableName: string;
before(async () => {
await r.connectPool(config);
dbName = uuid();
tableName = uuid();
const numDocs = 100;
const result1 = await r.dbCreate(dbName).run();
assert.equal(result1.dbs_created, 1);
const result2 = await r
.db(dbName)
.tableCreate(tableName)
.run();
assert.equal(result2.tables_created, 1);
const result3 = await r
.db(dbName)
.table(tableName)
.insert(Array(numDocs).fill({}))
.run();
assert.equal(result3.inserted, numDocs);
await r
.db(dbName)
.table(tableName)
.update({ val: r.js('Math.random()') }, { nonAtomic: true })
.run();
await r
.db(dbName)
.table(tableName)
.indexCreate('val')
.run();
await r
.db(dbName)
.table(tableName)
.indexWait('val')
.run();
});
after(async () => {
await r.getPoolMaster().drain();
});
it('`map` should work on array -- row => row', async () => {
let result = await r
.expr([1, 2, 3])
.map(row => row)
.run();
assert.deepEqual(result, [1, 2, 3]);
result = await r
.expr([1, 2, 3])
.map(row => row.add(1))
.run();
assert.deepEqual(result, [2, 3, 4]);
});
it('`map` should work on array -- function', async () => {
let result = await r
.expr([1, 2, 3])
.map(doc => doc)
.run();
assert.deepEqual(result, [1, 2, 3]);
result = await r
.expr([1, 2, 3])
.map(doc => doc.add(2))
.run();
assert.deepEqual(result, [3, 4, 5]);
});
it('`map` should throw if no argument has been passed', async () => {
try {
await r
.db(dbName)
.table(tableName)
.map()
.run();
assert.fail('should throw');
} catch (e) {
assert(
e.message.match(/^`map` takes at least 1 argument, 0 provided after/)
);
}
});
it('`withFields` should work on array -- single field', async () => {
const result = await r
.expr([{ a: 0, b: 1, c: 2 }, { a: 4, b: 4, c: 5 }, { a: 9, b: 2, c: 0 }])
.withFields('a')
.run();
assert.deepEqual(result, [{ a: 0 }, { a: 4 }, { a: 9 }]);
});
it('`withFields` should work on array -- multiple field', async () => {
const result = await r
.expr([{ a: 0, b: 1, c: 2 }, { a: 4, b: 4, c: 5 }, { a: 9, b: 2, c: 0 }])
.withFields('a', 'c')
.run();
assert.deepEqual(result, [{ a: 0, c: 2 }, { a: 4, c: 5 }, { a: 9, c: 0 }]);
});
it('`withFields` should throw if no argument has been passed', async () => {
try {
await r
.db(dbName)
.table(tableName)
.withFields()
.run();
assert.fail('should throw');
} catch (e) {
assert(
e.message.match(
/^`withFields` takes at least 1 argument, 0 provided after/
)
);
}
});
it('`concatMap` should work on array -- function', async () => {
const result = await r
.expr([[1, 2], [3], [4]])
.concatMap(doc => doc)
.run();
assert.deepEqual(result, [1, 2, 3, 4]);
});
it('`concatMap` should work on array -- row => row', async () => {
const result = await r
.expr([[1, 2], [3], [4]])
.concatMap(row => row)
.run();
assert.deepEqual(result, [1, 2, 3, 4]);
});
it('`concatMap` should throw if no argument has been passed', async () => {
try {
await r
.db(dbName)
.table(tableName)
.concatMap()
.run();
assert.fail('should throw');
} catch (e) {
assert(
e.message.match(/^`concatMap` takes 1 argument, 0 provided after/)
);
}
});
it('`orderBy` should work on array -- string', async () => {
const result = await r
.expr([{ a: 23 }, { a: 10 }, { a: 0 }, { a: 100 }])
.orderBy('a')
.run();
assert.deepEqual(result, [{ a: 0 }, { a: 10 }, { a: 23 }, { a: 100 }]);
});
it('`orderBy` should work on array -- row => row', async () => {
const result = await r
.expr([{ a: 23 }, { a: 10 }, { a: 0 }, { a: 100 }])
.orderBy(row => row('a'))
.run();
assert.deepEqual(result, [{ a: 0 }, { a: 10 }, { a: 23 }, { a: 100 }]);
});
it('`orderBy` should work on a table -- pk', async () => {
const result = await r
.db(dbName)
.table(tableName)
.orderBy({ index: 'id' })
.run();
for (let i = 0; i < result.length - 1; i++) {
assert(result[i].id < result[i + 1].id);
}
});
it('`orderBy` should work on a table -- secondary', async () => {
const result = await r
.db(dbName)
.table(tableName)
.orderBy({ index: 'val' })
.run();
for (let i = 0; i < result.length - 1; i++) {
assert(result[i].val < result[i + 1].val);
}
});
it('`orderBy` should work on a two fields', async () => {
const dbName1 = uuid();
const tableName1 = uuid();
const numDocs = 98;
const result1 = await r.dbCreate(dbName1).run();
assert.deepEqual(result1.dbs_created, 1);
const result2 = await r
.db(dbName1)
.tableCreate(tableName1)
.run();
assert.equal(result2.tables_created, 1);
const result3 = await r
.db(dbName1)
.table(tableName1)
.insert(
Array(numDocs)
.fill(0)
.map(() => ({ a: r.js('Math.random()') }))
)
.run();
assert.deepEqual(result3.inserted, numDocs);
const result4 = await r
.db(dbName1)
.table(tableName1)
.orderBy('id', 'a')
.run();
assert(Array.isArray(result4));
assert(result4[0].id < result4[1].id);
});
it('`orderBy` should throw if no argument has been passed', async () => {
try {
await r
.db(dbName)
.table(tableName)
.orderBy()
.run();
assert.fail('should throw');
} catch (e) {
assert(
e.message.match(
/^`orderBy` takes at least 1 argument, 0 provided after/
)
);
}
});
it('`orderBy` should not wrap on r.asc', async () => {
const result = await r
.expr([{ a: 23 }, { a: 10 }, { a: 0 }, { a: 100 }])
.orderBy(r.asc(row => row('a')))
.run();
assert.deepEqual(result, [{ a: 0 }, { a: 10 }, { a: 23 }, { a: 100 }]);
});
it('`orderBy` should not wrap on r.desc', async () => {
const result = await r
.expr([{ a: 23 }, { a: 10 }, { a: 0 }, { a: 100 }])
.orderBy(r.desc(row => row('a')))
.run();
assert.deepEqual(result, [{ a: 100 }, { a: 23 }, { a: 10 }, { a: 0 }]);
});
it('r.desc should work', async () => {
const result = await r
.expr([{ a: 23 }, { a: 10 }, { a: 0 }, { a: 100 }])
.orderBy(r.desc('a'))
.run();
assert.deepEqual(result, [{ a: 100 }, { a: 23 }, { a: 10 }, { a: 0 }]);
});
it('r.asc should work', async () => {
const result = await r
.expr([{ a: 23 }, { a: 10 }, { a: 0 }, { a: 100 }])
.orderBy(r.asc('a'))
.run();
assert.deepEqual(result, [{ a: 0 }, { a: 10 }, { a: 23 }, { a: 100 }]);
});
it('`desc` is not defined after a term', async () => {
try {
await r
.expr(1)
// @ts-ignore
.desc('foo')
.run();
assert.fail('sholud throw');
} catch (e) {
assert(e.message.endsWith('.desc is not a function'));
}
});
it('`asc` is not defined after a term', async () => {
try {
await r
.expr(1)
// @ts-ignore
.asc('foo')
.run();
assert.fail('should throw');
} catch (e) {
assert(e.message.endsWith('.asc is not a function'));
}
});
it('`skip` should work', async () => {
const result = await r
.expr([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
.skip(3)
.run();
assert.deepEqual(result, [3, 4, 5, 6, 7, 8, 9]);
});
it('`skip` should throw if no argument has been passed', async () => {
try {
// @ts-ignore
await r
.db(dbName)
.table(tableName)
.skip()
.run();
assert.fail('should throw');
} catch (e) {
assert(e.message.match(/^`skip` takes 1 argument, 0 provided after/));
}
});
it('`limit` should work', async () => {
const result = await r
.expr([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
.limit(3)
.run();
assert.deepEqual(result, [0, 1, 2]);
});
it('`limit` should throw if no argument has been passed', async () => {
try {
// @ts-ignore
await r
.db(dbName)
.table(tableName)
.limit()
.run();
assert.fail('should throw');
} catch (e) {
assert(e.message.match(/^`limit` takes 1 argument, 0 provided after/));
}
});
it('`slice` should work', async () => {
const result = await r
.expr([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
.slice(3, 5)
.run();
assert.deepEqual(result, [3, 4]);
});
it('`slice` should handle options and optional end', async () => {
let result = await r
.expr([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
.slice(3)
.run();
assert.deepEqual(result, [3, 4, 5, 6, 7, 8, 9]);
result = await r
.expr([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
.slice(3, { leftBound: 'open' })
.run();
assert.deepEqual(result, [4, 5, 6, 7, 8, 9]);
result = await r
.expr([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
.slice(3, 5, { leftBound: 'open' })
.run();
assert.deepEqual(result, [4]);
});
it('`slice` should work -- with options', async () => {
let result = await r
.expr([
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23
])
.slice(5, 10, { rightBound: 'closed' })
.run();
assert.deepEqual(result, [5, 6, 7, 8, 9, 10]);
result = await r
.expr([
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23
])
.slice(5, 10, { rightBound: 'open' })
.run();
assert.deepEqual(result, [5, 6, 7, 8, 9]);
result = await r
.expr([
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23
])
.slice(5, 10, { leftBound: 'open' })
.run();
assert.deepEqual(result, [6, 7, 8, 9]);
result = await r
.expr([
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23
])
.slice(5, 10, { leftBound: 'closed' })
.run();
assert.deepEqual(result, [5, 6, 7, 8, 9]);
result = await r
.expr([
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23
])
.slice(5, 10, { leftBound: 'closed', rightBound: 'closed' })
.run();
assert.deepEqual(result, [5, 6, 7, 8, 9, 10]);
});
it('`slice` should throw if no argument has been passed', async () => {
try {
// @ts-ignore
await r
.db(dbName)
.table(tableName)
.slice()
.run();
assert.fail('should throw');
} catch (e) {
assert(
e.message.match(/^`slice` takes at least 1 argument, 0 provided after/)
);
}
});
it('`nth` should work', async () => {
const result = await r
.expr([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
.nth(3)
.run();
assert.equal(result, 3);
});
it('`nth` should throw if no argument has been passed', async () => {
try {
// @ts-ignore
await r
.db(dbName)
.table(tableName)
.nth()
.run();
assert.fail('should throw');
} catch (e) {
assert(e.message.match(/^`nth` takes 1 argument, 0 provided after/));
}
});
it('`offsetsOf` should work - datum', async () => {
const result = await r
.expr([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
.nth(3)
.run();
assert.equal(result, 3);
});
it('`offsetsOf` should work - row => row', async () => {
const result = await r
.expr([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
.offsetsOf(row => row.eq(3))
.run();
assert.equal(result, 3);
});
it('`offsetsOf` should work - function', async () => {
const result = await r
.expr([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
.offsetsOf(doc => doc.eq(3))
.run();
assert.equal(result, 3);
});
it('`offsetsOf` should throw if no argument has been passed', async () => {
try {
// @ts-ignore
await r
.db(dbName)
.table(tableName)
.offsetsOf()
.run();
assert.fail('should throw');
} catch (e) {
assert(
e.message.match(/^`offsetsOf` takes 1 argument, 0 provided after/)
);
}
});
it('`isEmpty` should work', async () => {
let result = await r
.expr([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
.isEmpty()
.run();
assert.equal(result, false);
result = await r
.expr([])
.isEmpty()
.run();
assert.equal(result, true);
});
it('`union` should work - 1', async () => {
const result = await r
.expr([0, 1, 2])
.union([3, 4, 5])
.run();
assert.deepEqual(result.length, 6);
for (let i = 0; i < 6; i++) {
assert(result.indexOf(i) >= 0);
}
});
it('`union` should work - 2', async () => {
const result = await r.union([0, 1, 2], [3, 4, 5], [6, 7]).run();
assert.deepEqual(result.length, 8);
for (let i = 0; i < 8; i++) {
assert(result.indexOf(i) >= 0);
}
});
// it('`union` should work - 3', async () => {
// const result = await r.union().run();
// assert.deepEqual(result, []);
// });
it('`union` should work with interleave - 1', async () => {
const result = await r
.expr([0, 1, 2])
.union([3, 4, 5], { interleave: false })
.run();
assert.deepEqual(result, [0, 1, 2, 3, 4, 5]);
});
it('`union` should work with interleave - 1', async () => {
const result = await r
.expr([{ name: 'Michel' }, { name: 'Sophie' }, { name: 'Laurent' }])
.orderBy('name')
.union(r.expr([{ name: 'Moo' }, { name: 'Bar' }]).orderBy('name'), {
interleave: 'name'
})
.run();
assert.deepEqual(result, [
{ name: 'Bar' },
{ name: 'Laurent' },
{ name: 'Michel' },
{ name: 'Moo' },
{ name: 'Sophie' }
]);
});
it('`sample` should work', async () => {
const result = await r
.expr([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
.sample(2)
.run();
assert.equal(result.length, 2);
});
it('`sample` should throw if given -1', async () => {
try {
await r
.expr([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
.sample(-1)
.run();
assert.fail('should throw');
} catch (e) {
assert(
e.message.match(
'Number of items to sample must be non-negative, got `-1`'
)
);
}
});
it('`sample` should throw if no argument has been passed', async () => {
try {
// @ts-ignore
await r
.db(dbName)
.table(tableName)
.sample()
.run();
assert.fail('should throw');
} catch (e) {
assert(e.message.match(/^`sample` takes 1 argument, 0 provided after/));
}
});
}); | the_stack |
import ms from 'ms';
import bytes from 'bytes';
import { delimiter, dirname, join } from 'path';
import { fork, ChildProcess } from 'child_process';
import { createFunction } from '@zeit/fun';
import {
Builder,
BuildOptions,
Env,
File,
Lambda,
FileBlob,
FileFsRef,
isOfficialRuntime,
} from '@vercel/build-utils';
import plural from 'pluralize';
import minimatch from 'minimatch';
import { Output } from '../output';
import highlight from '../output/highlight';
import { treeKill } from '../tree-kill';
import { relative } from '../path-helpers';
import { LambdaSizeExceededError } from '../errors-ts';
import DevServer from './server';
import { getBuilder } from './builder-cache';
import {
VercelConfig,
BuildMatch,
BuildResult,
BuilderInputs,
BuilderOutput,
BuildResultV3,
BuilderOutputs,
EnvConfigs,
BuiltLambda,
} from './types';
import { normalizeRoutes } from '@vercel/routing-utils';
import getUpdateCommand from '../get-update-command';
import { getTitleName } from '../pkg-name';
interface BuildMessage {
type: string;
}
interface BuildMessageResult extends BuildMessage {
type: 'buildResult';
result?: BuilderOutputs | BuildResult;
error?: object;
}
async function createBuildProcess(
match: BuildMatch,
envConfigs: EnvConfigs,
workPath: string,
output: Output
): Promise<ChildProcess> {
output.debug(`Creating build process for "${match.entrypoint}"`);
const builderWorkerPath = join(__dirname, 'builder-worker.js');
// Ensure that `node` is in the builder's `PATH`
let PATH = `${dirname(process.execPath)}${delimiter}${process.env.PATH}`;
const env: Env = {
...process.env,
PATH,
...envConfigs.allEnv,
};
const buildProcess = fork(builderWorkerPath, [], {
cwd: workPath,
execArgv: [],
env,
});
match.buildProcess = buildProcess;
buildProcess.on('exit', (code, signal) => {
output.debug(
`Build process for "${match.entrypoint}" exited with ${signal || code}`
);
match.buildProcess = undefined;
});
return new Promise((resolve, reject) => {
// The first message that the builder process sends is the `ready` event
buildProcess.once('message', ({ type }) => {
if (type !== 'ready') {
reject(new Error('Did not get "ready" event from builder'));
} else {
resolve(buildProcess);
}
});
});
}
export async function executeBuild(
vercelConfig: VercelConfig,
devServer: DevServer,
files: BuilderInputs,
match: BuildMatch,
requestPath: string | null,
isInitialBuild: boolean,
filesChanged?: string[],
filesRemoved?: string[]
): Promise<void> {
const {
builderWithPkg: { runInProcess, requirePath, builder, package: pkg },
} = match;
const { entrypoint } = match;
const { envConfigs, cwd: workPath, devCacheDir } = devServer;
const debug = devServer.output.isDebugEnabled();
const startTime = Date.now();
const showBuildTimestamp =
!isOfficialRuntime('static', match.use) && (!isInitialBuild || debug);
if (showBuildTimestamp) {
devServer.output.log(`Building ${match.use}:${entrypoint}`);
devServer.output.debug(
`Using \`${pkg.name}${pkg.version ? `@${pkg.version}` : ''}\``
);
}
const config = match.config || {};
let result: BuildResult;
let { buildProcess } = match;
if (!runInProcess && !buildProcess) {
buildProcess = await createBuildProcess(
match,
envConfigs,
workPath,
devServer.output
);
}
const buildOptions: BuildOptions = {
files,
entrypoint,
workPath,
repoRootPath: workPath,
config,
meta: {
isDev: true,
requestPath,
devCacheDir,
filesChanged,
filesRemoved,
// This env distiniction is only necessary to maintain
// backwards compatibility with the `@vercel/next` builder.
env: { ...envConfigs.runEnv },
buildEnv: { ...envConfigs.buildEnv },
},
};
let buildResultOrOutputs: BuilderOutputs | BuildResult | BuildResultV3;
if (buildProcess) {
buildProcess.send({
type: 'build',
requirePath,
buildOptions,
});
buildResultOrOutputs = await new Promise((resolve, reject) => {
function onMessage({ type, result, error }: BuildMessageResult) {
cleanup();
if (type === 'buildResult') {
if (result) {
resolve(result);
} else if (error) {
reject(Object.assign(new Error(), error));
}
} else {
reject(new Error(`Got unexpected message type: ${type}`));
}
}
function onExit(code: number | null, signal: string | null) {
cleanup();
const err = new Error(
`Builder exited with ${signal || code} before sending build result`
);
reject(err);
}
function cleanup() {
buildProcess!.removeListener('exit', onExit);
buildProcess!.removeListener('message', onMessage);
}
buildProcess!.on('exit', onExit);
buildProcess!.on('message', onMessage);
});
} else {
buildResultOrOutputs = await builder.build(buildOptions);
}
// Sort out build result to builder v2 shape
if (!builder.version || builder.version === 1) {
// `BuilderOutputs` map was returned (Now Builder v1 behavior)
result = {
output: buildResultOrOutputs as BuilderOutputs,
routes: [],
watch: [],
distPath:
typeof buildResultOrOutputs.distPath === 'string'
? buildResultOrOutputs.distPath
: undefined,
};
} else if (builder.version === 2) {
result = buildResultOrOutputs as BuildResult;
} else if (builder.version === 3) {
const { output, ...rest } = buildResultOrOutputs as BuildResultV3;
if (!output || (output as BuilderOutput).type !== 'Lambda') {
throw new Error('The result of "builder.build()" must be a `Lambda`');
}
if (output.maxDuration) {
throw new Error(
'The result of "builder.build()" must not contain `maxDuration`'
);
}
if (output.memory) {
throw new Error(
'The result of "builder.build()" must not contain `memory`'
);
}
for (const [src, func] of Object.entries(config.functions || {})) {
if (src === entrypoint || minimatch(entrypoint, src)) {
if (func.maxDuration) {
output.maxDuration = func.maxDuration;
}
if (func.memory) {
output.memory = func.memory;
}
break;
}
}
result = {
...rest,
output: {
[entrypoint]: output,
},
} as BuildResult;
} else {
throw new Error(
`${getTitleName()} CLI does not support builder version ${
builder.version
}.\nPlease run \`${await getUpdateCommand()}\` to update to the latest CLI.`
);
}
// Normalize Builder Routes
const normalized = normalizeRoutes(result.routes);
if (normalized.error) {
throw new Error(normalized.error.message);
} else {
result.routes = normalized.routes || [];
}
const { output } = result;
const { cleanUrls } = vercelConfig;
// Mimic fmeta-util and perform file renaming
Object.entries(output).forEach(([path, value]) => {
if (cleanUrls && path.endsWith('.html')) {
path = path.slice(0, -5);
if (value.type === 'FileBlob' || value.type === 'FileFsRef') {
value.contentType = value.contentType || 'text/html; charset=utf-8';
}
}
const extensionless = devServer.getExtensionlessFile(path);
if (extensionless) {
path = extensionless;
}
output[path] = value;
});
// Convert the JSON-ified output map back into their corresponding `File`
// subclass type instances.
for (const name of Object.keys(output)) {
const obj = output[name] as File | Lambda;
let lambda: BuiltLambda;
let fileRef: FileFsRef;
let fileBlob: FileBlob;
switch (obj.type) {
case 'FileFsRef':
fileRef = Object.assign(Object.create(FileFsRef.prototype), obj);
output[name] = fileRef;
break;
case 'FileBlob':
fileBlob = Object.assign(Object.create(FileBlob.prototype), obj);
fileBlob.data = Buffer.from((obj as any).data.data);
output[name] = fileBlob;
break;
case 'Lambda':
lambda = Object.assign(Object.create(Lambda.prototype), obj);
// Convert the JSON-ified Buffer object back into an actual Buffer
lambda.zipBuffer = Buffer.from((obj as any).zipBuffer.data);
output[name] = lambda;
break;
default:
throw new Error(`Unknown file type: ${obj.type}`);
}
}
// The `watch` array must not have "./" prefix, so if the builder returned
// watched files that contain "./" strip them here for ease of writing the
// builder.
result.watch = (result.watch || []).map((w: string) => {
if (w.startsWith('./')) {
return w.substring(2);
}
return w;
});
// The `entrypoint` should always be watched, since we know that it was used
// to produce the build output. This is for builders that don't implement
// a fully featured `watch` return value.
if (!result.watch.includes(entrypoint)) {
result.watch.push(entrypoint);
}
// Enforce the lambda zip size soft watermark
const maxLambdaBytes = bytes('50mb');
for (const asset of Object.values(result.output)) {
if (asset.type === 'Lambda') {
const size = asset.zipBuffer.length;
if (size > maxLambdaBytes) {
throw new LambdaSizeExceededError(size, maxLambdaBytes);
}
}
}
// Create function for all 'Lambda' type output
await Promise.all(
Object.entries(result.output).map(async entry => {
const path: string = entry[0];
const asset: BuilderOutput = entry[1];
if (asset.type === 'Lambda') {
// Tear down the previous `fun` Lambda instance for this asset
const oldAsset = match.buildOutput && match.buildOutput[path];
if (oldAsset && oldAsset.type === 'Lambda' && oldAsset.fn) {
await oldAsset.fn.destroy();
}
asset.fn = await createFunction({
Code: { ZipFile: asset.zipBuffer },
Handler: asset.handler,
Runtime: asset.runtime,
MemorySize: asset.memory || 3008,
Environment: {
Variables: {
...vercelConfig.env,
...asset.environment,
...envConfigs.runEnv,
},
},
});
}
match.buildTimestamp = Date.now();
})
);
match.buildResults.set(requestPath, result);
Object.assign(match.buildOutput, result.output);
if (showBuildTimestamp) {
const endTime = Date.now();
devServer.output.log(
`Built ${match.use}:${entrypoint} [${ms(endTime - startTime)}]`
);
}
}
export async function getBuildMatches(
vercelConfig: VercelConfig,
cwd: string,
output: Output,
devServer: DevServer,
fileList: string[]
): Promise<BuildMatch[]> {
const matches: BuildMatch[] = [];
if (fileList.length === 0) {
// If there's no files in the cwd then we know there won't be any build
// matches, so bail eagerly, and avoid printing the "no matches" message.
return matches;
}
const noMatches: Builder[] = [];
const builds = vercelConfig.builds || [{ src: '**', use: '@vercel/static' }];
for (const buildConfig of builds) {
let { src = '**', use, config = {} } = buildConfig;
if (!use) {
continue;
}
if (src[0] === '/') {
// Remove a leading slash so that the globbing is relative to `cwd`
// instead of the root of the filesystem. This matches the behavior
// of Vercel deployments.
src = src.substring(1);
}
// lambda function files are trimmed of their file extension
const mapToEntrypoint = new Map<string, string>();
const extensionless = devServer.getExtensionlessFile(src);
if (extensionless) {
mapToEntrypoint.set(extensionless, src);
src = extensionless;
}
// We need to escape brackets since `glob` will
// try to find a group otherwise
src = src.replace(/(\[|\])/g, '[$1]');
const files = fileList
.filter(name => name === src || minimatch(name, src, { dot: true }))
.map(name => join(cwd, name));
if (files.length === 0) {
noMatches.push(buildConfig);
}
for (const file of files) {
src = relative(cwd, file);
// Remove the output directory prefix
if (config.zeroConfig && config.outputDirectory) {
const outputMatch = config.outputDirectory + '/';
if (src.startsWith(outputMatch)) {
src = src.slice(outputMatch.length);
}
}
const builderWithPkg = await getBuilder(use, output);
matches.push({
...buildConfig,
src,
entrypoint: mapToEntrypoint.get(src) || src,
builderWithPkg,
buildOutput: {},
buildResults: new Map(),
buildTimestamp: 0,
});
}
}
if (noMatches.length > 0) {
output.warn(
`You defined ${plural(
'build',
noMatches.length,
true
)} that did not match any source files (please ensure they are NOT defined in ${highlight(
'.vercelignore'
)}):`
);
for (const buildConfig of noMatches) {
output.print(`- ${JSON.stringify(buildConfig)}\n`);
}
}
return matches;
}
export async function shutdownBuilder(
match: BuildMatch,
{ debug }: Output
): Promise<void> {
const ops: Promise<void>[] = [];
if (match.buildProcess) {
const { pid } = match.buildProcess;
debug(`Killing builder sub-process with PID ${pid}`);
const killPromise = treeKill(pid)
.then(() => {
debug(`Killed builder with PID ${pid}`);
})
.catch((err: Error) => {
debug(`Failed to kill builder with PID ${pid}: ${err}`);
});
ops.push(killPromise);
delete match.buildProcess;
}
if (match.buildOutput) {
for (const asset of Object.values(match.buildOutput)) {
if (asset.type === 'Lambda' && asset.fn) {
debug(`Shutting down Lambda function`);
ops.push(asset.fn.destroy());
}
}
}
await Promise.all(ops);
} | the_stack |
import {BoolPropertyDefinition} from "../../../PropertyDefinitions/BoolPropertyDefinition";
import {ByteArrayPropertyDefinition} from "../../../PropertyDefinitions/ByteArrayPropertyDefinition";
import {ComplexPropertyDefinition} from "../../../PropertyDefinitions/ComplexPropertyDefinition";
import {ConversationFlagStatus} from "../../../Enumerations/ConversationFlagStatus";
import {ConversationId} from "../../../ComplexProperties/ConversationId";
import {DateTimePropertyDefinition} from "../../../PropertyDefinitions/DateTimePropertyDefinition";
import {ExchangeVersion} from "../../../Enumerations/ExchangeVersion";
import {GenericPropertyDefinition} from "../../../PropertyDefinitions/GenericPropertyDefinition";
import {IconIndex} from "../../../Enumerations/IconIndex";
import {Importance} from "../../../Enumerations/Importance";
import {IntPropertyDefinition} from "../../../PropertyDefinitions/IntPropertyDefinition";
import {ItemIdCollection} from "../../../ComplexProperties/ItemIdCollection";
import {PropertyDefinitionFlags} from "../../../Enumerations/PropertyDefinitionFlags";
import {PropertyDefinition} from "../../../PropertyDefinitions/PropertyDefinition";
import {Schemas} from "./Schemas";
import {StringList} from "../../../ComplexProperties/StringList";
import {StringPropertyDefinition} from "../../../PropertyDefinitions/StringPropertyDefinition";
import {XmlElementNames} from "../../XmlElementNames";
import {ServiceObjectSchema} from "./ServiceObjectSchema";
/**
* Field URIs for Conversation.
*/
module FieldUris {
export var ConversationId: string = "conversation:ConversationId";
export var ConversationTopic: string = "conversation:ConversationTopic";
export var UniqueRecipients: string = "conversation:UniqueRecipients";
export var GlobalUniqueRecipients: string = "conversation:GlobalUniqueRecipients";
export var UniqueUnreadSenders: string = "conversation:UniqueUnreadSenders";
export var GlobalUniqueUnreadSenders: string = "conversation:GlobalUniqueUnreadSenders";
export var UniqueSenders: string = "conversation:UniqueSenders";
export var GlobalUniqueSenders: string = "conversation:GlobalUniqueSenders";
export var LastDeliveryTime: string = "conversation:LastDeliveryTime";
export var GlobalLastDeliveryTime: string = "conversation:GlobalLastDeliveryTime";
export var Categories: string = "conversation:Categories";
export var GlobalCategories: string = "conversation:GlobalCategories";
export var FlagStatus: string = "conversation:FlagStatus";
export var GlobalFlagStatus: string = "conversation:GlobalFlagStatus";
export var HasAttachments: string = "conversation:HasAttachments";
export var GlobalHasAttachments: string = "conversation:GlobalHasAttachments";
export var MessageCount: string = "conversation:MessageCount";
export var GlobalMessageCount: string = "conversation:GlobalMessageCount";
export var UnreadCount: string = "conversation:UnreadCount";
export var GlobalUnreadCount: string = "conversation:GlobalUnreadCount";
export var Size: string = "conversation:Size";
export var GlobalSize: string = "conversation:GlobalSize";
export var ItemClasses: string = "conversation:ItemClasses";
export var GlobalItemClasses: string = "conversation:GlobalItemClasses";
export var Importance: string = "conversation:Importance";
export var GlobalImportance: string = "conversation:GlobalImportance";
export var ItemIds: string = "conversation:ItemIds";
export var GlobalItemIds: string = "conversation:GlobalItemIds";
export var LastModifiedTime: string = "conversation:LastModifiedTime";
export var InstanceKey: string = "conversation:InstanceKey";
export var Preview: string = "conversation:Preview";
export var IconIndex: string = "conversation:IconIndex";
export var GlobalIconIndex: string = "conversation:GlobalIconIndex";
export var DraftItemIds: string = "conversation:DraftItemIds";
export var HasIrm: string = "conversation:HasIrm";
export var GlobalHasIrm: string = "conversation:GlobalHasIrm";
}
/**
* Represents the schema for Conversation.
*/
export class ConversationSchema extends ServiceObjectSchema {
/**
* Defines the **Id** property.
*/
public static Id: PropertyDefinition = new ComplexPropertyDefinition<ConversationId>(
"ConversationId",
XmlElementNames.ConversationId,
FieldUris.ConversationId,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
() => { return new ConversationId(); }
);
/**
* Defines the **Topic** property.
*/
public static Topic: PropertyDefinition = new StringPropertyDefinition(
"ConversationTopic",
XmlElementNames.ConversationTopic,
FieldUris.ConversationTopic,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1
);
/**
* Defines the **UniqueRecipients** property.
*/
public static UniqueRecipients: PropertyDefinition = new ComplexPropertyDefinition<StringList>(
"UniqueRecipients",
XmlElementNames.UniqueRecipients,
FieldUris.UniqueRecipients,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
() => { return new StringList(); }
);
/**
* Defines the **GlobalUniqueRecipients** property.
*/
public static GlobalUniqueRecipients: PropertyDefinition = new ComplexPropertyDefinition<StringList>(
"GlobalUniqueRecipients",
XmlElementNames.GlobalUniqueRecipients,
FieldUris.GlobalUniqueRecipients,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
() => { return new StringList(); }
);
/**
* Defines the **UniqueUnreadSenders** property.
*/
public static UniqueUnreadSenders: PropertyDefinition = new ComplexPropertyDefinition<StringList>(
"UniqueUnreadSenders",
XmlElementNames.UniqueUnreadSenders,
FieldUris.UniqueUnreadSenders,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
() => { return new StringList(); }
);
/**
* Defines the **GlobalUniqueUnreadSenders** property.
*/
public static GlobalUniqueUnreadSenders: PropertyDefinition = new ComplexPropertyDefinition<StringList>(
"GlobalUniqueUnreadSenders",
XmlElementNames.GlobalUniqueUnreadSenders,
FieldUris.GlobalUniqueUnreadSenders,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
() => { return new StringList(); }
);
/**
* Defines the **UniqueSenders** property.
*/
public static UniqueSenders: PropertyDefinition = new ComplexPropertyDefinition<StringList>(
"UniqueSenders",
XmlElementNames.UniqueSenders,
FieldUris.UniqueSenders,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
() => { return new StringList(); }
);
/**
* Defines the **GlobalUniqueSenders** property.
*/
public static GlobalUniqueSenders: PropertyDefinition = new ComplexPropertyDefinition<StringList>(
"GlobalUniqueSenders",
XmlElementNames.GlobalUniqueSenders,
FieldUris.GlobalUniqueSenders,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
() => { return new StringList(); }
);
/**
* Defines the **LastDeliveryTime** property.
*/
public static LastDeliveryTime: PropertyDefinition = new DateTimePropertyDefinition(
"LastDeliveryTime",
XmlElementNames.LastDeliveryTime,
FieldUris.LastDeliveryTime,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1
);
/**
* Defines the **GlobalLastDeliveryTime** property.
*/
public static GlobalLastDeliveryTime: PropertyDefinition = new DateTimePropertyDefinition(
"GlobalLastDeliveryTime",
XmlElementNames.GlobalLastDeliveryTime,
FieldUris.GlobalLastDeliveryTime,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1
);
/**
* Defines the **Categories** property.
*/
public static Categories: PropertyDefinition = new ComplexPropertyDefinition<StringList>(
"Categories",
XmlElementNames.Categories,
FieldUris.Categories,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
() => { return new StringList(); }
);
/**
* Defines the **GlobalCategories** property.
*/
public static GlobalCategories: PropertyDefinition = new ComplexPropertyDefinition<StringList>(
"GlobalCategories",
XmlElementNames.GlobalCategories,
FieldUris.GlobalCategories,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
() => { return new StringList(); }
);
/**
* Defines the **FlagStatus** property.
*/
public static FlagStatus: PropertyDefinition = new GenericPropertyDefinition<ConversationFlagStatus>(
"FlagStatus",
XmlElementNames.FlagStatus,
FieldUris.FlagStatus,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
ConversationFlagStatus
);
/**
* Defines the **GlobalFlagStatus** property.
*/
public static GlobalFlagStatus: PropertyDefinition = new GenericPropertyDefinition<ConversationFlagStatus>(
"GlobalFlagStatus",
XmlElementNames.GlobalFlagStatus,
FieldUris.GlobalFlagStatus,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
ConversationFlagStatus
);
/**
* Defines the **HasAttachments** property.
*/
public static HasAttachments: PropertyDefinition = new BoolPropertyDefinition(
"HasAttachments",
XmlElementNames.HasAttachments,
FieldUris.HasAttachments,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1
);
/**
* Defines the **GlobalHasAttachments** property.
*/
public static GlobalHasAttachments: PropertyDefinition = new BoolPropertyDefinition(
"GlobalHasAttachments",
XmlElementNames.GlobalHasAttachments,
FieldUris.GlobalHasAttachments,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1
);
/**
* Defines the **MessageCount** property.
*/
public static MessageCount: PropertyDefinition = new IntPropertyDefinition(
"MessageCount",
XmlElementNames.MessageCount,
FieldUris.MessageCount,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1
);
/**
* Defines the **GlobalMessageCount** property.
*/
public static GlobalMessageCount: PropertyDefinition = new IntPropertyDefinition(
"GlobalMessageCount",
XmlElementNames.GlobalMessageCount,
FieldUris.GlobalMessageCount,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1
);
/**
* Defines the **UnreadCount** property.
*/
public static UnreadCount: PropertyDefinition = new IntPropertyDefinition(
"UnreadCount",
XmlElementNames.UnreadCount,
FieldUris.UnreadCount,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1
);
/**
* Defines the **GlobalUnreadCount** property.
*/
public static GlobalUnreadCount: PropertyDefinition = new IntPropertyDefinition(
"GlobalUnreadCount",
XmlElementNames.GlobalUnreadCount,
FieldUris.GlobalUnreadCount,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1
);
/**
* Defines the **Size** property.
*/
public static Size: PropertyDefinition = new IntPropertyDefinition(
"Size",
XmlElementNames.Size,
FieldUris.Size,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1
);
/**
* Defines the **GlobalSize** property.
*/
public static GlobalSize: PropertyDefinition = new IntPropertyDefinition(
"GlobalSize",
XmlElementNames.GlobalSize,
FieldUris.GlobalSize,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1
);
/**
* Defines the **ItemClasses** property.
*/
public static ItemClasses: PropertyDefinition = new ComplexPropertyDefinition<StringList>(
"ItemClasses",
XmlElementNames.ItemClasses,
FieldUris.ItemClasses,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
() => { return new StringList("ItemClass"); }
);
/**
* Defines the **GlobalItemClasses** property.
*/
public static GlobalItemClasses: PropertyDefinition = new ComplexPropertyDefinition<StringList>(
"GlobalItemClasses",
XmlElementNames.GlobalItemClasses,
FieldUris.GlobalItemClasses,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
() => { return new StringList("ItemClass"); }
);
/**
* Defines the **Importance** property.
*/
public static Importance: PropertyDefinition = new GenericPropertyDefinition<Importance>(
"Importance",
XmlElementNames.Importance,
FieldUris.Importance,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
Importance
);
/**
* Defines the **GlobalImportance** property.
*/
public static GlobalImportance: PropertyDefinition = new GenericPropertyDefinition<Importance>(
"GlobalImportance",
XmlElementNames.GlobalImportance,
FieldUris.GlobalImportance,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
Importance
);
/**
* Defines the **ItemIds** property.
*/
public static ItemIds: PropertyDefinition = new ComplexPropertyDefinition<ItemIdCollection>(
"ItemIds",
XmlElementNames.ItemIds,
FieldUris.ItemIds,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
() => { return new ItemIdCollection(); }
);
/**
* Defines the **GlobalItemIds** property.
*/
public static GlobalItemIds: PropertyDefinition = new ComplexPropertyDefinition<ItemIdCollection>(
"GlobalItemIds",
XmlElementNames.GlobalItemIds,
FieldUris.GlobalItemIds,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2010_SP1,
() => { return new ItemIdCollection(); }
);
/**
* Defines the **LastModifiedTime** property.
*/
public static LastModifiedTime: PropertyDefinition = new DateTimePropertyDefinition(
"LastModifiedTime",
XmlElementNames.LastModifiedTime,
FieldUris.LastModifiedTime,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013
);
/**
* Defines the **InstanceKey** property.
*/
public static InstanceKey: PropertyDefinition = new ByteArrayPropertyDefinition(
"InstanceKey",
XmlElementNames.InstanceKey,
FieldUris.InstanceKey,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013
);
/**
* Defines the **Preview** property.
*/
public static Preview: PropertyDefinition = new StringPropertyDefinition(
"Preview",
XmlElementNames.Preview,
FieldUris.Preview,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013
);
/**
* Defines the **IconIndex** property.
*/
public static IconIndex: PropertyDefinition = new GenericPropertyDefinition<IconIndex>(
"IconIndex",
XmlElementNames.IconIndex,
FieldUris.IconIndex,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013,
IconIndex
);
/**
* Defines the **GlobalIconIndex** property.
*/
public static GlobalIconIndex: PropertyDefinition = new GenericPropertyDefinition<IconIndex>(
"GlobalIconIndex",
XmlElementNames.GlobalIconIndex,
FieldUris.GlobalIconIndex,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013,
IconIndex
);
/**
* Defines the **DraftItemIds** property.
*/
public static DraftItemIds: PropertyDefinition = new ComplexPropertyDefinition<ItemIdCollection>(
"DraftItemIds",
XmlElementNames.DraftItemIds,
FieldUris.DraftItemIds,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013,
() => { return new ItemIdCollection(); }
);
/**
* Defines the **HasIrm** property.
*/
public static HasIrm: PropertyDefinition = new BoolPropertyDefinition(
"HasIrm",
XmlElementNames.HasIrm,
FieldUris.HasIrm,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013
);
/**
* Defines the **GlobalHasIrm** property.
*/
public static GlobalHasIrm: PropertyDefinition = new BoolPropertyDefinition(
"GlobalHasIrm",
XmlElementNames.GlobalHasIrm,
FieldUris.GlobalHasIrm,
PropertyDefinitionFlags.CanFind,
ExchangeVersion.Exchange2013
);
/**
* @internal Instance of **ConversationSchema**
*/
static Instance: ConversationSchema = new ConversationSchema();
/**
* Registers properties.
*
* /remarks/ IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the same order as they are defined in types.xsd)
*/
RegisterProperties(): void {
super.RegisterProperties();
this.RegisterProperty(ConversationSchema, ConversationSchema.Id);
this.RegisterProperty(ConversationSchema, ConversationSchema.Topic);
this.RegisterProperty(ConversationSchema, ConversationSchema.UniqueRecipients);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalUniqueRecipients);
this.RegisterProperty(ConversationSchema, ConversationSchema.UniqueUnreadSenders);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalUniqueUnreadSenders);
this.RegisterProperty(ConversationSchema, ConversationSchema.UniqueSenders);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalUniqueSenders);
this.RegisterProperty(ConversationSchema, ConversationSchema.LastDeliveryTime);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalLastDeliveryTime);
this.RegisterProperty(ConversationSchema, ConversationSchema.Categories);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalCategories);
this.RegisterProperty(ConversationSchema, ConversationSchema.FlagStatus);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalFlagStatus);
this.RegisterProperty(ConversationSchema, ConversationSchema.HasAttachments);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalHasAttachments);
this.RegisterProperty(ConversationSchema, ConversationSchema.MessageCount);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalMessageCount);
this.RegisterProperty(ConversationSchema, ConversationSchema.UnreadCount);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalUnreadCount);
this.RegisterProperty(ConversationSchema, ConversationSchema.Size);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalSize);
this.RegisterProperty(ConversationSchema, ConversationSchema.ItemClasses);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalItemClasses);
this.RegisterProperty(ConversationSchema, ConversationSchema.Importance);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalImportance);
this.RegisterProperty(ConversationSchema, ConversationSchema.ItemIds);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalItemIds);
this.RegisterProperty(ConversationSchema, ConversationSchema.LastModifiedTime);
this.RegisterProperty(ConversationSchema, ConversationSchema.InstanceKey);
this.RegisterProperty(ConversationSchema, ConversationSchema.Preview);
this.RegisterProperty(ConversationSchema, ConversationSchema.IconIndex);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalIconIndex);
this.RegisterProperty(ConversationSchema, ConversationSchema.DraftItemIds);
this.RegisterProperty(ConversationSchema, ConversationSchema.HasIrm);
this.RegisterProperty(ConversationSchema, ConversationSchema.GlobalHasIrm);
}
}
/**
* Represents the schema for Conversation.
*/
export interface ConversationSchema {
/**
* Defines the **Id** property.
*/
Id: PropertyDefinition;
/**
* Defines the **Topic** property.
*/
Topic: PropertyDefinition;
/**
* Defines the **UniqueRecipients** property.
*/
UniqueRecipients: PropertyDefinition;
/**
* Defines the **GlobalUniqueRecipients** property.
*/
GlobalUniqueRecipients: PropertyDefinition;
/**
* Defines the **UniqueUnreadSenders** property.
*/
UniqueUnreadSenders: PropertyDefinition;
/**
* Defines the **GlobalUniqueUnreadSenders** property.
*/
GlobalUniqueUnreadSenders: PropertyDefinition;
/**
* Defines the **UniqueSenders** property.
*/
UniqueSenders: PropertyDefinition;
/**
* Defines the **GlobalUniqueSenders** property.
*/
GlobalUniqueSenders: PropertyDefinition;
/**
* Defines the **LastDeliveryTime** property.
*/
LastDeliveryTime: PropertyDefinition;
/**
* Defines the **GlobalLastDeliveryTime** property.
*/
GlobalLastDeliveryTime: PropertyDefinition;
/**
* Defines the **Categories** property.
*/
Categories: PropertyDefinition;
/**
* Defines the **GlobalCategories** property.
*/
GlobalCategories: PropertyDefinition;
/**
* Defines the **FlagStatus** property.
*/
FlagStatus: PropertyDefinition;
/**
* Defines the **GlobalFlagStatus** property.
*/
GlobalFlagStatus: PropertyDefinition;
/**
* Defines the **HasAttachments** property.
*/
HasAttachments: PropertyDefinition;
/**
* Defines the **GlobalHasAttachments** property.
*/
GlobalHasAttachments: PropertyDefinition;
/**
* Defines the **MessageCount** property.
*/
MessageCount: PropertyDefinition;
/**
* Defines the **GlobalMessageCount** property.
*/
GlobalMessageCount: PropertyDefinition;
/**
* Defines the **UnreadCount** property.
*/
UnreadCount: PropertyDefinition;
/**
* Defines the **GlobalUnreadCount** property.
*/
GlobalUnreadCount: PropertyDefinition;
/**
* Defines the **Size** property.
*/
Size: PropertyDefinition;
/**
* Defines the **GlobalSize** property.
*/
GlobalSize: PropertyDefinition;
/**
* Defines the **ItemClasses** property.
*/
ItemClasses: PropertyDefinition;
/**
* Defines the **GlobalItemClasses** property.
*/
GlobalItemClasses: PropertyDefinition;
/**
* Defines the **Importance** property.
*/
Importance: PropertyDefinition;
/**
* Defines the **GlobalImportance** property.
*/
GlobalImportance: PropertyDefinition;
/**
* Defines the **ItemIds** property.
*/
ItemIds: PropertyDefinition;
/**
* Defines the **GlobalItemIds** property.
*/
GlobalItemIds: PropertyDefinition;
/**
* Defines the **LastModifiedTime** property.
*/
LastModifiedTime: PropertyDefinition;
/**
* Defines the **InstanceKey** property.
*/
InstanceKey: PropertyDefinition;
/**
* Defines the **Preview** property.
*/
Preview: PropertyDefinition;
/**
* Defines the **IconIndex** property.
*/
IconIndex: PropertyDefinition;
/**
* Defines the **GlobalIconIndex** property.
*/
GlobalIconIndex: PropertyDefinition;
/**
* Defines the **DraftItemIds** property.
*/
DraftItemIds: PropertyDefinition;
/**
* Defines the **HasIrm** property.
*/
HasIrm: PropertyDefinition;
/**
* Defines the **GlobalHasIrm** property.
*/
GlobalHasIrm: PropertyDefinition;
/**
* @internal Instance of **ConversationSchema**
*/
Instance: ConversationSchema;
}
/**
* Represents the schema for Conversation.
*/
export interface ConversationSchemaStatic extends ConversationSchema {
} | the_stack |
import { Injectable } from '@angular/core';
import { Actions, Effect, ofType } from '@ngrx/effects';
import { select, Store } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { forkJoin, from, Observable } from 'rxjs';
import { catchError, filter, map, mergeMap, switchMap, withLatestFrom } from 'rxjs/operators';
import {
CheckTrianglesAction,
DisplayOverlayAction,
DisplayOverlayFailedAction,
LoadOverlaysAction,
LoadOverlaysSuccessAction,
OverlaysActionTypes, SetOverlaysContainmentChecked,
RequestOverlayByIDFromBackendAction,
SetMarkUp,
SetOverlaysCriteriaAction,
SetOverlaysStatusMessageAction,
UpdateOverlays
} from '../actions/overlays.actions';
import { IOverlay, IOverlaysCriteria, IOverlaysFetchData, RegionContainment } from '../models/overlay.model';
import { BackToWorldView } from '../overlay-status/actions/overlay-status.actions';
import { selectFavoriteOverlays } from '../overlay-status/reducers/overlay-status.reducer';
import {
MarkUpClass,
overlaysStateSelector,
overlaysStatusMessages,
selectDrops,
selectIsFirstSearchRun,
selectOverlaysArray,
selectOverlaysCriteria
} from '../reducers/overlays.reducer';
import { OverlaysService } from '../services/overlays.service';
import { rxPreventCrash } from '../../core/utils/rxjs/operators/rxPreventCrash';
import { getPolygonIntersectionRatio, isPointContainedInGeometry } from '@ansyn/imagery';
import { getErrorLogFromException } from '../../core/utils/logs/timer-logs';
import { LoggerService } from '../../core/services/logger.service';
import { AreaToCredentialsService } from '../../core/services/credentials/area-to-credentials.service';
import { CredentialsService, ICredentialsResponse } from '../../core/services/credentials/credentials.service';
import { getMenuSessionData, SetBadgeAction } from '@ansyn/menu';
import { Update } from '@ngrx/entity';
import { selectFourViewsMode, selectWasWelcomeNotificationShown, SetToastMessageAction } from '@ansyn/map-facade';
import { OpenAdvancedSearchFromOutsideAction, ToggleAdvancedSearchAction, ToggleSimpleSearchAction } from '../../status-bar/actions/status-bar.actions';
@Injectable()
export class OverlaysEffects {
@Effect()
setOverlaysContainedInRegionField$ = this.actions$.pipe(
ofType(OverlaysActionTypes.LOAD_OVERLAYS_SUCCESS),
withLatestFrom(this.store$.select(selectOverlaysCriteria), this.store$.select(selectOverlaysArray)),
filter(([action, criteria, overlays]: [any, IOverlaysCriteria, IOverlay[]]) => Boolean(overlays) && overlays.length > 0),
mergeMap(([action, criteria, overlays]: [any, IOverlaysCriteria, IOverlay[]]) => {
const payload: Update<IOverlay>[] = overlays.map((overlay: IOverlay) => {
const region = criteria.region.geometry;
let containedInSearchPolygon;
try {
if (region.type === 'Point') {
const isContained = isPointContainedInGeometry(region, overlay.footprint);
containedInSearchPolygon = isContained ? RegionContainment.contained : RegionContainment.notContained;
} else {
const ratio = getPolygonIntersectionRatio(region, overlay.footprint);
if (!Boolean(ratio)) {
containedInSearchPolygon = RegionContainment.notContained;
} else if (ratio === 1) {
containedInSearchPolygon = RegionContainment.contained;
} else {
containedInSearchPolygon = RegionContainment.intersect;
}
}
} catch (e) {
console.error('failed to calc overlay intersection ratio of ', overlay, ' error ', e);
containedInSearchPolygon = RegionContainment.unknown;
}
return {
id: overlay.id,
changes: { containedInSearchPolygon }
};
});
return [
new UpdateOverlays(payload),
new SetOverlaysContainmentChecked()
];
}),
rxPreventCrash()
);
@Effect()
setOverlaysCriteria$ = this.actions$.pipe(
ofType<SetOverlaysCriteriaAction>(OverlaysActionTypes.SET_OVERLAYS_CRITERIA),
filter(action => !(action.options && action.options.noInitialSearch)),
withLatestFrom(this.store$.select(selectOverlaysCriteria)),
map(([{ payload }, overlaysCriteria]) => new CheckTrianglesAction(overlaysCriteria)));
userAuthorizedAreas$: Observable<any> = this.credentialsService.getCredentials().pipe(
map((userCredentials: ICredentialsResponse) => userCredentials.authorizedAreas.map(
area => area.Id
)
));
@Effect()
checkTrianglesBeforeSearch$ = this.actions$.pipe(
ofType<CheckTrianglesAction>(OverlaysActionTypes.CHECK_TRIANGLES),
switchMap((action: CheckTrianglesAction) => {
const region = action.payload.region.geometry;
const { isUserFirstEntrance } = getMenuSessionData();
return forkJoin([this.areaToCredentialsService.getAreaTriangles(region), this.userAuthorizedAreas$]).pipe(
mergeMap<any, any>(([trianglesOfArea, userAuthorizedAreas]: [any, any]) => {
if (userAuthorizedAreas.some( area => trianglesOfArea.includes(area))) {
return [new LoadOverlaysAction(action.payload),
new SetBadgeAction({key: 'Permissions', badge: undefined})];
}
return [new LoadOverlaysSuccessAction([]),
new SetOverlaysStatusMessageAction({ message: this.translate.instant(overlaysStatusMessages.noPermissionsForArea) }),
new SetBadgeAction({key: 'Permissions', badge: isUserFirstEntrance ? '' : undefined})];
}),
catchError( () => {
return [new LoadOverlaysAction(action.payload),
new SetBadgeAction({key: 'Permissions', badge: undefined})];
})
)
})
);
@Effect()
loadOverlays$: Observable<{} | LoadOverlaysSuccessAction> = this.actions$.pipe(
ofType<LoadOverlaysAction>(OverlaysActionTypes.LOAD_OVERLAYS),
withLatestFrom(this.store$.select(selectIsFirstSearchRun), this.store$.select(selectFourViewsMode)),
filter(([action, isFirstSearch, isFourViewsMode]: [LoadOverlaysAction, boolean, boolean]) => !isFourViewsMode),
switchMap(([action, isFirstSearch, isFourViewsMode]: [LoadOverlaysAction, boolean, boolean]) => this.requestOverlays(action.payload, isFirstSearch))
);
@Effect()
onRequestOverlayByID$: Observable<any> = this.actions$.pipe(
ofType<RequestOverlayByIDFromBackendAction>(OverlaysActionTypes.REQUEST_OVERLAY_FROM_BACKEND),
mergeMap((action: RequestOverlayByIDFromBackendAction) => {
return this.overlaysService.getOverlayById(action.payload.overlayId, action.payload.sourceType).pipe(
map((overlay: IOverlay) => new DisplayOverlayAction({
overlay,
mapId: action.payload.mapId,
forceFirstDisplay: true
})),
catchError((exception) => {
const errMsg = getErrorLogFromException(exception, `Failed to get overlay id=${action.payload.overlayId} sourceType=${action.payload.sourceType}`);
this.loggerService.error(errMsg, 'overlays', 'Overlay_By_ID');
return from([
new DisplayOverlayFailedAction({ id: action.payload.overlayId, mapId: action.payload.mapId }),
new BackToWorldView({ mapId: action.payload.mapId })
]);
})
);
})
);
@Effect()
setFavoriteOverlaysUpdateCase$: Observable<any> = this.store$.pipe(
select(selectFavoriteOverlays),
map((favoriteOverlays: IOverlay[]) => favoriteOverlays.map(overlay => overlay.id)),
map((overlayIds) => new SetMarkUp({
classToSet: MarkUpClass.favorites,
dataToSet: {
overlaysIds: overlayIds
}
}
))
);
constructor(protected actions$: Actions,
protected store$: Store<any>,
protected translate: TranslateService,
protected overlaysService: OverlaysService,
protected loggerService: LoggerService,
protected credentialsService: CredentialsService,
protected areaToCredentialsService: AreaToCredentialsService) {
}
private requestOverlays(criteria: IOverlaysCriteria, isFirstSearch) {
return this.overlaysService.search(criteria).pipe(
// We use translate.instant instead of withLatestFrom + translate.get
// Because of a bug: sometimes when starting the app the withLatestFrom that was here did not return,
// and the timeline was stuck and not updated. After this fix the pipe works, but once in a while the
// translations that are called here fail, and return the keys instead.
mergeMap<IOverlaysFetchData, any>((overlays: IOverlaysFetchData) => {
const noOverlayMatchQuery = this.translate.instant(overlaysStatusMessages.noOverLayMatchQuery);
const overLoad = this.translate.instant(overlaysStatusMessages.overLoad);
const error = this.translate.instant('Error on overlays request');
const overlaysResult = Array.isArray(overlays.data) ? overlays.data : [];
if (!Array.isArray(overlays.data) && Array.isArray(overlays.errors) && overlays.errors.length >= 0) {
return [new LoadOverlaysSuccessAction(overlaysResult),
new SetOverlaysStatusMessageAction({ message: error, originalMessages: overlays.errors })];
}
const actions: Array<any> = [new LoadOverlaysSuccessAction(overlaysResult)];
// if data.length != fetchLimit that means only duplicate overlays removed
if (!overlays.data || overlays.data.length === 0) {
actions.push(new SetOverlaysStatusMessageAction({ message: noOverlayMatchQuery, originalMessages: overlays.errors }));
} else if (overlays.limited > 0 && overlays.data.length === this.overlaysService.fetchLimit) {
// TODO: replace when design is available
actions.push(new SetOverlaysStatusMessageAction({ message: overLoad.replace('$overLoad', overlays.data.length.toString()) }));
}
if (!isFirstSearch) {
actions.push(new SetToastMessageAction({toastText: 'there are more overlays exist, ', buttonToDisplay: 'click here to expand', functionToExcute: this.toggleAdvancedSearch.bind(this)}))
}
return actions;
}),
catchError((err) => from([
new LoadOverlaysSuccessAction([]),
new SetOverlaysStatusMessageAction({
message: 'Error on overlays request', originalMessages: [{ message: err }]
})
]))
);
}
toggleAdvancedSearch() {
this.store$.dispatch(new ToggleSimpleSearchAction(true));
this.store$.dispatch(new ToggleAdvancedSearchAction(true));
this.store$.dispatch(new OpenAdvancedSearchFromOutsideAction(true));
}
} | the_stack |
import { ResponseHints } from '../../src/response';
import { Source } from '../../src/source';
import {
isPushable,
pushable,
Pushable
} from '../../src/source-interfaces/pushable';
import { buildTransform, Transform } from '../../src/transform';
import {
AddRecordOperation,
RecordData,
RecordOperation,
RecordResponse,
RecordTransformBuilder
} from '../support/record-data';
const { module, test } = QUnit;
module('@pushable', function (hooks) {
interface MySource
extends Source,
Pushable<
RecordData,
RecordResponse,
RecordOperation,
RecordTransformBuilder
> {}
@pushable
class MySource extends Source {}
let source: MySource;
hooks.beforeEach(function () {
source = new MySource({ name: 'src1' });
});
test('isPushable - tests for the application of the @pushable decorator', function (assert) {
assert.ok(isPushable(source));
});
test('should be applied to a Source', function (assert) {
assert.throws(
function () {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: Test of bad typing
@pushable
class Vanilla {}
},
Error(
'Assertion failed: Pushable interface can only be applied to a Source'
),
'assertion raised'
);
});
test('#push should resolve as a failure when `transform` fails', async function (assert) {
assert.expect(2);
source._push = function () {
return Promise.reject(':(');
};
try {
await source.push({
op: 'addRecord',
record: { type: 'planet', id: '1' }
});
} catch (error) {
assert.ok(true, 'push promise resolved as a failure');
assert.equal(error, ':(', 'failure');
}
});
test('#push should trigger `push` event after a successful action in which `transform` returns an array of transforms', async function (assert) {
assert.expect(12);
let order = 0;
const addPlanet1 = buildTransform<RecordOperation>({
op: 'addRecord',
record: { type: 'planet', id: '1' }
});
const addPlanet2 = buildTransform<RecordOperation>({
op: 'addRecord',
record: { type: 'planet', id: '2' }
});
const fullResponse = {
transforms: [addPlanet1, addPlanet2]
};
source.on('beforePush', (transform) => {
assert.equal(++order, 1, 'beforePush triggered first');
assert.strictEqual(transform, addPlanet1, 'transform matches');
});
source._push = async function (transform) {
assert.equal(++order, 2, 'action performed after beforePush');
assert.strictEqual(transform, addPlanet1, 'transform object matches');
return fullResponse;
};
let transformCount = 0;
source.on('transform', (transform) => {
assert.equal(
++order,
3 + transformCount,
'transform triggered after action performed successfully'
);
assert.strictEqual(
transform,
fullResponse.transforms[transformCount++],
'transform matches'
);
return Promise.resolve();
});
source.on('push', (transform) => {
assert.equal(
++order,
5,
'push triggered after action performed successfully'
);
assert.strictEqual(transform, addPlanet1, 'transform matches');
});
let result = await source.push(addPlanet1);
assert.equal(++order, 6, 'promise resolved last');
assert.deepEqual(
result,
fullResponse.transforms,
'applied transforms are returned on success'
);
});
test('#push should trigger `pushFail` event after an unsuccessful push', async function (assert) {
assert.expect(7);
const addPlanet1 = buildTransform<RecordOperation>({
op: 'addRecord',
record: { type: 'planet', id: '1' }
});
let order = 0;
source._push = function (transform) {
assert.equal(++order, 1, 'action performed after willPush');
assert.strictEqual(transform, addPlanet1, 'transform matches');
return Promise.reject(':(');
};
source.on('push', () => {
assert.ok(false, 'push should not be triggered');
});
source.on('pushFail', (transform, error) => {
assert.equal(++order, 2, 'pushFail triggered after an unsuccessful push');
assert.strictEqual(transform, addPlanet1, 'transform matches');
assert.equal(error, ':(', 'error matches');
});
try {
await source.push(addPlanet1);
} catch (error) {
assert.equal(++order, 3, 'promise resolved last');
assert.equal(error, ':(', 'failure');
}
});
test('#push should resolve all promises returned from `beforePush` before calling `_push`', async function (assert) {
assert.expect(7);
let order = 0;
const addPlanet1 = buildTransform<RecordOperation>({
op: 'addRecord',
record: { type: 'planet', id: '1' }
});
const addPlanet2 = buildTransform<RecordOperation>({
op: 'addRecord',
record: { type: 'planet', id: '2' }
});
const resultingTransforms = [addPlanet1, addPlanet2];
source.on('beforePush', () => {
assert.equal(++order, 1, 'beforePush triggered first');
return Promise.resolve();
});
source.on('beforePush', () => {
assert.equal(++order, 2, 'beforePush triggered second');
return undefined;
});
source.on('beforePush', () => {
assert.equal(++order, 3, 'beforePush triggered third');
return Promise.resolve();
});
source._push = async function () {
assert.equal(++order, 4, '_push invoked after all `beforePush` handlers');
return { transforms: resultingTransforms };
};
source.on('push', () => {
assert.equal(
++order,
5,
'push triggered after action performed successfully'
);
});
let result = await source.push(addPlanet1);
assert.equal(++order, 6, 'promise resolved last');
assert.deepEqual(
result,
resultingTransforms,
'applied transforms are returned on success'
);
});
test('#push should still call `_push` if the transform has been applied as a result of `beforePush` resolution', async function (assert) {
assert.expect(5);
let order = 0;
const addPlanet1 = buildTransform<AddRecordOperation>({
op: 'addRecord',
record: { type: 'planet', id: '1' }
});
source.on('beforePush', () => {
assert.equal(++order, 1, 'beforePush triggered first');
// source transformed
source.transformLog.append(addPlanet1.id);
return Promise.resolve();
});
source._push = async function () {
assert.ok(true, '_push should still be reached');
assert.ok(
this.transformLog.contains(addPlanet1.id),
'transform is already contained in the log'
);
return { transforms: [] };
};
source.on('push', () => {
assert.ok(true, 'push should still be reached');
});
await source.push<AddRecordOperation>(addPlanet1);
assert.equal(++order, 2, 'promise resolved last');
});
test('#push should resolve all promises returned from `beforePush` and fail if any fail', async function (assert) {
assert.expect(5);
let order = 0;
const addPlanet1 = buildTransform<RecordOperation>({
op: 'addRecord',
record: { type: 'planet', id: '1' }
});
source.on('beforePush', () => {
assert.equal(++order, 1, 'beforePush triggered first');
return Promise.resolve();
});
source.on('beforePush', () => {
assert.equal(++order, 2, 'beforePush triggered again');
return Promise.reject(':(');
});
source._push = async function () {
assert.ok(false, '_push should not be invoked');
return { transforms: [] };
};
source.on('push', () => {
assert.ok(false, 'push should not be triggered');
});
source.on('pushFail', () => {
assert.equal(++order, 3, 'pushFail triggered after action failed');
});
try {
await source.push(addPlanet1);
} catch (error) {
assert.equal(++order, 4, 'promise failed because no actions succeeded');
assert.equal(error, ':(', 'failure');
}
});
test('#push should pass a common `hints` object to all `beforePush` events and forward it to `_push`', async function (assert) {
assert.expect(11);
let order = 0;
const updatePlanet1 = buildTransform<RecordOperation>({
op: 'updateRecord',
record: { type: 'planet', id: '1' }
});
const updatePlanet2 = buildTransform<RecordOperation>({
op: 'updateRecord',
record: { type: 'planet', id: '2' }
});
const fullResponse = {
transforms: [updatePlanet1, updatePlanet2]
};
let h: ResponseHints<RecordData, RecordResponse>;
source.on(
'beforePush',
async function (
transform: Transform<RecordOperation>,
hints: ResponseHints<RecordData, RecordResponse>
) {
assert.equal(++order, 1, 'beforePush triggered first');
assert.deepEqual(
hints,
{},
'beforePush is passed empty `hints` object'
);
h = hints;
hints.data = [
{ type: 'planet', id: 'venus' },
{ type: 'planet', id: 'mars' }
];
}
);
source.on(
'beforePush',
async function (
transform: Transform<RecordOperation>,
hints: ResponseHints<RecordData, RecordResponse>
) {
assert.equal(++order, 2, 'beforePush triggered second');
assert.strictEqual(
hints,
h,
'beforePush is passed same hints instance'
);
}
);
source.on(
'beforePush',
async function (
transform: Transform<RecordOperation>,
hints: ResponseHints<RecordData, RecordResponse>
) {
assert.equal(++order, 3, 'beforePush triggered third');
assert.strictEqual(
hints,
h,
'beforePush is passed same hints instance'
);
}
);
source._push = async function (
transform: Transform<RecordOperation>,
hints?: ResponseHints<RecordData, RecordResponse>
) {
assert.equal(
++order,
4,
'_query invoked after all `beforePush` handlers'
);
assert.strictEqual(hints, h, '_query is passed same hints instance');
return { data: hints?.data, transforms: fullResponse.transforms };
};
source.on('push', async function () {
assert.equal(
++order,
5,
'push triggered after action performed successfully'
);
});
let result = await source.push(updatePlanet1);
assert.equal(++order, 6, 'promise resolved last');
assert.deepEqual(result, fullResponse.transforms, 'success!');
});
test('#push can return a full response, with `transforms` nested in a response object', async function (assert) {
assert.expect(7);
let order = 0;
const updatePlanet1 = buildTransform<RecordOperation>({
op: 'updateRecord',
record: { type: 'planet', id: '1' }
});
const updatePlanet2 = buildTransform<RecordOperation>({
op: 'updateRecord',
record: { type: 'planet', id: '2' }
});
const fullResponse = {
transforms: [updatePlanet1, updatePlanet2]
};
source._push = async function (transform) {
assert.equal(++order, 1, 'action performed after beforePush');
assert.deepEqual(
transform.operations,
updatePlanet1.operations,
'operations match'
);
return fullResponse;
};
source.on('push', (transform, result) => {
assert.equal(
++order,
2,
'push triggered after action performed successfully'
);
assert.deepEqual(
transform.operations,
updatePlanet1.operations,
'operations match'
);
assert.deepEqual(result, fullResponse, 'result matches');
});
let result = await source.push(updatePlanet1, {
fullResponse: true
});
assert.equal(++order, 3, 'promise resolved last');
assert.deepEqual(result, fullResponse, 'success!');
});
test('#push can return a full response, with `transforms`, `details`, and `sources` nested in a response object', async function (assert) {
assert.expect(9);
let order = 0;
const transform1 = buildTransform<RecordOperation>([
{
op: 'updateRecord',
record: { type: 'planet', id: '1' }
},
{
op: 'updateRecord',
record: { type: 'planet', id: '2' }
}
]);
const data1 = [
{
type: 'planet',
id: 'p1'
}
];
const details1 = {
data: data1,
links: {
self: 'https://example.com/api/planets'
}
};
const expectedResult = {
transforms: [transform1],
details: details1,
// source-specific responses are based on beforePush responses
sources: {
remote: { details: details1 }
}
};
source.on('beforePush', async (transform) => {
assert.equal(++order, 1, 'beforePush triggered first');
assert.strictEqual(
transform.operations,
transform1.operations,
'beforePush: transform matches'
);
return ['remote', { details: details1 }];
});
source._push = async function (transform) {
assert.equal(++order, 2, '_push performed after beforePush');
assert.strictEqual(
transform.operations,
transform1.operations,
'_push: transform matches'
);
return {
transforms: [transform1],
details: details1
};
};
source.on('push', (transform, result) => {
assert.equal(++order, 3, 'push triggered after action');
assert.deepEqual(
transform.operations,
transform1.operations,
'push: transform matches'
);
assert.deepEqual(result, expectedResult, 'push: result matches');
});
const result = await source.push(transform1, {
fullResponse: true
});
assert.equal(++order, 4, 'request resolved last');
assert.deepEqual(result, expectedResult, 'success!');
});
}); | the_stack |
import { AcceptMeetingInvitationMessage } from "../ResponseObjects/AcceptMeetingInvitationMessage";
import { Appointment } from "./Appointment";
import { AppointmentType } from "../../../Enumerations/AppointmentType";
import { AttendeeCollection } from "../../../ComplexProperties/AttendeeCollection";
import { CalendarActionResults } from "../../../Misc/CalendarActionResults";
import { ChangeHighlights } from "../../../ComplexProperties/ChangeHighlights";
import { DateTime } from "../../../DateTime";
import { DeclineMeetingInvitationMessage } from "../ResponseObjects/DeclineMeetingInvitationMessage";
import { DeletedOccurrenceInfoCollection } from "../../../ComplexProperties/DeletedOccurrenceInfoCollection";
import { EmailAddress } from "../../../ComplexProperties/EmailAddress";
import { EnhancedLocation } from "../../../ComplexProperties/EnhancedLocation";
import { ExchangeService } from "../../ExchangeService";
import { ExchangeVersion } from "../../../Enumerations/ExchangeVersion";
import { ICalendarActionProvider } from "../../../Interfaces/ICalendarActionProvider";
import { ItemAttachment } from "../../../ComplexProperties/ItemAttachment";
import { ItemCollection } from "../../../ComplexProperties/ItemCollection";
import { ItemId } from "../../../ComplexProperties/ItemId";
import { LegacyFreeBusyStatus } from "../../../Enumerations/LegacyFreeBusyStatus";
import { MeetingRequestType } from "../../../Enumerations/MeetingRequestType";
import { MeetingResponseType } from "../../../Enumerations/MeetingResponseType";
import { OccurrenceInfo } from "../../../ComplexProperties/OccurrenceInfo";
import { OccurrenceInfoCollection } from "../../../ComplexProperties/OccurrenceInfoCollection";
import { Promise } from "../../../Promise";
import { PropertySet } from "../../PropertySet";
import { Recurrence } from "../../../ComplexProperties/Recurrence/Patterns/Recurrence";
import { Schemas } from "../Schemas/Schemas";
import { ServiceObjectSchema } from "../Schemas/ServiceObjectSchema";
import { TimeSpan } from "../../../TimeSpan";
import { TimeZoneInfo } from "../../../TimeZoneInfo";
import { XmlElementNames } from "../../XmlElementNames";
import { MeetingMessage } from "./MeetingMessage";
/**
* Represents a meeting request that an attendee can accept or decline. Properties available on meeting requests are defined in the MeetingRequestSchema class.
*/
export class MeetingRequest extends MeetingMessage implements ICalendarActionProvider {
/**
* Gets the type of this meeting request.
*/
get MeetingRequestType(): MeetingRequestType {
return <MeetingRequestType>this.PropertyBag._getItem(Schemas.MeetingRequestSchema.MeetingRequestType);
}
/**
* Gets the a value representing the intended free/busy status of the meeting.
*/
get IntendedFreeBusyStatus(): LegacyFreeBusyStatus {
return <LegacyFreeBusyStatus>this.PropertyBag._getItem(Schemas.MeetingRequestSchema.IntendedFreeBusyStatus);
}
/**
* Gets the change highlights of the meeting request.
*/
get ChangeHighlights(): ChangeHighlights {
return <ChangeHighlights>this.PropertyBag._getItem(Schemas.MeetingRequestSchema.ChangeHighlights);
}
/**
* Gets the Enhanced location object.
*/
get EnhancedLocation(): EnhancedLocation {
return <EnhancedLocation>this.PropertyBag._getItem(Schemas.MeetingRequestSchema.EnhancedLocation);
}
/**
* Gets the start time of the appointment.
*/
get Start(): DateTime {
return <DateTime>this.PropertyBag._getItem(Schemas.AppointmentSchema.Start);
}
/**
* Gets the end time of the appointment.
*/
get End(): DateTime {
return <DateTime>this.PropertyBag._getItem(Schemas.AppointmentSchema.End);
}
/**
* Gets the original start time of this appointment.
*/
get OriginalStart(): DateTime {
return <DateTime>this.PropertyBag._getItem(Schemas.AppointmentSchema.OriginalStart);
}
/**
* Gets a value indicating whether this appointment is an all day event.
*/
get IsAllDayEvent(): boolean {
return <boolean>this.PropertyBag._getItem(Schemas.AppointmentSchema.IsAllDayEvent);
}
/**
* Gets a value indicating the free/busy status of the owner of this appointment.
*/
get LegacyFreeBusyStatus(): LegacyFreeBusyStatus {
return <LegacyFreeBusyStatus>this.PropertyBag._getItem(Schemas.AppointmentSchema.LegacyFreeBusyStatus);
}
/**
* Gets the location of this appointment.
*/
get Location(): string {
return <string>this.PropertyBag._getItem(Schemas.AppointmentSchema.Location);
}
/**
* Gets a text indicating when this appointment occurs.
* The text returned by When is localized using the Exchange Server culture or using the culture specified in the PreferredCulture property of the ExchangeService object this appointment is bound to.
*/
get When(): string {
return <string>this.PropertyBag._getItem(Schemas.AppointmentSchema.When);
}
/**
* Gets a value indicating whether the appointment is a meeting.
*/
get IsMeeting(): boolean {
return <boolean>this.PropertyBag._getItem(Schemas.AppointmentSchema.IsMeeting);
}
/**
* Gets a value indicating whether the appointment has been cancelled.
*/
get IsCancelled(): boolean {
return <boolean>this.PropertyBag._getItem(Schemas.AppointmentSchema.IsCancelled);
}
/**
* Gets a value indicating whether the appointment is recurring.
*/
get IsRecurring(): boolean {
return <boolean>this.PropertyBag._getItem(Schemas.AppointmentSchema.IsRecurring);
}
/**
* Gets a value indicating whether the meeting request has already been sent.
*/
get MeetingRequestWasSent(): boolean {
return <boolean>this.PropertyBag._getItem(Schemas.AppointmentSchema.MeetingRequestWasSent);
}
/**
* Gets a value indicating the type of this appointment.
*/
get AppointmentType(): AppointmentType {
return <AppointmentType>this.PropertyBag._getItem(Schemas.AppointmentSchema.AppointmentType);
}
/**
* Gets a value indicating what was the last response of the user that loaded this meeting.
*/
get MyResponseType(): MeetingResponseType {
return <MeetingResponseType>this.PropertyBag._getItem(Schemas.AppointmentSchema.MyResponseType);
}
/**
* Gets the organizer of this meeting.
*/
get Organizer(): EmailAddress {
return <EmailAddress>this.PropertyBag._getItem(Schemas.AppointmentSchema.Organizer);
}
/**
* Gets a list of required attendees for this meeting.
*/
get RequiredAttendees(): AttendeeCollection {
return <AttendeeCollection>this.PropertyBag._getItem(Schemas.AppointmentSchema.RequiredAttendees);
}
/**
* Gets a list of optional attendeed for this meeting.
*/
get OptionalAttendees(): AttendeeCollection {
return <AttendeeCollection>this.PropertyBag._getItem(Schemas.AppointmentSchema.OptionalAttendees);
}
/**
* Gets a list of resources for this meeting.
*/
get Resources(): AttendeeCollection {
return <AttendeeCollection>this.PropertyBag._getItem(Schemas.AppointmentSchema.Resources);
}
/**
* Gets the number of calendar entries that conflict with this appointment in the authenticated user's calendar.
*/
get ConflictingMeetingCount(): number {
return <number>this.PropertyBag._getItem(Schemas.AppointmentSchema.ConflictingMeetingCount);
}
/**
* Gets the number of calendar entries that are adjacent to this appointment in the authenticated user's calendar.
*/
get AdjacentMeetingCount(): number {
return <number>this.PropertyBag._getItem(Schemas.AppointmentSchema.AdjacentMeetingCount);
}
/**
* Gets a list of meetings that conflict with this appointment in the authenticated user's calendar.
*/
get ConflictingMeetings(): ItemCollection<Appointment> {
return <ItemCollection<Appointment>>this.PropertyBag._getItem(Schemas.AppointmentSchema.ConflictingMeetings);
}
/**
* Gets a list of meetings that are adjucent to this appointment in the authenticated user's calendar.
*/
get AdjacentMeetings(): ItemCollection<Appointment> {
return <ItemCollection<Appointment>>this.PropertyBag._getItem(Schemas.AppointmentSchema.AdjacentMeetings);
}
/**
* Gets the duration of this appointment.
*/
get Duration(): TimeSpan {
return <TimeSpan>this.PropertyBag._getItem(Schemas.AppointmentSchema.Duration);
}
/**
* Gets the name of the time zone this appointment is defined in.
*/
get TimeZone(): string {
return <string>this.PropertyBag._getItem(Schemas.AppointmentSchema.TimeZone);
}
/**
* Gets the time when the attendee replied to the meeting request.
*/
get AppointmentReplyTime(): DateTime {
return <DateTime>this.PropertyBag._getItem(Schemas.AppointmentSchema.AppointmentReplyTime);
}
/**
* Gets the sequence number of this appointment.
*/
get AppointmentSequenceNumber(): number {
return <number>this.PropertyBag._getItem(Schemas.AppointmentSchema.AppointmentSequenceNumber);
}
/**
* Gets the state of this appointment.
*/
get AppointmentState(): number {
return <number>this.PropertyBag._getItem(Schemas.AppointmentSchema.AppointmentState);
}
/**
* Gets the recurrence pattern for this meeting request.
*/
get Recurrence(): Recurrence {
return <Recurrence>this.PropertyBag._getItem(Schemas.AppointmentSchema.Recurrence);
}
/**
* Gets an OccurrenceInfo identifying the first occurrence of this meeting.
*/
get FirstOccurrence(): OccurrenceInfo {
return <OccurrenceInfo>this.PropertyBag._getItem(Schemas.AppointmentSchema.FirstOccurrence);
}
/**
* Gets an OccurrenceInfo identifying the last occurrence of this meeting.
*/
get LastOccurrence(): OccurrenceInfo {
return <OccurrenceInfo>this.PropertyBag._getItem(Schemas.AppointmentSchema.LastOccurrence);
}
/**
* Gets a list of modified occurrences for this meeting.
*/
get ModifiedOccurrences(): OccurrenceInfoCollection {
return <OccurrenceInfoCollection>this.PropertyBag._getItem(Schemas.AppointmentSchema.ModifiedOccurrences);
}
/**
* Gets a list of deleted occurrences for this meeting.
*/
get DeletedOccurrences(): DeletedOccurrenceInfoCollection {
return <DeletedOccurrenceInfoCollection>this.PropertyBag._getItem(Schemas.AppointmentSchema.DeletedOccurrences);
}
/**
* Gets time zone of the start property of this meeting request.
*/
get StartTimeZone(): TimeZoneInfo {
return <TimeZoneInfo>this.PropertyBag._getItem(Schemas.AppointmentSchema.StartTimeZone);
}
/**
* Gets time zone of the end property of this meeting request.
*/
get EndTimeZone(): TimeZoneInfo {
return <TimeZoneInfo>this.PropertyBag._getItem(Schemas.AppointmentSchema.EndTimeZone);
}
/**
* Gets the type of conferencing that will be used during the meeting.
*/
get ConferenceType(): number {
return <number>this.PropertyBag._getItem(Schemas.AppointmentSchema.ConferenceType);
}
/**
* Gets a value indicating whether new time proposals are allowed for attendees of this meeting.
*/
get AllowNewTimeProposal(): boolean {
return <boolean>this.PropertyBag._getItem(Schemas.AppointmentSchema.AllowNewTimeProposal);
}
/**
* Gets a value indicating whether this is an online meeting.
*/
get IsOnlineMeeting(): boolean {
return <boolean>this.PropertyBag._getItem(Schemas.AppointmentSchema.IsOnlineMeeting);
}
/**
* Gets the URL of the meeting workspace. A meeting workspace is a shared Web site for planning meetings and tracking results.
*/
get MeetingWorkspaceUrl(): string {
return <string>this.PropertyBag._getItem(Schemas.AppointmentSchema.MeetingWorkspaceUrl);
}
/**
* Gets the URL of the Microsoft NetShow online meeting.
*/
get NetShowUrl(): string {
return <string>this.PropertyBag._getItem(Schemas.AppointmentSchema.NetShowUrl);
}
/**
* @internal Initializes a new instance of the **MeetingRequest** class.
*
* @param {ItemAttachment} parentAttachment The parent attachment.
*/
constructor(parentAttachment: ItemAttachment);
/**
* @internal Initializes a new instance of the **MeetingRequest** class.
*
* @param {ExchangeService} service EWS service to which this object belongs.
*/
constructor(service: ExchangeService);
constructor(parentAttachmentOrService: any) {
super(parentAttachmentOrService);
}
/**
* Accepts the meeting. Calling this method results in a call to EWS.
*
* @param {boolean} sendResponse Indicates whether to send a response to the organizer.
* @return {Promise<CalendarActionResults>} A CalendarActionResults object containing the various items that were created or modified as a results of this operation :Promise.
*/
Accept(sendResponse: boolean): Promise<CalendarActionResults> {
return this.InternalAccept(false, sendResponse);
}
/**
* Tentatively accepts the meeting. Calling this method results in a call to EWS.
*
* @param {boolean} sendResponse Indicates whether to send a response to the organizer.
* @return {Promise<CalendarActionResults>} A CalendarActionResults object containing the various items that were created or modified as a results of this operation :Promise.
*/
AcceptTentatively(sendResponse: boolean): Promise<CalendarActionResults> {
return this.InternalAccept(true, sendResponse);
}
/**
* Binds to an existing meeting request and loads the specified set of properties. Calling this method results in a call to EWS.
*
* @param {ExchangeService} service The service to use to bind to the meeting request.
* @param {ItemId} id The Id of the meeting request to bind to.
* @param {PropertySet} propertySet The set of properties to load.
* @return {Promise<MeetingRequest>} A MeetingRequest instance representing the meeting request corresponding to the specified Id :Promise.
*/
public static Bind(service: ExchangeService, id: ItemId, propertySet: PropertySet): Promise<MeetingRequest>;
/**
* Binds to an existing meeting request and loads its first class properties.
*
* @param {ExchangeService} service The service to use to bind to the meeting request.
* @param {ItemId} id The Id of the meeting request to bind to.
* @return {Promise<MeetingRequest>} A MeetingRequest instance representing the meeting request corresponding to the specified Id :Promise.
*/
public static Bind(service: ExchangeService, id: ItemId): Promise<MeetingRequest>;
public static Bind(service: ExchangeService, id: ItemId, propertySet: PropertySet = PropertySet.FirstClassProperties): Promise<MeetingRequest> {
return service.BindToItem<MeetingRequest>(id, propertySet, MeetingRequest);
}
/**
* Creates a local meeting acceptance message that can be customized and sent.
*
* @param {boolean} tentative Specifies whether the meeting will be tentatively accepted.
* @return {AcceptMeetingInvitationMessage} An AcceptMeetingInvitationMessage representing the meeting acceptance message.
*/
CreateAcceptMessage(tentative: boolean): AcceptMeetingInvitationMessage {
return new AcceptMeetingInvitationMessage(this, tentative);
}
/**
* Creates a local meeting declination message that can be customized and sent.
*
* @return {DeclineMeetingInvitationMessage} A DeclineMeetingInvitation representing the meeting declination message.
*/
CreateDeclineMessage(): DeclineMeetingInvitationMessage {
return new DeclineMeetingInvitationMessage(this);
}
/**
* Declines the meeting invitation. Calling this method results in a call to EWS.
*
* @param {boolean} sendResponse Indicates whether to send a response to the organizer.
* @return {Promise<CalendarActionResults>} A CalendarActionResults object containing the various items that were created or modified as a results of this operation :Promise.
*/
Decline(sendResponse: boolean): Promise<CalendarActionResults> {
let decline: DeclineMeetingInvitationMessage = this.CreateDeclineMessage();
if (sendResponse) {
return decline.SendAndSaveCopy();
}
else {
return decline.Save();
}
}
/**
* @internal Gets the minimum required server version.
*
* @return {ExchangeVersion} Earliest Exchange version in which this service object type is supported.
*/
GetMinimumRequiredServerVersion(): ExchangeVersion {
return ExchangeVersion.Exchange2007_SP1;
}
/**
* @internal Internal method to return the schema associated with this type of object.
*
* @return {ServiceObjectSchema} The schema associated with this type of object.
*/
GetSchema(): ServiceObjectSchema {
return Schemas.MeetingRequestSchema.Instance;
}
/**
* @internal Gets the element name of item in XML
*
* @return {string} name of elelment
*/
GetXmlElementName(): string {
return XmlElementNames.MeetingRequest;
}
/**
* @internal Accepts the meeting.
*
* @param {boolean} tentative True if tentative accept.
* @param {boolean} sendResponse Indicates whether to send a response to the organizer.
* @return {Promise<CalendarActionResults>} A CalendarActionResults object containing the various items that were created or modified as a results of this operation :Promise.
*/
InternalAccept(tentative: boolean, sendResponse: boolean): Promise<CalendarActionResults> {
let accept: AcceptMeetingInvitationMessage = this.CreateAcceptMessage(tentative);
if (sendResponse) {
return accept.SendAndSaveCopy();
}
else {
return accept.Save();
}
}
} | the_stack |
import { Iterate, IterateAction } from 'iteratez';
import { CalendarDay } from './CalendarDay';
import { CalendarEvent } from './CalendarEvent';
import { Constants } from './Constants';
import { Day, DayInput } from './Day';
import { DaySpan } from './DaySpan';
import { Event, EventInput } from './Event';
import { Functions as fn } from './Functions';
import { Op } from './Operation';
import { Parse } from './Parse';
import { Schedule } from './Schedule';
import { SortEvent } from './Sort';
import { Units } from './Units';
/**
* A function which moves a given day by some amount and some unit. This is
* used to shift a calendar's frame via [[Calendar.next]] and [[Calendar.prev]].
*
* @param day The day to move.
* @param amount The amount to move the day by.
* @returns A new day instance moved by the given amount.
*/
export type CalendarMover = (day: Day, amount: number) => Day;
/**
* A definition for a given [[Units]] which informs a calendar how to setup the
* [[Calendar.span]] and how to move with [[Calendar.move]].
*/
export interface CalendarTypeDefinition
{
getStart(around: Day, size: number, focus: number): Day;
getEnd(start: Day, size: number, focus: number): Day;
moveStart(day: Day, amount: number): Day;
moveEnd(day: Day, amount: number): Day;
defaultInput: any
}
/**
* A map of [[CalendarTypeDefinition]] keyed by the [[Units]].
*/
export type CalendarTypeDefinitionMap = { [unit: number]: CalendarTypeDefinition };
/**
* Input used to initialize or mass change the properties of a [[Calendar]].
*
* @typeparam T The type of data stored in the [[Event]] class.
* @typeparam M The type of metadata stored in the schedule.
*/
export interface CalendarInput<T, M>
{
/**
* @see [[Calendar.fill]]
*/
fill?: boolean;
/**
* @see [[Calendar.minimumSize]]
*/
minimumSize?: number;
/**
* @see [[Calendar.repeatCovers]]
*/
repeatCovers?: boolean;
/**
* @see [[Calendar.listTimes]]
*/
listTimes?: boolean;
/**
* @see [[Calendar.eventsOutside]]
*/
eventsOutside?: boolean;
/**
* @see [[Calendar.updateRows]]
*/
updateRows?: boolean;
/**
* @see [[Calendar.updateColumns]]
*/
updateColumns?: boolean;
/**
* @see [[Calendar.eventSorter]]
*/
eventSorter?: SortEvent<T, M>;
/**
* @see [[Calendar.events]]
*/
events?: EventInput<T, M>[];
/**
* @see [[Calendar.type]]
*/
type?: Units;
/**
* @see [[Calendar.size]]
*/
size?: number; // 1
/**
* @see [[Calendar.parseMeta]]
*/
parseMeta?(input: any): M;
/**
* @see [[Calendar.parseData]]
*/
parseData?(input: any): T;
/**
* When morphing a calendar to a fewer number of days, do we want to keep
* today in the calendar if it is already in the calendar?
*/
preferToday?: boolean; // true
/**
* What day should the calendar be based around (contain)?
*/
around?: DayInput; // null
/**
* When morphing a calendar and `preferToday` is false OR today is not in the
* calendar AND `around` is not specified, we will pick a day at this number
* in the current calendar (a value between 0 and 1 signifying the start and
* and of the current calendar).
*/
otherwiseFocus?: number; // 0.499999
/**
* When morphing or creating passing a value of `true` will avoid calling
* [[Calendar.refresh]] as is typically done right after each of those
* functions.
*/
delayRefresh?: boolean; // false
}
/**
* A collection of [[CalendarDay]]s, the events on the calendar, and all
* [[CalendarEvent]]s generated based on the events.
*
* @typeparam T The type of data stored in the [[Event]] class.
* @typeparam M The type of metadata stored in the schedule.
*/
export class Calendar<T, M>
{
public static readonly DEFAULT_FOCUS = 0.4999;
/**
* The span of days in the calendar.
*/
public span: DaySpan;
/**
* The full span of days represented on the calendar. This may be different
* than the [[Calendar.span]] when [[Calendar.fill]] is `true` and the
* calendar is representing months or years and the days need to start on
* Sunday and end on Saturday.
*/
public filled: DaySpan;
/**
* The number of days in the calendar specified by [[Calendar.span]].
*/
public length: number;
/**
* The type of calendar.
*/
public type: Units;
/**
* The size of the calendar. When the calendar type is...
*
* - [[Units.DAY]]: The number of days in the calendar.
* - [[Units.WEEK]]: The number of weeks in the calendar.
* - [[Units.MONTH]]: The number of months in the calendar.
* - [[Units.YEAR]]: The number of years in the calendar.
*/
public size: number;
/**
* The function used to move the start day of the calendar when functions like
* [[Calendar.next]] or [[Calendar.prev]] are called.
*/
public moveStart: CalendarMover;
/**
* The function used to move the end day of the calendar when functions like
* [[Calendar.next]] or [[Calendar.prev]] are called.
*/
public moveEnd: CalendarMover;
/**
* If the calendar should be filled in so the first day of the calendar is
* Sunday and the last day is Saturday.
*/
public fill: boolean = false;
/**
* The minimum number of days in the calendar no matter what the type or size
* is. This can be used to display a month with a constant number of weeks -
* because not all months contain the same number of weeks.
*/
public minimumSize: number = 0;
/**
* When `true` a [[CalendarEvent]] instance exists on each [[CalendarDay]]
* the event covers even if the event didn't start on that day.
*/
public repeatCovers: boolean = true;
/**
* When `true` an event instance will be created for each time specified on
* the schedule. If the schedule specifies an all day event then only one
* event is added to a day. This is typically done when displaying days or
* weeks and events can be displayed on a timeline.
*/
public listTimes: boolean = false;
/**
* When `true` events will be added to days "outside" the calendar. Days
* outside the calendar are days filled in when [[Calendar.fill]] is `true`.
* More specifically days that are in [[Calendar.filled]] and not in
* [[Calendar.span]].
*/
public eventsOutside: boolean = false;
/**
* When `true` [[CalendarEvent.row]] will be set so when visually displaying
* the event with others multi-day events will align and not overlap.
*/
public updateRows: boolean = false;
/**
* When `true` [[CalendarEvent.col]] will be set so when visually displaying
* the event based on start and end time any events that overlap with each
* other will be "indented" to see the event below it.
*/
public updateColumns: boolean = false;
/**
* The function (if any) which sorts the events on a calendar day.
*/
public eventSorter: SortEvent<T, M> = null;
/**
* A function to use when parsing meta input into the desired type.
*
* @param input The input to parse.
* @returns The meta parsed from the given input, if any.
*/
public parseMeta: (input: any) => M = (x => x);
/**
* A function to use when parsing meta input into the desired type.
*
* @param input The input to parse.
* @returns The meta parsed from the given input, if any.
*/
public parseData: (input: any) => T = (x => x);
/**
* A selection of days on the calendar. If no days are selected this is `null`.
* This is merely used to keep the selection flags in [[CalendarDay]] updated
* via [[Calendar.refreshSelection]].
*/
public selection: DaySpan = null;
/**
* The array of days in this calendar and their events.
*/
public days: CalendarDay<T, M>[] = [];
/**
* The array of scheduled events added to the calendar.
*/
public events: Event<T, M>[] = [];
/**
* The array of visible events on the calendar. This is built based on the
* span of the schedule in the given event and also the [[Event.visible]] flag.
*/
public visible: Event<T, M>[] = [];
/**
* Creates a new calendar given a span, type, size, moving functions, and
* optionally some default properties for the calendar.
*
* @param start The first day on the calendar.
* @param end The last day on the calendar.
* @param type The calendar type used for describing the calendar and splitting it.
* @param size The number of calendar types in this calendar.
* @param moveStart The function to move the start day.
* @param moveEnd The function to move the end by.
* @param input The default properties for this calendar.
* @see [[Calendar.start]]
* @see [[Calendar.end]]
* @see [[Calendar.type]]
* @see [[Calendar.size]]
* @see [[Calendar.moveStart]]
* @see [[Calendar.moveEnd]]
*/
public constructor(start: Day, end: Day, type: Units, size: number, moveStart: CalendarMover, moveEnd: CalendarMover, input?: CalendarInput<T, M>)
{
this.span = new DaySpan(start, end);
this.filled = new DaySpan(start, end);
this.type = type;
this.size = size;
this.moveStart = moveStart;
this.moveEnd = moveEnd;
if (fn.isDefined(input))
{
this.set( input );
}
else
{
this.refresh();
}
}
/**
* Changes the calendar possibly morphing it to a different type or size if
* specified in the given input. If the type and size are not morphed then
* the following properties may be updated:
*
* - [[Calendar.fill]]
* - [[Calendar.minimumSize]]
* - [[Calendar.repeatCovers]]
* - [[Calendar.listTimes]]
* - [[Calendar.eventsOutside]]
* - [[Calendar.updateRows]]
* - [[Calendar.updateColumns]]
* - [[Calendar.eventSorter]]
* - [[Calendar.events]]
* - [[Calendar.parseData]]
* - [[Calendar.parseMeta]]
*
* If [[CalendarInput.delayRefresh]] is not given with `true` then
* [[Calendar.refresh]] will be called once the calendar properties have been
* updated.
*
* @param input The new properties for this calendar to overwrite with.
*/
public set(input: CalendarInput<T, M>): this
{
type CTD = CalendarTypeDefinition;
const typeChange: boolean = fn.isDefined(input.type) && input.type !== this.type;
const sizeChange: boolean = fn.isDefined(input.size) && input.size !== this.size;
if (typeChange || sizeChange)
{
const focus: number = fn.coalesce( input.otherwiseFocus, Calendar.DEFAULT_FOCUS );
const prefer: boolean = fn.coalesce( input.preferToday, true );
const size: number = fn.coalesce( input.size, this.size );
const type: Units = fn.coalesce( input.type, this.type );
const today: Day = Day.today();
let around: DayInput = fn.coalesce( input.around, this.days[ Math.floor( (this.days.length - 1) * focus ) ] );
if (!around || (prefer && this.span.matchesDay(today)))
{
around = today;
}
const meta: CTD = Calendar.TYPES[ type ];
const start: Day = meta.getStart( Day.parse( around ), size, focus );
const end: Day = meta.getEnd( start, size, focus );
this.span.start = start;
this.span.end = end;
this.type = type;
this.size = size;
this.moveStart = meta.moveStart;
this.moveEnd = meta.moveEnd;
}
else if (input.around)
{
const focus: number = fn.coalesce( input.otherwiseFocus, Calendar.DEFAULT_FOCUS );
const around: Day = Day.parse( input.around );
const type: Units = this.type;
const size: number = this.size;
const meta: CTD = Calendar.TYPES[ type ];
const start: Day = meta.getStart( around, size, focus );
const end: Day = meta.getEnd( start, size, focus );
this.span.start = start;
this.span.end = end;
}
this.fill = fn.coalesce( input.fill, this.fill );
this.minimumSize = fn.coalesce( input.minimumSize, this.minimumSize );
this.repeatCovers = fn.coalesce( input.repeatCovers, this.repeatCovers );
this.listTimes = fn.coalesce( input.listTimes, this.listTimes );
this.eventsOutside = fn.coalesce( input.eventsOutside, this.eventsOutside );
this.updateRows = fn.coalesce( input.updateRows, this.updateRows );
this.updateColumns = fn.coalesce( input.updateColumns, this.updateColumns );
this.eventSorter = fn.coalesce( input.eventSorter, this.eventSorter );
this.parseMeta = fn.coalesce( input.parseMeta, this.parseMeta );
this.parseData = fn.coalesce( input.parseData, this.parseData );
if (fn.isArray(input.events))
{
this.setEvents(input.events, true);
}
if (!input.delayRefresh)
{
this.refresh();
}
return this;
}
/**
* Sets the [[Calendar.minimumSize]] value and returns `this` for method
* chaining.
*
* @param minimumSize The new value.
*/
public withMinimumSize(minimumSize: number): this
{
this.minimumSize = minimumSize;
this.refresh();
return this;
}
/**
* Sets the [[Calendar.repeatCovers]] value and returns `this` for method
* chaining.
*
* @param repeatCovers The new value.
*/
public withRepeatCovers(repeatCovers: boolean): this
{
this.repeatCovers = repeatCovers;
this.refreshEvents();
return this;
}
/**
* Sets the [[Calendar.listTimes]] value and returns `this` for method
* chaining.
*
* @param listTimes The new value.
*/
public withListTimes(listTimes: boolean): this
{
this.listTimes = listTimes;
this.refreshEvents();
return this;
}
/**
* Sets the [[Calendar.eventsOutside]] value and returns `this` for method
* chaining.
*
* @param eventsOutside The new value.
*/
public withEventsOutside(eventsOutside: boolean): this
{
this.eventsOutside = eventsOutside;
this.refreshEvents();
return this;
}
/**
* Sets the [[Calendar.updateRows]] value and returns `this` for method
* chaining.
*
* @param updateRows The new value.
* @param refresh If the rows should be updated now if `updateRows` is `true`.
*/
public withUpdateRows(updateRows: boolean, refresh: boolean = true): this
{
this.updateRows = updateRows;
if (refresh && updateRows)
{
this.refreshRows();
}
return this;
}
/**
* Sets the [[Calendar.updateColumns]] value and returns `this` for method
* chaining.
*
* @param updateColumns The new value.
* @param refresh If the columns should be updated now if `updateColumns` is
* `true`.
*/
public withUpdateColumns(updateColumns: boolean, refresh: boolean = true): this
{
this.updateColumns = updateColumns;
if (refresh && updateColumns)
{
this.refreshColumns();
}
return this;
}
/**
* Returns the start day of the calendar. If this calendar is filled, this
* may not represent the very first day in the calendar.
*/
public get start(): Day
{
return this.span.start;
}
/**
* Returns the end day of the calendar. If this calendar is filled, this
* may not represent the very last day in the calendar.
*/
public get end(): Day
{
return this.span.end;
}
/**
* Returns the summary of the span of time this calendar represents.
*
* @param dayOfWeek [[DaySpan.summary]]
* @param short [[DaySpan.summary]]
* @param repeat [[DaySpan.summary]]
* @param contextual [[DaySpan.summary]]
* @param delimiter [[DaySpan.summary]]
* @see [[DaySpan.summary]]
*/
public summary(dayOfWeek: boolean = true, short: boolean = false, repeat: boolean = false, contextual: boolean = true, delimiter: string = ' - '): string
{
return this.span.summary( this.type, dayOfWeek, short, repeat, contextual, delimiter );
}
/**
* Splits up this calendar into an iterable collection of calendars. The
* resulting iterator will return `size / by` number of calendars.
*
* @param by The new size of the resulting calendars. If the the size of the
* current calendar is not divisible by this value the resulting calendars
* may cover more or less than this calendar covers.
* @returns An iterator for the calendars produced.
*/
public split(by: number = 1): Iterate<Calendar<T, M>, number, Calendar<T, M>>
{
return new Iterate<Calendar<T, M>, number, Calendar<T, M>>(iterator =>
{
let start: Day = this.start;
let end: Day = this.moveEnd( this.end, by - this.size );
for (let i = 0; i < this.size; i++)
{
const calendar = new Calendar(start, end, this.type, by, this.moveStart, this.moveEnd, this);
if (iterator.act(calendar, i) === IterateAction.STOP)
{
return;
}
start = this.moveStart( start, by );
end = this.moveEnd( end, by );
}
});
}
/**
* Refreshes the days and events in this calendar based on the start and end
* days, the calendar properties, and its eventss.
*
* @param today The current day to update the calendar days via
* [[CalendarDay.updateCurrent]].
*/
public refresh(today: Day = Day.today()): this
{
this.length = this.span.days(Op.UP, true);
this.resetDays();
this.refreshCurrent(today);
this.refreshSelection();
this.refreshVisible();
this.refreshEvents();
return this;
}
/**
* Updates the [[Calendar.filled]] span based on [[Calendar.start]],
* [[Calendar.end]], and [[Calendar.fill]] properties.
*/
public resetFilled(): this
{
this.filled.start = this.fill ? this.start.startOf('week') : this.start;
this.filled.end = this.fill ? this.end.endOf('week') : this.end;
return this;
}
/**
* Updates [[Calendar.days]] to match the span of days in the calendar.
*/
public resetDays(): this
{
this.resetFilled();
const days: CalendarDay<T, M>[] = this.days;
const filled: DaySpan = this.filled;
const daysBetween: number = filled.days(Op.UP);
const total: number = Math.max( this.minimumSize, daysBetween );
let current: Day = filled.start;
for (let i = 0; i < total; i++)
{
let day: CalendarDay<T, M> = days[ i ];
if (!day || !day.sameDay( current ))
{
day = new CalendarDay<T, M>( current.date );
if (i < days.length)
{
days.splice( i, 1, day );
}
else
{
days.push( day );
}
}
day.inCalendar = this.span.contains( day );
current = current.next();
}
if (days.length > total)
{
days.splice( total, days.length - total );
}
return this;
}
/**
* Updates the list of visible schedules.
*/
public refreshVisible(): this
{
const start: Day = this.filled.start;
const end: Day = this.filled.end;
this.visible = this.events.filter(e =>
{
return e.visible && e.schedule.matchesRange(start, end);
});
return this;
}
/**
* Updates the days with the current day via [[CalendarDay.updateCurrent]].
*
* @param today The new current day.
*/
public refreshCurrent(today: Day = Day.today()): this
{
this.iterateDays().each(d => d.updateCurrent(today));
return this;
}
/**
* Updates the selection flags in [[CalendarDay]] based on the
* [[Calendar.selection]] property.
*/
public refreshSelection(): this
{
this.iterateDays().each(d =>
{
if (this.selection)
{
d.updateSelected( this.selection );
}
else
{
d.clearSelected();
}
});
return this;
}
/**
* Updates the [[CalendarDay.events]] based on the events in this calendar
* and the following properties:
*
* - [[Calendar.eventsForDay]]
* - [[Calendar.eventsOutside]]
* - [[Calendar.listTimes]]
* - [[Calendar.repeatCovers]]
* - [[Calendar.updateRows]]
* - [[Calendar.updateColumns]]
*/
public refreshEvents(): this
{
this.iterateDays().each(d =>
{
if (d.inCalendar || this.eventsOutside)
{
d.events = this.eventsForDay(d, this.listTimes, this.repeatCovers);
}
});
if (this.updateRows)
{
this.refreshRows();
}
if (this.updateColumns)
{
this.refreshColumns();
}
return this;
}
/**
* Refreshes the [[CalendarEvent.row]] property as described in the link.
*/
public refreshRows(): this
{
type EventToRowMap = { [id: number]: number };
type UsedMap = { [row: number]: boolean };
const onlyFullDay: boolean = this.listTimes;
let eventToRow: EventToRowMap = {};
this.iterateDays().each(d =>
{
if (d.dayOfWeek === 0)
{
eventToRow = {};
}
const used: UsedMap = {};
for (const event of d.events)
{
if (onlyFullDay && !event.fullDay)
{
continue;
}
if (event.id in eventToRow)
{
used[ event.row = eventToRow[ event.id ] ] = true;
}
}
let rowIndex: number = 0;
for (const event of d.events)
{
if ((onlyFullDay && !event.fullDay) || event.id in eventToRow)
{
continue;
}
while (used[ rowIndex ])
{
rowIndex++;
}
eventToRow[ event.id ] = event.row = rowIndex;
rowIndex++;
}
});
return this;
}
/**
* Refreshes the [[CalendarEvent.col]] property as described in the link.
*/
public refreshColumns(): this
{
interface Marker {
time: number,
event: CalendarEvent<T, M>,
start: boolean,
parent: Marker;
}
this.iterateDays().each(d =>
{
const markers: Marker[] = [];
for (const event of d.events)
{
if (!event.fullDay)
{
markers.push({
event,
time: event.time.start.time,
start: true,
parent: null
});
markers.push({
event,
time: event.time.end.time - 1,
start: false,
parent: null
});
}
}
markers.sort((a, b) =>
{
return a.time - b.time;
});
let parent = null;
for (const marker of markers)
{
if (marker.start)
{
marker.parent = parent;
parent = marker;
}
else if (parent)
{
parent = parent.parent;
}
}
for (const marker of markers)
{
if (marker.start)
{
marker.event.col = marker.parent ? marker.parent.event.col + 1 : 0;
}
}
});
return this;
}
/**
* Gets the calendar day for the given day.
*
* @param input The day to get the calendar day for.
* @returns The reference to the calendar day, or null if the given input
* is not on this calendar.
*/
public getDay(input: DayInput): CalendarDay<T, M>
{
const parsed: Day = Day.parse( input );
if (parsed)
{
const dayCount: number = parsed.startOf('day').daysBetween( this.days[ 0 ], Op.DOWN, false );
return this.days[ dayCount ];
}
return null;
}
/**
* Iterates over all days in this calendar and passes each day to `iterator`.
*
* @param iterator The function to pass [[CalendarDay]]s to.
*/
public iterateDays(): Iterate<CalendarDay<T, M>, number, Calendar<T, M>>
{
return new Iterate<CalendarDay<T, M>, number, Calendar<T, M>>(iterator =>
{
const days: CalendarDay<T, M>[] = this.days;
for (let i = 0; i < days.length; i++)
{
switch (iterator.act(days[i], i))
{
case IterateAction.STOP:
return;
}
}
});
}
/**
* Returns the events for the given day optionally looking at schedule times,
* optionally looking at events which cover multiple days, and optionally
* sorted with the given function.
*
* @param day The day to find events for.
* @param getTimes When `true` an event is added to the result for each time
* specified in the schedule.
* @param covers When `true` events which don't start on the given day but do
* overlap are added to the result.
* @param sorter The function to sort the events by, if any.
* @returns An array of events that occurred on the given day.
*/
public eventsForDay(day: Day, getTimes: boolean = true, covers: boolean = true, sorter: SortEvent<T, M> = this.eventSorter): CalendarEvent<T, M>[]
{
const events: CalendarEvent<T, M>[] = [];
const entries: Event<T, M>[] = this.visible;
for (let entryIndex = 0; entryIndex < entries.length; entryIndex++)
{
const entry: Event<T, M> = entries[ entryIndex ];
const schedule: Schedule<M> = entry.schedule;
const eventId: number = entryIndex * Constants.MAX_EVENTS_PER_DAY;
let timeIndex: number = 0;
schedule.iterateSpans( day, covers ).each((span, key, iterator) =>
{
events.push(new CalendarEvent(eventId + timeIndex++, entry, span, day));
if (!getTimes)
{
iterator.stop();
}
});
}
if (sorter)
{
events.sort( sorter );
}
return events
}
/**
* Finds the event given one of the ways to identify the event.
*
* @param input The value to use to search for an event.
* @returns The refrence to the event or null if not found.
*/
public findEvent(id: any): Event<T, M>
{
for (const event of this.events)
{
if (event === id || event.schedule === id || event.data === id || event.id === id)
{
return event;
}
}
return null;
}
/**
* Removes the list of events if they exist in the calendar.
*
* @param events The array of events to remove if they exist. If no
* events are passed (via `null`) then all events will be removed
* from the calendar.
* @param delayRefresh When `true` the [[Calendar.refreshEvents]] will not be
* called after the events are removed.
* @see [[Calendar.removeEvent]]
* @see [[Calendar.refreshEvents]]
*/
public removeEvents(events: any[] = null, delayRefresh: boolean = false): this
{
if (events)
{
for (const event of events)
{
this.removeEvent( event, true );
}
}
else
{
this.events = [];
}
this.refreshVisible();
if (!delayRefresh)
{
this.refreshEvents();
}
return this;
}
/**
* Removes the given event if it exists on the calendar.
*
* @param event The event to remove if it exists.
* @param delayRefresh When `true` the [[Calendar.refreshEvents]] will not be
* called after the event is removed.
* @see [[Calendar.refreshEvents]]
*/
public removeEvent(event: any, delayRefresh: boolean = false): this
{
const found: Event<T, M> = this.findEvent(event);
if (found)
{
this.events.splice( this.events.indexOf(found), 1 );
this.refreshVisible();
if (!delayRefresh)
{
this.refreshEvents();
}
}
return this;
}
/**
* Adds the given event to this calendar if it doesn't exist already (or
* `allowDuplicates` is `true`).
*
* @param event The event to add to the calendar.
* @param allowDuplicates If an event can be added more than once.
* @param delayRefresh When `true` the [[Calendar.refreshEvents]] will not be
* called after the event is added.
* @see [[Calendar.refreshEvents]]
*/
public addEvent(event: EventInput<T, M>, allowDuplicates: boolean = false, delayRefresh: boolean = false): this
{
const parsed: Event<T, M> = Parse.event<T, M>(event, this.parseData, this.parseMeta);
if (!allowDuplicates)
{
const existing = this.findEvent(parsed);
if (existing)
{
return this;
}
}
this.events.push(parsed);
this.refreshVisible();
if (!delayRefresh)
{
this.refreshEvents();
}
return this;
}
/**
* Adds the given events to this calendar if they don't exist already (or
* `allowDuplicates` is `true`).
*
* @param events The events to add to the calendar.
* @param allowDuplicates If an event can be added more than once.
* @param delayRefresh When `true` the [[Calendar.refreshEvents]] will not be
* called after the events are added.
* @see [[Calendar.refreshEvents]]
*/
public addEvents(events: EventInput<T, M>[], allowDuplicates: boolean = false, delayRefresh: boolean = false): this
{
for (const event of events)
{
this.addEvent(event, allowDuplicates, true);
}
if (!delayRefresh)
{
this.refreshEvents();
}
return this;
}
/**
* Sets the given events to this calendar replacing the current list of
* events.
*
* @param events The events to set to the calendar.
* @param delayRefresh When `true` the [[Calendar.refreshEvents]] will not be
* called after the events are added.
* @see [[Calendar.refreshEvents]]
*/
public setEvents(events: EventInput<T, M>[], delayRefresh: boolean = false): this
{
const parsedEvents = [];
for (const event of events)
{
const parsed: Event<T, M> = Parse.event<T, M>(event, this.parseData, this.parseMeta);
if (parsed)
{
parsedEvents.push(parsed);
}
}
this.events = parsedEvents;
this.refreshVisible();
if (!delayRefresh)
{
this.refreshEvents();
}
return this;
}
/**
* Sets the selection point or range of the calendar and updates the flags
* in the days.
*
* @param start The start of the selection.
* @param end The end of the selection.
* @see [[Calendar.refreshSelection]]
*/
public select(start: Day, end: Day = start): this
{
this.selection = new DaySpan( start, end );
this.refreshSelection();
return this;
}
/**
* Sets the selection of the calendar to nothing.
*
* @see [[Calendar.refreshSelection]]
*/
public unselect(): this
{
this.selection = null;
this.refreshSelection();
return this;
}
/**
* Shifts the calendar days by the given amount.
*
* @param jump The amount to shift the calendar by.
* @param delayRefresh When `true` [[Calendar.refresh]] will not be called
* after calendar is moved.
*/
public move(jump: number = this.size, delayRefresh: boolean = false): this
{
this.span.start = this.moveStart( this.start, jump );
this.span.end = this.moveEnd( this.end, jump );
if (!delayRefresh)
{
this.refresh();
}
return this;
}
/**
* Moves the calenndar to the next set of days.
*
* @param jump The amount to shift the calendar by.
* @param delayRefresh When `true` [[Calendar.refresh]] will not be called
* after calendar is moved.
*/
public next(jump: number = this.size, delayRefresh: boolean = false): this
{
return this.move( jump, delayRefresh );
}
/**
* Moves the calenndar to the previous set of days.
*
* @param jump The amount to shift the calendar by.
* @param delayRefresh When `true` [[Calendar.refresh]] will not be called
* after calendar is moved.
*/
public prev(jump: number = this.size, delayRefresh: boolean = false): this
{
return this.move( -jump, delayRefresh );
}
/**
* Converts this calendar to input which can be used to later recreate this
* calendar. The only properties of the calendar which will be loss is the
* [[Calendar.eventSorter]] property because it is a function.
*
* @param plain If the returned input should be plain objects as opposed
* to [[Day]] and [[Event]] instances.
* @param plainData A function to convert [[Event.data]] to a plain object if
* it is not already.
* @param plainMeta A function to convert values in [[Schedule.meta]] to plain
* objects if they are not alreday.
* @returns The input generated from this calendar.
*/
public toInput(plain: boolean = false,
plainData: (data: T) => any = d => d,
plainMeta: (meta: M) => any = m => m): CalendarInput<T, M>
{
const out: CalendarInput<T, M> = {};
out.type = this.type;
out.size = this.size;
out.fill = this.fill;
out.minimumSize = this.minimumSize;
out.repeatCovers = this.repeatCovers;
out.listTimes = this.listTimes;
out.eventsOutside = this.eventsOutside;
out.updateRows = this.updateRows;
out.updateColumns = this.updateColumns;
out.around = plain ? this.span.start.time : this.span.start;
out.events = [];
for (const event of this.events)
{
if (plain)
{
const plainEvent: any = {};
if (fn.isDefined(event.id))
{
plainEvent.id = event.id;
}
if (fn.isDefined(event.data))
{
plainEvent.data = plainData( event.data );
}
if (!event.visible)
{
plainEvent.visible = event.visible;
}
plainEvent.schedule = event.schedule.toInput();
const meta = plainEvent.schedule.meta;
if (meta)
{
for (const identifier in meta)
{
meta[ identifier ] = plainMeta( meta[ identifier ] );
}
}
out.events.push( plainEvent );
}
else
{
out.events.push( event );
}
}
return out;
}
/**
* Creates a calendar based on the given input.
*
* @param input The input which has at least the `type` specified.
* @returns A new calendar instance.
*/
public static fromInput<T, M>(input: CalendarInput<T, M>): Calendar<T, M>
{
const initial: Day = Day.today();
return new Calendar(initial, initial, null, 1, null, null, input);
}
/**
* Creates a calendar based around a given unit optionally focused around a
* given day.
*
* @param type The unit of the calendar.
* @param days The number of units in the calendar.
* @param around The day to focus the calendar on.
* @param focus The value which describes how months are added around the given
* day. The default value will center the calendar around the given day.
* When the value is `0` the given day is the first day in the calendar,
* and when the value is `1` the given day is the last day in the calendar.
* @param input The default properties for the calendar.
* @returns A new calendar instance.
*/
public static forType<T, M>(type: Units, size: number = 1, around: Day = Day.today(), focus: number = 0.49999, input?: CalendarInput<T, M>): Calendar<T, M>
{
const meta: CalendarTypeDefinition = this.TYPES[ type ];
const start: Day = meta.getStart( around, size, focus );
const end: Day = meta.getEnd( start, size, focus );
return new Calendar<T, M>(start, end, type, size, meta.moveStart, meta.moveEnd, input || meta.defaultInput);
}
/**
* Creates a calendar based around days optionally focused around a given day.
*
* @param days The number of days in the calendar.
* @param around The day to focus the calendar on.
* @param focus The value which describes how days are added around the given
* day. The default value will center the calendar around the given day.
* When the value is `0` the given day is the first day in the calendar,
* and when the value is `1` the given day is the last day in the calendar.
* @param input The default properties for the calendar.
* @returns A new calendar instance.
* @see [[Calendar.forType]]
*/
public static days<T, M>(days: number = 1, around: Day = Day.today(), focus: number = 0.4999, input?: CalendarInput<T, M>): Calendar<T, M>
{
return this.forType( Units.DAY, days, around, focus, input );
}
/**
* Creates a calendar based around weeks optionally focused around a given day.
*
* @param days The number of weeks in the calendar.
* @param around The day to focus the calendar on.
* @param focus The value which describes how weeks are added around the given
* day. The default value will center the calendar around the given day.
* When the value is `0` the given day is the first day in the calendar,
* and when the value is `1` the given day is the last day in the calendar.
* @param input The default properties for the calendar.
* @returns A new calendar instance.
* @see [[Calendar.forType]]
*/
public static weeks<T, M>(weeks: number = 1, around: Day = Day.today(), focus: number = 0.4999, input?: CalendarInput<T, M>): Calendar<T, M>
{
return this.forType( Units.WEEK, weeks, around, focus, input );
}
/**
* Creates a calendar based around months optionally focused around a given day.
*
* @param days The number of months in the calendar.
* @param around The day to focus the calendar on.
* @param focus The value which describes how months are added around the given
* day. The default value will center the calendar around the given day.
* When the value is `0` the given day is the first day in the calendar,
* and when the value is `1` the given day is the last day in the calendar.
* @param input The default properties for the calendar.
* @returns A new calendar instance.
* @see [[Calendar.forType]]
*/
public static months<T, M>(months: number = 1, around: Day = Day.today(), focus: number = 0.4999, input?: CalendarInput<T, M>): Calendar<T, M>
{
return this.forType( Units.MONTH, months, around, focus, input );
}
/**
* Creates a calendar based around years optionally focused around a given day.
*
* @param days The number of years in the calendar.
* @param around The day to focus the calendar on.
* @param focus The value which describes how years are added around the given
* day. The default value will center the calendar around the given day.
* When the value is `0` the given day is the first day in the calendar,
* and when the value is `1` the given day is the last day in the calendar.
* @param input The default properties for the calendar.
* @returns A new calendar instance.
* @see [[Calendar.forType]]
*/
public static years<T, M>(years: number = 1, around: Day = Day.today(), focus: number = 0.4999, input?: CalendarInput<T, M>): Calendar<T, M>
{
return this.forType( Units.YEAR, years, around, focus, input );
}
/**
* A map of functions and properties by [[Units]] used to create or morph
* Calendars.
*/
public static TYPES: CalendarTypeDefinitionMap =
{
[Units.DAY]:
{
getStart(around: Day, size: number, focus: number): Day {
return around.startOf('day').add('day', -Math.floor( size * focus ))
},
getEnd(start: Day, size: number, focus: number): Day {
return start.add('day', size - 1).endOf('day');
},
moveStart(day: Day, amount: number): Day {
return day.add('day', amount);
},
moveEnd(day: Day, amount: number): Day {
return day.add('day', amount);
},
defaultInput: undefined
},
[Units.WEEK]:
{
getStart(around: Day, size: number, focus: number): Day {
return around.startOf('week').add('week', -Math.floor( size * focus ));
},
getEnd(start: Day, size: number, focus: number): Day {
return start.add('week', size - 1).endOf('week');
},
moveStart(day: Day, amount: number): Day {
return day.add('week', amount);
},
moveEnd(day: Day, amount: number): Day {
return day.add('week', amount);
},
defaultInput: undefined
},
[Units.MONTH]:
{
getStart(around: Day, size: number, focus: number): Day {
return around.startOf('month').add('month', -Math.floor( size * focus ) );
},
getEnd(start: Day, size: number, focus: number): Day {
return start.add('month', size - 1).endOf('month');
},
moveStart(day: Day, amount: number): Day {
return day.add('month', amount);
},
moveEnd(day: Day, amount: number): Day {
return day.startOf('month').add('month', amount).endOf('month');
},
defaultInput: { fill: true }
},
[Units.YEAR]:
{
getStart(around: Day, size: number, focus: number): Day {
return around.startOf('year').add('year', -Math.floor( size * focus ));
},
getEnd(start: Day, size: number, focus: number): Day {
return start.add('year', size - 1).endOf('year');
},
moveStart(day: Day, amount: number): Day {
return day.add('year', amount);
},
moveEnd(day: Day, amount: number): Day {
return day.add('year', amount);
},
defaultInput: { fill: true }
}
};
} | the_stack |
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MockPipe } from 'ng-mocks';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { TranslateService } from '@ngx-translate/core';
import { QuizScoringInfoStudentModalComponent } from 'app/exercises/quiz/shared/questions/quiz-scoring-infostudent-modal/quiz-scoring-info-student-modal.component';
import { MockTranslateService } from '../../../helpers/mocks/service/mock-translate.service';
import { MockNgbModalService } from '../../../helpers/mocks/service/mock-ngb-modal.service';
import { ArtemisTestModule } from '../../../test.module';
import { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe';
import { ShortAnswerQuestion } from 'app/entities/quiz/short-answer-question.model';
import { DragAndDropQuestion } from 'app/entities/quiz/drag-and-drop-question.model';
import { ShortAnswerSpot } from 'app/entities/quiz/short-answer-spot.model';
import { ShortAnswerSubmittedText } from 'app/entities/quiz/short-answer-submitted-text.model';
import { MultipleChoiceQuestion } from 'app/entities/quiz/multiple-choice-question.model';
import { AnswerOption } from 'app/entities/quiz/answer-option.model';
import { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';
import { Result } from 'app/entities/result.model';
import { QuizSubmission } from 'app/entities/quiz/quiz-submission.model';
import { SubmittedAnswer } from 'app/entities/quiz/submitted-answer.model';
import { MultipleChoiceSubmittedAnswer } from 'app/entities/quiz/multiple-choice-submitted-answer.model';
describe('Quiz Scoring Info Student Modal Component', () => {
let fixture: ComponentFixture<QuizScoringInfoStudentModalComponent>;
let comp: QuizScoringInfoStudentModalComponent;
let modalService: NgbModal;
let translateService: TranslateService;
let translateSpy: jest.SpyInstance;
const translationBasePath = 'artemisApp.quizExercise.explanationText.';
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ArtemisTestModule],
declarations: [QuizScoringInfoStudentModalComponent, MockPipe(ArtemisTranslatePipe)],
providers: [
{ provide: TranslateService, useClass: MockTranslateService },
{ provide: NgbModal, useClass: MockNgbModalService },
],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(QuizScoringInfoStudentModalComponent);
comp = fixture.componentInstance;
modalService = TestBed.inject(NgbModal);
translateService = TestBed.inject(TranslateService);
translateSpy = jest.spyOn(translateService, 'instant');
comp.question = {} as ShortAnswerQuestion;
});
});
afterEach(() => {
jest.restoreAllMocks();
});
it('should check for singular point singular score', () => {
comp.question.points = 1;
comp.score = 1;
comp.ngAfterViewInit();
expect(translateSpy).toHaveBeenCalledTimes(2);
expect(translateSpy).toHaveBeenNthCalledWith(1, translationBasePath + 'point');
expect(translateSpy).toHaveBeenNthCalledWith(2, translationBasePath + 'point');
});
it('should check for plural points and scores', () => {
comp.question.points = 2;
comp.score = 2;
comp.ngAfterViewInit();
expect(translateSpy).toHaveBeenCalledTimes(2);
expect(translateSpy).toHaveBeenNthCalledWith(1, translationBasePath + 'points');
expect(translateSpy).toHaveBeenNthCalledWith(2, translationBasePath + 'points');
});
it('should open modal', () => {
const content: any = {} as HTMLElement;
const openModalSpy = jest.spyOn(modalService, 'open');
comp.open(content);
expect(openModalSpy).toHaveBeenCalledOnce();
expect(openModalSpy).toHaveBeenCalledWith(content, { size: 'lg' });
});
it('check count for drag and drop exercise with singular values', () => {
comp.question = new DragAndDropQuestion();
comp.correctlyMappedDragAndDropItems = 1;
comp.incorrectlyMappedDragAndDropItems = 1;
comp.ngAfterViewInit();
expect(comp.differenceDragAndDrop).toBe(0);
expect(translateSpy).toHaveBeenCalledTimes(4);
expect(translateSpy).toHaveBeenNthCalledWith(3, translationBasePath + 'item');
expect(translateSpy).toHaveBeenNthCalledWith(4, translationBasePath + 'item');
});
it('check count for drag and drop exercise with plural values', () => {
comp.question = new DragAndDropQuestion();
comp.correctlyMappedDragAndDropItems = 5;
comp.incorrectlyMappedDragAndDropItems = 2;
comp.ngAfterViewInit();
expect(comp.differenceDragAndDrop).toBe(3);
expect(translateSpy).toHaveBeenCalledTimes(4);
expect(translateSpy).toHaveBeenNthCalledWith(3, translationBasePath + 'items');
expect(translateSpy).toHaveBeenNthCalledWith(4, translationBasePath + 'items');
});
it('check count for short answer exercise with singular values', () => {
const question = new ShortAnswerQuestion();
question.spots = [new ShortAnswerSpot(), new ShortAnswerSpot()];
comp.question = question;
const shortAnswerText1 = new ShortAnswerSubmittedText();
shortAnswerText1.isCorrect = true;
const shortAnswerText2 = new ShortAnswerSubmittedText();
shortAnswerText2.isCorrect = false;
comp.shortAnswerText = [shortAnswerText1, shortAnswerText2];
comp.ngAfterViewInit();
expect(comp.shortAnswerSpots).toBe(2);
expect(comp.shortAnswerCorrectAnswers).toBe(1);
expect(comp.shortAnswerWrongAnswers).toBe(1);
expect(comp.differenceShortAnswer).toBe(0);
expect(translateSpy).toHaveBeenCalledTimes(4);
expect(translateSpy).toHaveBeenNthCalledWith(3, translationBasePath + 'textgap');
expect(translateSpy).toHaveBeenNthCalledWith(4, translationBasePath + 'textgap');
});
it('check count for short answer exercise with plural values', () => {
const question = new ShortAnswerQuestion();
question.spots = [new ShortAnswerSpot(), new ShortAnswerSpot(), new ShortAnswerSpot(), new ShortAnswerSpot()];
comp.question = question;
const shortAnswerText1 = new ShortAnswerSubmittedText();
shortAnswerText1.isCorrect = true;
const shortAnswerText2 = new ShortAnswerSubmittedText();
shortAnswerText2.isCorrect = true;
const shortAnswerText3 = new ShortAnswerSubmittedText();
shortAnswerText3.isCorrect = false;
const shortAnswerText4 = new ShortAnswerSubmittedText();
shortAnswerText4.isCorrect = false;
comp.shortAnswerText = [shortAnswerText1, shortAnswerText2, shortAnswerText3, shortAnswerText4];
comp.ngAfterViewInit();
expect(comp.shortAnswerSpots).toBe(4);
expect(comp.shortAnswerCorrectAnswers).toBe(2);
expect(comp.shortAnswerWrongAnswers).toBe(2);
expect(comp.differenceShortAnswer).toBe(0);
expect(translateSpy).toHaveBeenCalledTimes(4);
expect(translateSpy).toHaveBeenNthCalledWith(3, translationBasePath + 'textgaps');
expect(translateSpy).toHaveBeenNthCalledWith(4, translationBasePath + 'textgaps');
});
describe('Check values for multiple choice exercise', () => {
let question: MultipleChoiceQuestion;
let submittedAnswers: SubmittedAnswer[];
beforeEach(() => {
// multiple choice question with 2 answers
// submission with one correct answer and one wrong answer
question = new MultipleChoiceQuestion();
const correctAnswer1 = new AnswerOption();
correctAnswer1.id = 1;
correctAnswer1.isCorrect = true;
const wrongAnswer1 = new AnswerOption();
wrongAnswer1.id = 2;
wrongAnswer1.isCorrect = false;
question.answerOptions = [correctAnswer1, wrongAnswer1];
comp.question = question;
const submittedExercise = new QuizExercise(undefined, undefined);
submittedExercise.quizQuestions = [question];
comp.submittedQuizExercise = submittedExercise;
const submittedResult = new Result();
comp.multipleChoiceSubmittedResult = submittedResult;
const submission = new QuizSubmission();
submittedResult.submission = submission;
const correctSubmittedAnswer = new MultipleChoiceSubmittedAnswer();
correctSubmittedAnswer.quizQuestion = question;
const correctSelectedOption = new AnswerOption();
correctSelectedOption.id = 1;
correctSelectedOption.isCorrect = true;
correctSubmittedAnswer.selectedOptions = [correctSelectedOption];
const wrongSubmittedAnswer = new MultipleChoiceSubmittedAnswer();
wrongSubmittedAnswer.quizQuestion = question;
const wrongSelectedOption = new AnswerOption();
wrongSelectedOption.id = 2;
wrongSelectedOption.isCorrect = false;
wrongSubmittedAnswer.selectedOptions = [wrongSelectedOption];
submittedAnswers = [correctSubmittedAnswer, wrongSubmittedAnswer];
submission.submittedAnswers = submittedAnswers;
submittedResult.submission = submission;
});
it('check count for multiple choice exercise with singular values', () => {
comp.ngAfterViewInit();
expect(comp.multipleChoiceAnswerOptions).toBe(2);
expect(comp.multipleChoiceCorrectAnswerCorrectlyChosen).toBe(1);
expect(comp.multipleChoiceWrongAnswerChosen).toBe(1);
expect(comp.forgottenMultipleChoiceRightAnswers).toBe(0);
expect(comp.inTotalSelectedRightOptions).toBe(1);
expect(comp.forgottenMultipleChoiceRightAnswers).toBe(0);
expect(comp.inTotalSelectedWrongOptions).toBe(1);
expect(translateSpy).toHaveBeenCalledTimes(4);
expect(translateSpy).toHaveBeenNthCalledWith(3, translationBasePath + 'option');
expect(translateSpy).toHaveBeenNthCalledWith(4, translationBasePath + 'option');
});
it('check count for multiple choice exercise with plural values', () => {
// add one wrong and one correct answer to the exercise
const correctAnswer2 = new AnswerOption();
correctAnswer2.id = 3;
correctAnswer2.isCorrect = true;
const wrongAnswer2 = new AnswerOption();
wrongAnswer2.id = 4;
wrongAnswer2.isCorrect = false;
question.answerOptions!.push(correctAnswer2, wrongAnswer2);
const correctSubmittedAnswer2 = new MultipleChoiceSubmittedAnswer();
correctSubmittedAnswer2.quizQuestion = question;
const correctSelectedOption2 = new AnswerOption();
correctSelectedOption2.id = 3;
correctSelectedOption2.isCorrect = true;
correctSubmittedAnswer2.selectedOptions = [correctSelectedOption2];
const wrongSubmittedAnswer2 = new MultipleChoiceSubmittedAnswer();
wrongSubmittedAnswer2.quizQuestion = question;
const wrongSelectedOption2 = new AnswerOption();
wrongSelectedOption2.id = 4;
wrongSelectedOption2.isCorrect = false;
wrongSubmittedAnswer2.selectedOptions = [wrongSelectedOption2];
submittedAnswers.push(correctSubmittedAnswer2, wrongSubmittedAnswer2);
comp.ngAfterViewInit();
expect(comp.multipleChoiceAnswerOptions).toBe(4);
expect(comp.multipleChoiceCorrectAnswerCorrectlyChosen).toBe(2);
expect(comp.multipleChoiceWrongAnswerChosen).toBe(2);
expect(comp.forgottenMultipleChoiceRightAnswers).toBe(0);
expect(comp.inTotalSelectedRightOptions).toBe(2);
expect(comp.forgottenMultipleChoiceRightAnswers).toBe(0);
expect(comp.inTotalSelectedWrongOptions).toBe(2);
expect(translateSpy).toHaveBeenCalledTimes(4);
expect(translateSpy).toHaveBeenNthCalledWith(3, translationBasePath + 'options');
expect(translateSpy).toHaveBeenNthCalledWith(4, translationBasePath + 'options');
});
});
}); | the_stack |
import { configure, mount, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import * as React from 'react';
import renderer from 'react-test-renderer';
import MDPicker from '../index';
configure({ adapter: new Adapter() });
beforeEach(() => {
jest.useFakeTimers();
});
it('renders correctly with defaults', () => {
const component = renderer
.create(
<MDPicker
data={Sample}
cols={1}
isView={true}
pickerHeight={200}
pickerWidth={350}
defaultIndex={[0]}
invalidIndex={[[4, 2, 3]]}
onChange={(columnIndex: number, itemIndex: number, value: any) => {}}
/>
)
.toJSON();
expect(component).toMatchSnapshot();
});
it('renders correctly with not icon', () => {
const component = renderer
.create(
<MDPicker
data={Sample}
cols={3}
isView={true}
isCascade={true}
pickerHeight={200}
pickerWidth={350}
itemHeight={40}
invalidIndex={[[1], [3], [3]]}
// defaultIndex={[1, 0, 1]}
defaultValue={['北京', '北京', '朝阳区']}
/>
)
.toJSON();
expect(component).toMatchSnapshot();
});
it('renders correctly with tab', () => {
const component = renderer
.create(
<MDPicker
data={Sample}
cols={3}
isView={false}
isCascade={true}
pickerHeight={200}
pickerWidth={350}
itemHeight={40}
defaultIndex={[1, 0, 1]}
title='选择省市区/县'
onConfirm={(activeValues: any) => {
// this.updateText(activeValues);
}}
onCancel={() => {}}
onShow={() => {}}
onHide={() => {}}
isVisible={true}
/>
)
.toJSON();
expect(component).toMatchSnapshot();
});
it('renders correctly with tab action', () => {
const mockFn = jest.fn(() => {
console.log('------aaa----fn(1)');
});
const component = shallow(
<MDPicker
data={Sample}
cols={3}
isView={false}
isCascade={true}
pickerHeight={200}
pickerWidth={350}
itemHeight={40}
defaultIndex={[1, 0, 1]}
title='选择省市区/县'
onConfirm={mockFn}
onCancel={mockFn}
onShow={mockFn}
onHide={mockFn}
isVisible={true}
/>
);
// component.setProps({ isVisible: false });
// component.setProps({ isVisible: true });
const titleBar = component.find('MDPopupTitleBar');
const barComponent = titleBar.shallow();
barComponent.find('TouchableWithoutFeedback').forEach((btn: any) => {
btn.simulate('press');
});
expect(mockFn).toBeCalledTimes(2);
// expect(mockFn).toHaveBeenCalled();
});
it('renders correctly with not icon', () => {
const mockFn = jest.fn(() => {
console.log('------aaa----fn(2)');
});
const component = renderer.create(
<MDPicker
ref={(e) => {
// @ts-ignore
this._picker = e;
}}
data={Sample}
cols={3}
isView={true}
isCascade={true}
pickerHeight={200}
pickerWidth={350}
itemHeight={40}
invalidIndex={[[1], [3], [3]]}
defaultIndex={[1, 0, 1]}
// defaultValue={['北京', '北京', '朝阳区']}
/>
);
// @ts-ignore
const picker = this._picker;
expect(picker.getCurIndexs().length).toBe(3);
expect(picker.getCurValues().length).toBe(3);
expect(picker.getColumnValue(1).label).toBe('北海市');
expect(picker.getColumnValues().length).toBe(3);
expect(picker.getColumnIndex(1)).toBe(0);
expect(picker.getColumnIndexs().length).toBe(3);
picker.setColumnValues(
1,
[{ text: 'aa' }, { text: 'bb' }, { text: 'cc' }],
mockFn
);
expect(mockFn).toBeCalled();
picker.refresh(mockFn);
expect(mockFn).toBeCalledTimes(2);
});
const Sample = [
[
{
value: '110000',
label: '北京',
children: [
{
value: '110100',
label: '北京市',
children: [
{
value: '110114',
label: '昌平区',
children: [],
},
{
value: '110105',
label: '朝阳区',
children: [],
},
{
value: '110103',
label: '崇文区',
children: [],
},
{
value: '110115',
label: '大兴区',
children: [],
},
{
value: '110101',
label: '东城区',
children: [],
},
{
value: '110111',
label: '房山区',
children: [],
},
{
value: '110106',
label: '丰台区',
children: [],
},
{
value: '110108',
label: '海淀区',
children: [],
},
{
value: '110116',
label: '怀柔区',
children: [],
},
{
value: '110109',
label: '门头沟区',
children: [],
},
{
value: '110228',
label: '密云县',
children: [],
},
{
value: '110117',
label: '平谷区',
children: [],
},
{
value: '110230',
label: '其它区',
children: [],
},
{
value: '110107',
label: '石景山区',
children: [],
},
{
value: '110113',
label: '顺义区',
children: [],
},
{
value: '110112',
label: '通州区',
children: [],
},
{
value: '110102',
label: '西城区',
children: [],
},
{
value: '110104',
label: '宣武区',
children: [],
},
{
value: '110229',
label: '延庆县',
children: [],
},
],
},
],
},
{
value: '450000',
label: '广西壮族自治区',
children: [
{
value: '450500',
label: '北海市',
children: [
{
value: '450502',
label: '海城区',
children: [],
},
{
value: '450521',
label: '合浦县',
children: [],
},
{
value: '450522',
label: '其它区',
children: [],
},
{
value: '450512',
label: '铁山港区',
children: [],
},
{
value: '450503',
label: '银海区',
children: [],
},
],
},
{
value: '451000',
label: '百色市',
children: [
{
value: '451024',
label: '德保县',
children: [],
},
{
value: '451025',
label: '靖西县',
children: [],
},
{
value: '451028',
label: '乐业县',
children: [],
},
{
value: '451027',
label: '凌云县',
children: [],
},
{
value: '451031',
label: '隆林各族自治县',
children: [],
},
{
value: '451026',
label: '那坡县',
children: [],
},
{
value: '451023',
label: '平果县',
children: [],
},
{
value: '451032',
label: '其它区',
children: [],
},
{
value: '451022',
label: '田东县',
children: [],
},
{
value: '451029',
label: '田林县',
children: [],
},
{
value: '451021',
label: '田阳县',
children: [],
},
{
value: '451030',
label: '西林县',
children: [],
},
{
value: '451002',
label: '右江区',
children: [],
},
],
},
{
value: '451400',
label: '崇左市',
children: [
{
value: '451424',
label: '大新县',
children: [],
},
{
value: '451421',
label: '扶绥县',
children: [],
},
{
value: '451402',
label: '江州区',
children: [],
},
{
value: '451423',
label: '龙州县',
children: [],
},
{
value: '451422',
label: '宁明县',
children: [],
},
{
value: '451481',
label: '凭祥市',
children: [],
},
{
value: '451482',
label: '其它区',
children: [],
},
{
value: '451425',
label: '天等县',
children: [],
},
],
},
{
value: '450600',
label: '防城港市',
children: [
{
value: '450681',
label: '东兴市',
children: [],
},
{
value: '450603',
label: '防城区',
children: [],
},
{
value: '450602',
label: '港口区',
children: [],
},
{
value: '450682',
label: '其它区',
children: [],
},
{
value: '450621',
label: '上思县',
children: [],
},
],
},
{
value: '450800',
label: '贵港市',
children: [
{
value: '450802',
label: '港北区',
children: [],
},
{
value: '450803',
label: '港南区',
children: [],
},
{
value: '450881',
label: '桂平市',
children: [],
},
{
value: '450821',
label: '平南县',
children: [],
},
{
value: '450882',
label: '其它区',
children: [],
},
{
value: '450804',
label: '覃塘区',
children: [],
},
],
},
{
value: '450300',
label: '桂林市',
children: [
{
value: '450303',
label: '叠彩区',
children: [],
},
{
value: '450332',
label: '恭城瑶族自治县',
children: [],
},
{
value: '450327',
label: '灌阳县',
children: [],
},
{
value: '450331',
label: '荔浦县',
children: [],
},
{
value: '450322',
label: '临桂区',
children: [],
},
{
value: '450323',
label: '灵川县',
children: [],
},
{
value: '450328',
label: '龙胜各族自治县',
children: [],
},
{
value: '450330',
label: '平乐县',
children: [],
},
{
value: '450333',
label: '其它区',
children: [],
},
{
value: '450305',
label: '七星区',
children: [],
},
{
value: '450324',
label: '全州县',
children: [],
},
{
value: '450304',
label: '象山区',
children: [],
},
{
value: '450325',
label: '兴安县',
children: [],
},
{
value: '450302',
label: '秀峰区',
children: [],
},
{
value: '450311',
label: '雁山区',
children: [],
},
{
value: '450321',
label: '阳朔县',
children: [],
},
{
value: '450326',
label: '永福县',
children: [],
},
{
value: '450329',
label: '资源县',
children: [],
},
],
},
{
value: '451200',
label: '河池市',
children: [
{
value: '451227',
label: '巴马瑶族自治县',
children: [],
},
{
value: '451229',
label: '大化瑶族自治县',
children: [],
},
{
value: '451224',
label: '东兰县',
children: [],
},
{
value: '451228',
label: '都安瑶族自治县',
children: [],
},
{
value: '451223',
label: '凤山县',
children: [],
},
{
value: '451226',
label: '环江毛南族自治县',
children: [],
},
{
value: '451202',
label: '金城江区',
children: [],
},
{
value: '451225',
label: '罗城仫佬族自治县',
children: [],
},
{
value: '451221',
label: '南丹县',
children: [],
},
{
value: '451282',
label: '其它区',
children: [],
},
{
value: '451222',
label: '天峨县',
children: [],
},
{
value: '451281',
label: '宜州市',
children: [],
},
],
},
{
value: '451100',
label: '贺州市',
children: [
{
value: '451102',
label: '八步区',
children: [],
},
{
value: '451123',
label: '富川瑶族自治县',
children: [],
},
{
value: '451119',
label: '平桂管理区',
children: [],
},
{
value: '451124',
label: '其它区',
children: [],
},
{
value: '451121',
label: '昭平县',
children: [],
},
{
value: '451122',
label: '钟山县',
children: [],
},
],
},
{
value: '451300',
label: '来宾市',
children: [
{
value: '451381',
label: '合山市',
children: [],
},
{
value: '451324',
label: '金秀瑶族自治县',
children: [],
},
{
value: '451382',
label: '其它区',
children: [],
},
{
value: '451323',
label: '武宣县',
children: [],
},
{
value: '451322',
label: '象州县',
children: [],
},
{
value: '451321',
label: '忻城县',
children: [],
},
{
value: '451302',
label: '兴宾区',
children: [],
},
],
},
{
value: '450200',
label: '柳州市',
children: [
{
value: '450202',
label: '城中区',
children: [],
},
{
value: '450205',
label: '柳北区',
children: [],
},
{
value: '450222',
label: '柳城县',
children: [],
},
{
value: '450221',
label: '柳江县',
children: [],
},
{
value: '450204',
label: '柳南区',
children: [],
},
{
value: '450223',
label: '鹿寨县',
children: [],
},
{
value: '450227',
label: '其它区',
children: [],
},
{
value: '450224',
label: '融安县',
children: [],
},
{
value: '450225',
label: '融水苗族自治县',
children: [],
},
{
value: '450226',
label: '三江侗族自治县',
children: [],
},
{
value: '450203',
label: '鱼峰区',
children: [],
},
],
},
{
value: '450100',
label: '南宁市',
children: [
{
value: '450126',
label: '宾阳县',
children: [],
},
{
value: '450127',
label: '横县',
children: [],
},
{
value: '450105',
label: '江南区',
children: [],
},
{
value: '450108',
label: '良庆区',
children: [],
},
{
value: '450123',
label: '隆安县',
children: [],
},
{
value: '450124',
label: '马山县',
children: [],
},
{
value: '450128',
label: '其它区',
children: [],
},
{
value: '450103',
label: '青秀区',
children: [],
},
{
value: '450125',
label: '上林县',
children: [],
},
{
value: '450122',
label: '武鸣区',
children: [],
},
{
value: '450107',
label: '西乡塘区',
children: [],
},
{
value: '450102',
label: '兴宁区',
children: [],
},
{
value: '450109',
label: '邕宁区',
children: [],
},
],
},
{
value: '450700',
label: '钦州市',
children: [
{
value: '450721',
label: '灵山县',
children: [],
},
{
value: '450722',
label: '浦北县',
children: [],
},
{
value: '450723',
label: '其它区',
children: [],
},
{
value: '450703',
label: '钦北区',
children: [],
},
{
value: '450702',
label: '钦南区',
children: [],
},
],
},
{
value: '450400',
label: '梧州市',
children: [
{
value: '450421',
label: '苍梧县',
children: [],
},
{
value: '450481',
label: '岑溪市',
children: [],
},
{
value: '450405',
label: '长洲区',
children: [],
},
{
value: '450404',
label: '蝶山区',
children: [],
},
{
value: '450406',
label: '龙圩区',
children: [],
},
{
value: '450423',
label: '蒙山县',
children: [],
},
{
value: '450482',
label: '其它区',
children: [],
},
{
value: '450422',
label: '藤县',
children: [],
},
{
value: '450403',
label: '万秀区',
children: [],
},
],
},
{
value: '450900',
label: '玉林市',
children: [
{
value: '450981',
label: '北流市',
children: [],
},
{
value: '450923',
label: '博白县',
children: [],
},
{
value: '450903',
label: '福绵区',
children: [],
},
{
value: '450922',
label: '陆川县',
children: [],
},
{
value: '450982',
label: '其它区',
children: [],
},
{
value: '450921',
label: '容县',
children: [],
},
{
value: '450924',
label: '兴业县',
children: [],
},
{
value: '450902',
label: '玉州区',
children: [],
},
],
},
],
},
],
]; | the_stack |
import { stripIndent } from "common-tags";
import { fromFixture } from "eslint-etc";
import rule = require("../../source/rules/suffix-subjects");
import { ruleTester } from "../utils";
ruleTester({ types: true }).run("suffix-subjects", rule, {
valid: [
{
code: stripIndent`
// with default suffix
import { Subject } from "rxjs";
const subject = new Subject<any>();
const someSubject = new Subject<any>();
const someObject = {
subject: new Subject<any>(),
someSubject: new Subject<any>()
};
function someFunction(
subject: Subject<any>,
someSubject: Subject<any>
) {
console.log(subject, someSubject);
}
class SomeClass {
subject = new Subject<any>();
someSubject = new Subject<void>();
constructor(private ctorSubject: Subject<any>) {}
someMethod(someSubject: Subject<any>): Subject<any> {
return someSubject;
}
get anotherSubject(): Subject<any> {
return this.subject;
}
set anotherSubject(someSubject: Subject<any>) {
this.someSubject = someSubject;
}
}
interface SomeInterface {
subject: Subject<any>;
someSubject: Subject<any>;
someMethod(someSubject: Subject<any>): Subject<any>;
new (someSubject: Subject<any>);
(someSubject: Subject<any>): void;
}
`,
options: [{}],
},
{
code: stripIndent`
// with default suffix and $
import { Subject } from "rxjs";
const subject$ = new Subject<any>();
const someSubject$ = new Subject<any>();
const someObject = {
subject$: new Subject<any>(),
someSubject$: new Subject<any>()
};
function someFunction(
subject$: Subject<any>,
someSubject$: Subject<any>
) {
console.log(subject$, someSubject$);
}
class SomeClass {
subject$ = new Subject<any>();
someSubject$ = new Subject<void>();
constructor(private ctorSubject$: Subject<any>) {}
someMethod(someSubject$: Subject<any>): Subject<any> {
return someSubject$;
}
get anotherSubject$(): Subject<any> {
return this.subject$;
}
set anotherSubject$(someSubject$: Subject<any>) {
this.someSubject$ = someSubject$;
}
}
interface SomeInterface {
subject$: Subject<any>;
someSubject$: Subject<any>;
someMethod(someSubject$: Subject<any>): Subject<any>;
new (someSubject$: Subject<any>);
(someSubject$: Subject<any>): void;
}
`,
options: [{}],
},
{
code: stripIndent`
// with explicit suffix
import { Subject } from "rxjs";
const sub = new Subject<any>();
const someSub = new Subject<any>();
const someObject = {
sub: new Subject<any>(),
someSub: new Subject<any>()
};
function someFunction(
sub: Subject<any>,
someSub: Subject<any>
) {
console.log(sub, someSub);
}
class SomeClass {
sub = new Subject<any>();
someSub = new Subject<void>();
constructor(private ctorSub: Subject<any>) {}
someMethod(someSub: Subject<any>): Subject<any> {
return someSub;
}
get anotherSub(): Subject<any> {
return this.sub;
}
set anotherSub(someSub: Subject<any>) {
this.someSub = someSub;
}
}
interface SomeInterface {
sub: Subject<any>;
someSub: Subject<any>;
someMethod(someSub: Subject<any>): Subject<any>;
new (someSub: Subject<any>);
(someSub: Subject<any>): void;
}
`,
options: [{ suffix: "Sub" }],
},
{
code: stripIndent`
// with explicit suffix and $
import { Subject } from "rxjs";
const sub$ = new Subject<any>();
const someSub$ = new Subject<any>();
const someObject = {
sub$: new Subject<any>(),
someSub$: new Subject<any>()
};
function someFunction(
sub$: Subject<any>,
someSub$: Subject<any>
) {
console.log(sub$, someSub$);
}
class SomeClass {
sub$ = new Subject<any>();
someSub$ = new Subject<void>();
constructor(private ctorSub$: Subject<any>) {}
someMethod(someSub$: Subject<any>): Subject<any> {
return someSub$;
}
get anotherSub$(): Subject<any> {
return this.sub$;
}
set anotherSub$(someSub$: Subject<any>) {
this.someSub$ = someSub$;
}
}
interface SomeInterface {
sub$: Subject<any>;
someSub$: Subject<any>;
someMethod(someSub$: Subject<any>): Subject<any>;
new (someSub$: Subject<any>);
(someSub$: Subject<any>): void;
}
`,
options: [{ suffix: "Sub" }],
},
{
code: stripIndent`
// with EventEmitter
import { Subject } from "rxjs";
class EventEmitter<T> extends Subject<T> {}
const emitter = new EventEmitter<any>();
`,
options: [{}],
},
{
code: stripIndent`
// with explicit non-enforced type
import { Subject } from "rxjs";
class Thing<T> extends Subject<T> {}
const thing = new Thing<any>();
`,
options: [
{
types: {
"^Thing$": false,
},
},
],
},
{
code: stripIndent`
// https://github.com/cartant/rxjs-tslint-rules/issues/88
import { RouterStateSerializer } from '@ngrx/router-store';
import { Params, RouterStateSnapshot } from '@angular/router';
/**
* The RouterStateSerializer takes the current RouterStateSnapshot
* and returns any pertinent information needed. The snapshot contains
* all information about the state of the router at the given point in time.
* The entire snapshot is complex and not always needed. In this case, you only
* need the URL and query parameters from the snapshot in the store. Other items could be
* returned such as route parameters and static route data.
*/
export interface RouterStateUrl {
url: string;
queryParams: Params;
}
export class CustomRouterStateSerializer implements RouterStateSerializer<RouterStateUrl> {
serialize(routerState: RouterStateSnapshot): RouterStateUrl {
const { url } = routerState;
const queryParams = routerState.root.queryParams;
return { url, queryParams };
}
}
`,
},
{
code: stripIndent`
// variables without suffix, but not enforced
import { Subject } from "rxjs";
const one = new Subject<any>();
const some = new Subject<any>();
`,
options: [{ variables: false }],
},
],
invalid: [
fromFixture(
stripIndent`
// parameters without suffix
import { Subject } from "rxjs";
function someFunction(
one: Subject<any>,
~~~ [forbidden { "suffix": "Subject" }]
some: Subject<any>
~~~~ [forbidden { "suffix": "Subject" }]
) {
console.log(one, some);
}
class SomeClass {
constructor(ctor: Subject<any>) {}
~~~~ [forbidden { "suffix": "Subject" }]
someMethod(some: Subject<any>): Subject<any> {
~~~~ [forbidden { "suffix": "Subject" }]
return some;
}
get another(): Subject<any> {
~~~~~~~ [forbidden { "suffix": "Subject" }]
return this.ctor;
}
set another(some: Subject<any>) {
~~~~~~~ [forbidden { "suffix": "Subject" }]
~~~~ [forbidden { "suffix": "Subject" }]
this.ctor = some;
}
}
interface SomeInterface {
someMethod(some: Subject<any>): Subject<any>;
~~~~ [forbidden { "suffix": "Subject" }]
new (some: Subject<any>);
~~~~ [forbidden { "suffix": "Subject" }]
(some: Subject<any>): void;
~~~~ [forbidden { "suffix": "Subject" }]
}
`
),
fromFixture(
stripIndent`
// parameters without suffix, but not enforced
import { Subject } from "rxjs";
function someFunction(
one: Subject<any>,
some: Subject<any>
) {
console.log(one, some);
}
class SomeClass {
constructor(ctor: Subject<any>) {}
someMethod(some: Subject<any>): Subject<any> {
return some;
}
get another(): Subject<any> {
~~~~~~~ [forbidden { "suffix": "Subject" }]
return this.ctor;
}
set another(some: Subject<any>) {
~~~~~~~ [forbidden { "suffix": "Subject" }]
this.ctor = some;
}
}
interface SomeInterface {
someMethod(some: Subject<any>): Subject<any>;
new (some: Subject<any>);
(some: Subject<any>): void;
}
`,
{ options: [{ parameters: false }] }
),
fromFixture(
stripIndent`
// parameters without explicit suffix
import { Subject } from "rxjs";
function someFunction(
one: Subject<any>,
~~~ [forbidden { "suffix": "Sub" }]
some: Subject<any>
~~~~ [forbidden { "suffix": "Sub" }]
) {
console.log(one, some);
}
class SomeClass {
constructor(ctor: Subject<any>) {}
~~~~ [forbidden { "suffix": "Sub" }]
someMethod(some: Subject<any>): Subject<any> {
~~~~ [forbidden { "suffix": "Sub" }]
return some;
}
get another(): Subject<any> {
~~~~~~~ [forbidden { "suffix": "Sub" }]
return this.ctor;
}
set another(some: Subject<any>) {
~~~~~~~ [forbidden { "suffix": "Sub" }]
~~~~ [forbidden { "suffix": "Sub" }]
this.ctor = some;
}
}
interface SomeInterface {
someMethod(some: Subject<any>): Subject<any>;
~~~~ [forbidden { "suffix": "Sub" }]
new (some: Subject<any>);
~~~~ [forbidden { "suffix": "Sub" }]
(some: Subject<any>): void;
~~~~ [forbidden { "suffix": "Sub" }]
}
`,
{ options: [{ suffix: "Sub" }] }
),
fromFixture(
stripIndent`
// properties without suffix
import { Subject } from "rxjs";
const someObject = {
one: new Subject<any>(),
~~~ [forbidden { "suffix": "Subject" }]
some: new Subject<any>()
~~~~ [forbidden { "suffix": "Subject" }]
};
class SomeClass {
one = new Subject<any>();
~~~ [forbidden { "suffix": "Subject" }]
some = new Subject<void>();
~~~~ [forbidden { "suffix": "Subject" }]
get another(): Subject<any> {
~~~~~~~ [forbidden { "suffix": "Subject" }]
return this.subject;
}
set another(some: Subject<any>) {
~~~~~~~ [forbidden { "suffix": "Subject" }]
~~~~ [forbidden { "suffix": "Subject" }]
this.some = some;
}
}
interface SomeInterface {
one: Subject<any>;
~~~ [forbidden { "suffix": "Subject" }]
some: Subject<any>;
~~~~ [forbidden { "suffix": "Subject" }]
}
`
),
fromFixture(
stripIndent`
// properties without suffix, but not enforced
import { Subject } from "rxjs";
const someObject = {
one: new Subject<any>(),
some: new Subject<any>()
};
class SomeClass {
one = new Subject<any>();
some = new Subject<void>();
get another(): Subject<any> {
return this.subject;
}
set another(some: Subject<any>) {
~~~~ [forbidden { "suffix": "Subject" }]
this.some = some;
}
}
interface SomeInterface {
one: Subject<any>;
some: Subject<any>;
}
`,
{ options: [{ properties: false }] }
),
fromFixture(
stripIndent`
// properties without explicit suffix
import { Subject } from "rxjs";
const someObject = {
one: new Subject<any>(),
~~~ [forbidden { "suffix": "Sub" }]
some: new Subject<any>()
~~~~ [forbidden { "suffix": "Sub" }]
};
class SomeClass {
one = new Subject<any>();
~~~ [forbidden { "suffix": "Sub" }]
some = new Subject<void>();
~~~~ [forbidden { "suffix": "Sub" }]
get another(): Subject<any> {
~~~~~~~ [forbidden { "suffix": "Sub" }]
return this.subject;
}
set another(some: Subject<any>) {
~~~~~~~ [forbidden { "suffix": "Sub" }]
~~~~ [forbidden { "suffix": "Sub" }]
this.some = some;
}
}
interface SomeInterface {
one: Subject<any>;
~~~ [forbidden { "suffix": "Sub" }]
some: Subject<any>;
~~~~ [forbidden { "suffix": "Sub" }]
}
`,
{ options: [{ suffix: "Sub" }] }
),
fromFixture(
stripIndent`
// variables without suffix
import { Subject } from "rxjs";
const one = new Subject<any>();
~~~ [forbidden { "suffix": "Subject" }]
const some = new Subject<any>();
~~~~ [forbidden { "suffix": "Subject" }]
`
),
fromFixture(
stripIndent`
// variables without explicit suffix
import { Subject } from "rxjs";
const one = new Subject<any>();
~~~ [forbidden { "suffix": "Sub" }]
const some = new Subject<any>();
~~~~ [forbidden { "suffix": "Sub" }]
`,
{ options: [{ suffix: "Sub" }] }
),
fromFixture(
stripIndent`
// functions and methods with array destructuring
import { Subject } from "rxjs";
function someFunction([someParam]: Subject<any>[]): void {}
~~~~~~~~~ [forbidden { "suffix": "Subject" }]
class SomeClass {
someMethod([someParam]: Subject<any>[]): void {}
~~~~~~~~~ [forbidden { "suffix": "Subject" }]
}
`
),
fromFixture(
stripIndent`
// functions and methods with object destructuring
import { Subject } from "rxjs";
function someFunction({ source }: Record<string, Subject<any>>): void {}
~~~~~~ [forbidden { "suffix": "Subject" }]
class SomeClass {
someMethod({ source }: Record<string, Subject<any>>): void {}
~~~~~~ [forbidden { "suffix": "Subject" }]
}
`
),
fromFixture(
stripIndent`
// parameter property
import { Subject } from "rxjs";
class SomeClass {
constructor(public some: Subject<any>) {}
~~~~ [forbidden { "suffix": "Subject" }]
}
`
),
],
}); | the_stack |
import { WebApiTeam } from 'TFS/Core/Contracts';
import * as Calendar_Contracts from '../Contracts';
import * as Calendar_DateUtils from '../Utils/Date';
import { realPromise } from "../Utils/Promise";
import * as Capacity_Enhancer from '../Enhancers/VSOCapacityEnhancer';
import * as Culture from 'VSS/Utils/Culture';
import * as Service from 'VSS/Service';
import * as TFS_Core_Contracts from 'TFS/Core/Contracts';
import * as Utils_Date from 'VSS/Utils/Date';
import * as Utils_String from 'VSS/Utils/String';
import * as WebApi_Constants from 'VSS/WebApi/Constants';
import * as Work_Client from 'TFS/Work/RestClient';
import * as Work_Contracts from 'TFS/Work/Contracts';
export class VSOCapacityEventSource implements Calendar_Contracts.IEventSource {
public id = "daysOff";
public name = "Days off";
public order = 30;
private _enhancer: Capacity_Enhancer.VSOCapacityEnhancer;
private _events: Calendar_Contracts.CalendarEvent[];
private _renderedEvents: Calendar_Contracts.CalendarEvent[];
private _categoryColor: string = "transparent";
private _team: WebApiTeam;
constructor(context?: any) {
this.updateTeamContext(context.team);
}
public updateTeamContext(newTeam: WebApiTeam) {
this._team = newTeam;
}
public load(): PromiseLike<Calendar_Contracts.CalendarEvent[]> {
return this.getEvents().then((events: Calendar_Contracts.CalendarEvent[]) => {
for (const event of events) {
const start = Utils_Date.shiftToUTC(new Date(event.startDate));
const end = Utils_Date.shiftToUTC(new Date(event.endDate));
if (start.getHours() !== 0) {
// Set dates back to midnight
start.setHours(0);
end.setHours(0);
// update the event in the list
const newEvent = $.extend({}, event);
newEvent.startDate = Utils_Date.shiftToLocal(start).toISOString();
newEvent.endDate = Utils_Date.shiftToLocal(end).toISOString();
const eventInArray: Calendar_Contracts.CalendarEvent = $.grep(events, function(
e: Calendar_Contracts.CalendarEvent,
) {
return e.id === newEvent.id;
})[0];
const index = events.indexOf(eventInArray);
if (index > -1) {
events.splice(index, 1);
}
events.push(newEvent);
// Update event
this.updateEvent(event, newEvent);
}
}
return events;
});
}
public getEnhancer(): PromiseLike<Calendar_Contracts.IEventEnhancer> {
if (!this._enhancer) {
this._enhancer = new Capacity_Enhancer.VSOCapacityEnhancer();
}
return Promise.resolve(this._enhancer);
}
public getEvents(query?: Calendar_Contracts.IEventQuery): PromiseLike<Calendar_Contracts.CalendarEvent[]> {
const capacityPromises: PromiseLike<Work_Contracts.TeamMemberCapacity[]>[] = [];
const iterationTeamDaysOffPromises: PromiseLike<Work_Contracts.TeamSettingsDaysOff>[] = [];
const eventMap: { [dateString: string]: Calendar_Contracts.CalendarEvent } = {};
this._events = null;
this._renderedEvents = null;
const events: Calendar_Contracts.CalendarEvent[] = [];
const renderedEvents: Calendar_Contracts.CalendarEvent[] = [];
const webContext = VSS.getWebContext();
const teamContext: TFS_Core_Contracts.TeamContext = {
projectId: webContext.project.id,
teamId: this._team.id,
project: "",
team: "",
};
const workClient: Work_Client.WorkHttpClient2_1 = Service.VssConnection
.getConnection()
.getHttpClient(Work_Client.WorkHttpClient2_1, WebApi_Constants.ServiceInstanceTypes.TFS);
return realPromise(this.getIterations()).then(iterations => {
if (!iterations || iterations.length === 0) {
this._events = events;
this._renderedEvents = renderedEvents;
return renderedEvents;
}
for (const iteration of iterations) {
iterationTeamDaysOffPromises.push(workClient.getTeamDaysOff(teamContext, iteration.id));
iterationTeamDaysOffPromises[
iterationTeamDaysOffPromises.length - 1
].then((teamDaysOff: Work_Contracts.TeamSettingsDaysOff) => {
if (teamDaysOff && teamDaysOff.daysOff && teamDaysOff.daysOff.length) {
for (const daysOffRange of teamDaysOff.daysOff) {
const event: any = {};
event.startDate = new Date(daysOffRange.start.valueOf()).toISOString();
event.endDate = new Date(daysOffRange.end.valueOf()).toISOString();
event.title = "Team Day Off";
event.member = {
displayName: this._team.name,
id: this._team.id,
imageUrl: this._buildTeamImageUrl(webContext.host.uri, this._team.id),
};
event.category = <Calendar_Contracts.IEventCategory>{
id: this.id + "." + "Everyone",
title: IdentityHelper.parseUniquefiedIdentityName(event.member.displayName),
imageUrl: this._buildTeamImageUrl(webContext.host.uri, teamContext.teamId),
color: this._categoryColor,
};
event.id = this._buildCapacityEventId(event);
event.iterationId = iteration.id;
event.icons = [
{
src: event.category.imageUrl,
title: event.title,
linkedEvent: event,
},
];
events.push(event);
// add personal day off event to calendar day off events
const dates = Calendar_DateUtils.getDatesInRange(daysOffRange.start, daysOffRange.end);
for (const dateObj of dates) {
const date = dateObj.toISOString();
if (!eventMap[date]) {
const regroupedEvent: Calendar_Contracts.CalendarEvent = {
startDate: date,
endDate: date,
member: event.member,
title: "",
id: this.id + "." + date,
category: <Calendar_Contracts.IEventCategory>{
id: "",
title: "Grouped Event",
color: this._categoryColor,
},
icons: [],
};
eventMap[date] = regroupedEvent;
renderedEvents.push(regroupedEvent);
}
eventMap[date].icons.push(event.icons[0]);
}
}
}
return renderedEvents;
});
capacityPromises.push(workClient.getCapacities(teamContext, iteration.id));
capacityPromises[capacityPromises.length - 1].then((capacities: Work_Contracts.TeamMemberCapacity[]) => {
if (capacities && capacities.length) {
for (const capacity of capacities) {
for (const daysOffRange of capacity.daysOff) {
const event: any = {};
event.startDate = new Date(daysOffRange.start.valueOf()).toISOString();
event.endDate = new Date(daysOffRange.end.valueOf()).toISOString();
event.title =
IdentityHelper.parseUniquefiedIdentityName(capacity.teamMember.displayName) + " Day Off";
event.member = capacity.teamMember;
event.category = <Calendar_Contracts.IEventCategory>{
id: this.id + "." + capacity.teamMember.uniqueName,
title: IdentityHelper.parseUniquefiedIdentityName(event.member.displayName),
imageUrl: event.member.imageUrl,
color: this._categoryColor,
};
event.id = this._buildCapacityEventId(event);
event.iterationId = iteration.id;
event.icons = [
{
src: event.category.imageUrl,
title: event.title,
linkedEvent: event,
},
];
events.push(event);
// add personal day off event to calendar day off events
const dates = Calendar_DateUtils.getDatesInRange(daysOffRange.start, daysOffRange.end);
for (const dateObj of dates) {
const date = dateObj.toISOString();
if (!eventMap[date]) {
const regroupedEvent: Calendar_Contracts.CalendarEvent = {
startDate: date,
endDate: date,
member: event.member,
title: "",
id: this.id + "." + date,
category: <Calendar_Contracts.IEventCategory>{
id: "",
title: "Grouped Event",
color: this._categoryColor,
},
icons: [],
};
eventMap[date] = regroupedEvent;
renderedEvents.push(regroupedEvent);
}
eventMap[date].icons.push(event.icons[0]);
}
}
}
}
return renderedEvents;
});
}
return Promise.all(iterationTeamDaysOffPromises).then(() => {
return Promise.all(capacityPromises).then(() => {
this._events = events;
this._renderedEvents = renderedEvents;
return renderedEvents;
});
});
});
}
public getIterations(): PromiseLike<Work_Contracts.TeamSettingsIteration[]> {
const webContext = VSS.getWebContext();
const teamContext: TFS_Core_Contracts.TeamContext = {
projectId: webContext.project.id,
teamId: this._team.id,
project: "",
team: "",
};
const workClient: Work_Client.WorkHttpClient2_1 = Service.VssConnection
.getConnection()
.getHttpClient(Work_Client.WorkHttpClient2_1, WebApi_Constants.ServiceInstanceTypes.TFS);
return workClient.getTeamIterations(teamContext);
}
public getCategories(query: Calendar_Contracts.IEventQuery): PromiseLike<Calendar_Contracts.IEventCategory[]> {
if (this._events) {
return Promise.resolve(this._getCategoryData(this._events.slice(0), query));
} else {
return this.getEvents().then((events: Calendar_Contracts.CalendarEvent[]) => {
return this._getCategoryData(this._events, query);
});
}
}
public addEvent(event: Calendar_Contracts.CalendarEvent): PromiseLike<Calendar_Contracts.CalendarEvent> {
const dayOffStart = new Date(event.startDate);
const dayOffEnd = new Date(event.endDate);
const isTeam: boolean = event.member.displayName === "Everyone";
const memberId: string = event.member.id;
const iterationId: string = event.iterationId;
const webContext = VSS.getWebContext();
const teamContext: TFS_Core_Contracts.TeamContext = {
projectId: webContext.project.id,
teamId: this._team.id,
project: "",
team: "",
};
const workClient: Work_Client.WorkHttpClient2_1 = Service.VssConnection
.getConnection()
.getHttpClient(Work_Client.WorkHttpClient2_1, WebApi_Constants.ServiceInstanceTypes.TFS);
if (isTeam) {
return realPromise(
this._getTeamDaysOff(workClient, teamContext, iterationId),
).then((teamDaysOff: Work_Contracts.TeamSettingsDaysOff) => {
const teamDaysOffPatch: Work_Contracts.TeamSettingsDaysOffPatch = { daysOff: teamDaysOff.daysOff };
teamDaysOffPatch.daysOff.push({ start: dayOffStart, end: dayOffEnd });
return workClient
.updateTeamDaysOff(teamDaysOffPatch, teamContext, iterationId)
.then((value: Work_Contracts.TeamSettingsDaysOff) => {
// Resolve null to tell views.js to reload the entire event source instead of re-rendering the updated event
return null;
});
});
} else {
return realPromise(
this._getCapacity(workClient, teamContext, iterationId, memberId),
).then((capacity: Work_Contracts.TeamMemberCapacity) => {
const capacityPatch: Work_Contracts.CapacityPatch = {
activities: capacity.activities,
daysOff: capacity.daysOff,
};
capacityPatch.daysOff.push({ start: dayOffStart, end: dayOffEnd });
return workClient
.updateCapacity(capacityPatch, teamContext, iterationId, memberId)
.then((value: Work_Contracts.TeamMemberCapacity) => {
// Resolve null to tell views.js to reload the entire event source instead of re-rendering the updated event
return null;
});
});
}
}
public removeEvent(event: Calendar_Contracts.CalendarEvent): PromiseLike<Calendar_Contracts.CalendarEvent[]> {
const dayOffStart = new Date(event.startDate);
const memberId = event.member.id;
const isTeam: boolean = event.member.uniqueName === undefined;
const iterationId: string = event.iterationId;
const webContext = VSS.getWebContext();
const teamContext: TFS_Core_Contracts.TeamContext = {
projectId: webContext.project.id,
teamId: this._team.id,
project: "",
team: "",
};
const workClient: Work_Client.WorkHttpClient2_1 = Service.VssConnection
.getConnection()
.getHttpClient(Work_Client.WorkHttpClient2_1, WebApi_Constants.ServiceInstanceTypes.TFS);
if (isTeam) {
return realPromise(
this._getTeamDaysOff(workClient, teamContext, iterationId),
).then((teamDaysOff: Work_Contracts.TeamSettingsDaysOff) => {
const teamDaysOffPatch: Work_Contracts.TeamSettingsDaysOffPatch = { daysOff: teamDaysOff.daysOff };
teamDaysOffPatch.daysOff.some(
(dateRange: Work_Contracts.DateRange, index: number, array: Work_Contracts.DateRange[]) => {
if (dateRange.start.valueOf() === dayOffStart.valueOf()) {
teamDaysOffPatch.daysOff.splice(index, 1);
return true;
}
return false;
},
);
return workClient
.updateTeamDaysOff(teamDaysOffPatch, teamContext, iterationId)
.then((value: Work_Contracts.TeamSettingsDaysOff) => {
// Resolve null to tell views.js to reload the entire event source instead removing one event
return null;
});
});
} else {
return realPromise(
this._getCapacity(workClient, teamContext, iterationId, memberId),
).then((capacity: Work_Contracts.TeamMemberCapacity) => {
const capacityPatch: Work_Contracts.CapacityPatch = {
activities: capacity.activities,
daysOff: capacity.daysOff,
};
capacityPatch.daysOff.some(
(dateRange: Work_Contracts.DateRange, index: number, array: Work_Contracts.DateRange[]) => {
if (dateRange.start.valueOf() === dayOffStart.valueOf()) {
capacityPatch.daysOff.splice(index, 1);
return true;
}
return false;
},
);
return workClient
.updateCapacity(capacityPatch, teamContext, iterationId, memberId)
.then((value: Work_Contracts.TeamMemberCapacity) => {
// Resolve null to tell views.js to reload the entire event source instead removing one event
return null;
});
});
}
}
public updateEvent(
oldEvent: Calendar_Contracts.CalendarEvent,
newEvent: Calendar_Contracts.CalendarEvent,
): PromiseLike<Calendar_Contracts.CalendarEvent> {
const dayOffStart = new Date(oldEvent.startDate);
const memberId = oldEvent.member.id;
const iterationId = oldEvent.iterationId;
const isTeam: boolean = oldEvent.member.uniqueName === undefined;
const webContext = VSS.getWebContext();
const teamContext: TFS_Core_Contracts.TeamContext = {
projectId: webContext.project.id,
teamId: this._team.id,
project: "",
team: "",
};
const workClient: Work_Client.WorkHttpClient2_1 = Service.VssConnection
.getConnection()
.getHttpClient(Work_Client.WorkHttpClient2_1, WebApi_Constants.ServiceInstanceTypes.TFS);
if (isTeam) {
return realPromise(
this._getTeamDaysOff(workClient, teamContext, iterationId),
).then((teamDaysOff: Work_Contracts.TeamSettingsDaysOff) => {
const teamDaysOffPatch: Work_Contracts.TeamSettingsDaysOffPatch = { daysOff: teamDaysOff.daysOff };
const updated: boolean = teamDaysOffPatch.daysOff.some(
(dateRange: Work_Contracts.DateRange, index: number, array: Work_Contracts.DateRange[]) => {
if (dateRange.start.valueOf() === dayOffStart.valueOf()) {
teamDaysOffPatch.daysOff[index].start = new Date(newEvent.startDate);
teamDaysOffPatch.daysOff[index].end = new Date(newEvent.endDate);
return true;
}
return false;
},
);
return workClient
.updateTeamDaysOff(teamDaysOffPatch, teamContext, iterationId)
.then((value: Work_Contracts.TeamSettingsDaysOff) => {
return null;
});
});
} else {
return realPromise(
this._getCapacity(workClient, teamContext, iterationId, memberId),
).then((capacity: Work_Contracts.TeamMemberCapacity) => {
const capacityPatch: Work_Contracts.CapacityPatch = {
activities: capacity.activities,
daysOff: capacity.daysOff,
};
capacityPatch.daysOff.some(
(dateRange: Work_Contracts.DateRange, index: number, array: Work_Contracts.DateRange[]) => {
if (dateRange.start.valueOf() === dayOffStart.valueOf()) {
capacityPatch.daysOff[index].start = new Date(newEvent.startDate);
capacityPatch.daysOff[index].end = new Date(newEvent.endDate);
return true;
}
return false;
},
);
return workClient
.updateCapacity(capacityPatch, teamContext, iterationId, memberId)
.then((value: Work_Contracts.TeamMemberCapacity) => {
return null;
});
});
}
}
public getTitleUrl(webContext: WebContext): PromiseLike<string> {
const workClient: Work_Client.WorkHttpClient2_1 = Service.VssConnection
.getConnection()
.getHttpClient(Work_Client.WorkHttpClient2_1, WebApi_Constants.ServiceInstanceTypes.TFS);
const teamContext: TFS_Core_Contracts.TeamContext = {
projectId: webContext.project.id,
teamId: this._team.id,
project: "",
team: "",
};
return realPromise(workClient.getTeamIterations(teamContext, "current")).then(
(iterations: Work_Contracts.TeamSettingsIteration[]) => {
if (iterations.length > 0) {
const iterationPath = iterations[0].path.substr(iterations[0].path.indexOf("\\") + 1);
return (
webContext.host.uri +
webContext.project.name +
"/" +
this._team.name +
"/_backlogs/capacity/" +
iterationPath
);
} else {
return webContext.host.uri + webContext.project.name + "/" + this._team.name + "/_admin/_iterations";
}
},
error => {
return webContext.host.uri + webContext.project.name + "/" + this._team.name + "/_admin/_iterations";
},
);
}
private _getTeamDaysOff(
workClient: Work_Client.WorkHttpClient2_1,
teamContext: TFS_Core_Contracts.TeamContext,
iterationId,
): PromiseLike<Work_Contracts.TeamSettingsDaysOff> {
return workClient.getTeamDaysOff(teamContext, iterationId).then((value: Work_Contracts.TeamSettingsDaysOff) => {
return value;
});
}
private _getCapacity(
workClient: Work_Client.WorkHttpClient2_1,
teamContext: TFS_Core_Contracts.TeamContext,
iterationId,
memberId: string,
): PromiseLike<Work_Contracts.TeamMemberCapacity> {
return workClient.getCapacities(teamContext, iterationId).then((capacities: Work_Contracts.TeamMemberCapacity[]) => {
const foundCapacities = capacities.filter(value => value.teamMember.id === memberId);
if (foundCapacities.length > 0) {
return foundCapacities[0];
}
const value = {
activities: [
{
capacityPerDay: 0,
name: null,
},
],
daysOff: [],
} as Work_Contracts.TeamMemberCapacity;
return value;
});
}
private _getCategoryData(
events: Calendar_Contracts.CalendarEvent[],
query: Calendar_Contracts.IEventQuery,
): Calendar_Contracts.IEventCategory[] {
const memberMap: { [id: string]: Calendar_Contracts.IEventCategory } = {};
const categories: Calendar_Contracts.IEventCategory[] = [];
for (const event of events) {
if (Calendar_DateUtils.eventIn(event, query)) {
const member = <Work_Contracts.Member>(<any>event).member;
if (!memberMap[member.id]) {
event.category.events = [event.id];
event.category.subTitle = this._getCategorySubTitle(event.category, events, query);
memberMap[member.id] = event.category;
categories.push(event.category);
} else {
const category = memberMap[member.id];
category.events.push(event.id);
category.subTitle = this._getCategorySubTitle(category, events, query);
}
}
}
return categories;
}
private _getCategorySubTitle(
category: Calendar_Contracts.IEventCategory,
events: Calendar_Contracts.CalendarEvent[],
query: Calendar_Contracts.IEventQuery,
): string {
// add up days off per person
const daysOffInRange: Date[] = [];
const queryStartInUtc = new Date(
query.startDate.getUTCFullYear(),
query.startDate.getUTCMonth(),
query.startDate.getUTCDate(),
query.startDate.getUTCHours(),
query.startDate.getUTCMinutes(),
query.startDate.getUTCSeconds(),
);
const queryEndInUtc = new Date(
query.endDate.getUTCFullYear(),
query.endDate.getUTCMonth(),
query.endDate.getUTCDate(),
query.endDate.getUTCHours(),
query.endDate.getUTCMinutes(),
query.endDate.getUTCSeconds(),
);
category.events.forEach(e => {
const event = events.filter(event => event.id === e)[0];
const datesInRange = Calendar_DateUtils.getDatesInRange(
Utils_Date.shiftToUTC(new Date(event.startDate)),
Utils_Date.shiftToUTC(new Date(event.endDate)),
);
datesInRange.forEach((dateToCheck: Date, index: number, array: Date[]) => {
const dateToCheckInUtc = new Date(
dateToCheck.getUTCFullYear(),
dateToCheck.getUTCMonth(),
dateToCheck.getUTCDate(),
dateToCheck.getUTCHours(),
dateToCheck.getUTCMinutes(),
dateToCheck.getUTCSeconds(),
);
if (Calendar_DateUtils.isBetween(dateToCheckInUtc, queryStartInUtc, queryEndInUtc)) {
daysOffInRange.push(dateToCheck);
}
});
});
// if user has only one day off, return that date
if (daysOffInRange.length === 1) {
return Utils_Date.localeFormat(daysOffInRange[0], Culture.getDateTimeFormat().ShortDatePattern, true);
}
// else return total number of days off
return Utils_String.format("{0} days off", daysOffInRange.length);
}
private _buildTeamImageUrl(hostUri: string, id: string): string {
return Utils_String.format("{0}_api/_common/IdentityImage?id={1}", hostUri, id);
}
private _buildCapacityEventId(event: Calendar_Contracts.CalendarEvent): string {
return Utils_String.format("{0}.{1}.{2}", this.id, event.title, event.startDate);
}
}
export class IdentityHelper {
public static IDENTITY_UNIQUEFIEDNAME_SEPERATOR_START = "<";
public static IDENTITY_UNIQUEFIEDNAME_SEPERATOR_END = ">";
public static AAD_IDENTITY_UNIQUEFIEDNAME_SEPERATOR_START = "<<";
public static AAD_IDENTITY_UNIQUEFIEDNAME_SEPERATOR_END = ">>";
public static AAD_IDENTITY_USER_PREFIX = "user:";
public static AAD_IDENTITY_GROUP_PREFIX = "group:";
public static IDENTITY_UNIQUENAME_SEPARATOR = "\\";
/**
* Parse a distinct display name string into an identity reference object
*
* @param name A distinct display name for an identity
*/
public static parseUniquefiedIdentityName(name: string): string {
if (!name) {
return null;
}
let i = name.lastIndexOf(IdentityHelper.AAD_IDENTITY_UNIQUEFIEDNAME_SEPERATOR_START);
let j = name.lastIndexOf(IdentityHelper.AAD_IDENTITY_UNIQUEFIEDNAME_SEPERATOR_END);
let isContainer: boolean = false;
let isAad: boolean = false;
if (i >= 0 && j > i) {
isAad = true;
}
// replace "<<" with "<" and ">>" with ">" in case of an AAD identity string representation to make further processing easier
name = name
.replace(
IdentityHelper.AAD_IDENTITY_UNIQUEFIEDNAME_SEPERATOR_START,
IdentityHelper.IDENTITY_UNIQUEFIEDNAME_SEPERATOR_START,
)
.replace(
IdentityHelper.AAD_IDENTITY_UNIQUEFIEDNAME_SEPERATOR_END,
IdentityHelper.IDENTITY_UNIQUEFIEDNAME_SEPERATOR_END,
);
i = name.lastIndexOf(IdentityHelper.IDENTITY_UNIQUEFIEDNAME_SEPERATOR_START);
j = name.lastIndexOf(IdentityHelper.IDENTITY_UNIQUEFIEDNAME_SEPERATOR_END);
let displayName = name;
let alias = "";
let id = "";
let localScopeId = "";
if (i >= 0 && j > i) {
displayName = name.substr(0, i).trim();
if (isAad) {
// if its an AAD identity, the string would be in format - name <<object id>>
id = name.substr(i + 1, j - i - 1).trim(); // this would be in format objectid\email
if (id.indexOf(IdentityHelper.AAD_IDENTITY_USER_PREFIX) === 0) {
id = id.substr(IdentityHelper.AAD_IDENTITY_USER_PREFIX.length);
} else if (id.indexOf(IdentityHelper.AAD_IDENTITY_GROUP_PREFIX) === 0) {
isContainer = true;
id = id.substr(IdentityHelper.AAD_IDENTITY_GROUP_PREFIX.length);
}
const ii = id.lastIndexOf("\\");
if (ii > 0) {
alias = id.substr(ii + 1).trim();
id = id.substr(0, ii).trim();
}
} else {
alias = name.substr(i + 1, j - i - 1).trim();
// If the alias component is just a guid then this is not a uniqueName
// but the localScopeId which is used only for TFS/AAD groups
if (Utils_String.isGuid(alias)) {
localScopeId = alias;
alias = "";
}
}
}
return displayName;
}
} | the_stack |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="yue_CN">
<context>
<name>AboutWindow</name>
<message>
<location filename="../../windows/aboutwindow.cpp" line="+159"/>
<source>About %1</source>
<translation>关于 %1</translation>
</message>
<message>
<location line="-91"/>
<location line="+82"/>
<source>Build %1</source>
<translation>版本:%1</translation>
</message>
<message>
<location line="-54"/>
<location line="+55"/>
<source>View on Github...</source>
<translation>喺Github上查看…</translation>
</message>
</context>
<context>
<name>AdvancedTab</name>
<message>
<location filename="../../components/settings/advancedtab.cpp" line="+123"/>
<source>Automatically check for updates on startup:</source>
<translation>自动检查更新:</translation>
</message>
<message>
<location line="+3"/>
<source>Enable dark mode:</source>
<translation>使用深色模式:</translation>
</message>
<message>
<location line="+5"/>
<source>Application language:</source>
<translation>软件语言:</translation>
</message>
<message>
<location line="+2"/>
<source>Back up</source>
<translation>备份</translation>
</message>
<message>
<location line="+2"/>
<source>Use system language</source>
<translation>系统默认</translation>
</message>
<message>
<location line="+1"/>
<source>English</source>
<translation>英文</translation>
</message>
<message>
<location line="+5"/>
<source>Simplified Chinese</source>
<translation>简体中文</translation>
</message>
<message>
<location line="+1"/>
<source>Traditional Chinese</source>
<translation>繁体中文</translation>
</message>
<message>
<location line="+107"/>
<source>Path to save exported database</source>
<translation>保存文件至</translation>
</message>
<message>
<location line="-112"/>
<source>French (CA)</source>
<translation>法文(加拿大)</translation>
</message>
<message>
<location line="-8"/>
<source>Back up saved words and history:</source>
<translation>备份你保存嘅词语同埋搜索历史:</translation>
</message>
<message>
<location line="+9"/>
<source>French</source>
<translation>法文</translation>
</message>
<message>
<location line="+1"/>
<source>Cantonese (Simplified)</source>
<translation>简体粤语</translation>
</message>
<message>
<location line="+1"/>
<source>Cantonese (Traditional)</source>
<translation>繁体粤语</translation>
</message>
</context>
<context>
<name>ContactTab</name>
<message>
<location filename="../../components/settings/contacttab.cpp" line="+150"/>
<source>Email...</source>
<translation>发送电子邮件…</translation>
</message>
<message>
<location line="+1"/>
<source>Donate...</source>
<translation>捐款…</translation>
</message>
<message>
<location line="+1"/>
<source>View on Github...</source>
<translation>喺Github上查看…</translation>
</message>
<message>
<location line="+3"/>
<source>Looking for other Cantonese resources? Try these!</source>
<translation>你系咪揾紧第啲广东话嘅资源? 试试呢啲!</translation>
</message>
</context>
<context>
<name>DictionaryTab</name>
<message>
<location filename="../../components/settings/dictionarytab.cpp" line="+134"/>
<source>The Dictionaries tab allows you to view information about dictionaries, and add or remove them.</source>
<translation>你喺“词典”呢一页上可以查看同埋管理储存咗嘅词典。</translation>
</message>
<message>
<location line="+3"/>
<source>Add Dictionary...</source>
<translation>添加词典…</translation>
</message>
<message>
<location line="+1"/>
<source>Delete Dictionary</source>
<translation>刪除词典</translation>
</message>
<message>
<location line="+1"/>
<source>Website</source>
<translation>网站</translation>
</message>
<message>
<location line="-33"/>
<source>Select dictionary file</source>
<translation>选择词典文件</translation>
</message>
<message>
<location line="+51"/>
<source>Version: %1</source>
<translation>版本: %1</translation>
</message>
<message>
<location line="+2"/>
<source>About %1</source>
<translation>关于 %1</translation>
</message>
<message>
<location line="+51"/>
<source>Dropping search indexes...</source>
<translation>删除紧搜索索引…</translation>
</message>
<message>
<location line="+6"/>
<location line="+106"/>
<source>Adding source...</source>
<translation>添加紧新词典…</translation>
</message>
<message>
<location line="-102"/>
<location line="+106"/>
<source>Adding new entries...</source>
<translation>添加紧新条目…</translation>
</message>
<message>
<location line="-102"/>
<location line="+106"/>
<source>Adding new definitions...</source>
<translation>添加紧新解释…</translation>
</message>
<message>
<location line="-102"/>
<location line="+106"/>
<location line="+71"/>
<source>Rebuilding search indexes...</source>
<translation>重建搜索索引…</translation>
</message>
<message>
<location line="-115"/>
<location line="+86"/>
<source>Removing source...</source>
<translation>移除紧来源…</translation>
</message>
<message>
<location line="-79"/>
<location line="+85"/>
<source>Removing definitions...</source>
<translation>删除紧解释…</translation>
</message>
<message>
<location line="-76"/>
<location line="+85"/>
<source>Deleted entry 0 of %1</source>
<translation>删除咗 0 / %1 个词条</translation>
</message>
<message>
<location line="-77"/>
<location line="+85"/>
<source>Deleted entry %1 of %2</source>
<translation>删除咗 %1 / %2 个词条</translation>
</message>
<message>
<location line="+11"/>
<source>Cleaning up...</source>
<translation>帮紧你清理…</translation>
</message>
<message>
<location line="+7"/>
<source>Done!</source>
<translation>完成!</translation>
</message>
<message>
<location line="+0"/>
<source>Failed!</source>
<translation>失败!</translation>
</message>
</context>
<context>
<name>DictionaryTabFailureDialog</name>
<message>
<location filename="../../dialogs/dictionarytabfailuredialog.cpp" line="+16"/>
<source>Failed to add source!</source>
<translation>添加词典失败!</translation>
</message>
<message>
<location line="+1"/>
<source>OK</source>
<translation>确定</translation>
</message>
</context>
<context>
<name>EntryActionWidget</name>
<message>
<location filename="../../components/entryview/entryactionwidget.cpp" line="+109"/>
<source>Saved!</source>
<translation>已保存!</translation>
</message>
<message>
<location line="+0"/>
<source>Save</source>
<translation>保存</translation>
</message>
<message>
<location line="+1"/>
<source>Share</source>
<translation>分享</translation>
</message>
<message>
<location line="+88"/>
<source>Path to save exported image</source>
<translation>保存文件至</translation>
</message>
</context>
<context>
<name>EntrySpeakErrorDialog</name>
<message>
<location filename="../../dialogs/entryspeakerrordialog.cpp" line="+21"/>
<source>Unable to speak entry!</source>
<translation>播放失败!</translation>
</message>
<message>
<location line="+2"/>
<source>OK</source>
<translation>确定</translation>
</message>
<message>
<location line="+2"/>
<source>Add voice</source>
<translation>下载新语言</translation>
</message>
<message>
<location line="+7"/>
<source>Help</source>
<translation>帮助</translation>
</message>
</context>
<context>
<name>EntryViewSentenceCardSection</name>
<message>
<location filename="../../components/entryview/entryviewsentencecardsection.cpp" line="+87"/>
<source>View all sentences →</source>
<translation>查看所有例句 →</translation>
</message>
</context>
<context>
<name>FavouriteSplitter</name>
<message>
<location filename="../../components/favouritewindow/favouritesplitter.cpp" line="+70"/>
<source>Saved Words</source>
<translation>已保存嘅词语</translation>
</message>
</context>
<context>
<name>HistoryWindow</name>
<message>
<location filename="../../windows/historywindow.cpp" line="+64"/>
<location line="+11"/>
<source>Search History</source>
<translation>搜索历史</translation>
</message>
<message>
<location line="-10"/>
<location line="+11"/>
<source>Viewed Entries</source>
<translation>查看历史</translation>
</message>
<message>
<location line="-3"/>
<source>History</source>
<translation>历史</translation>
</message>
</context>
<context>
<name>LoadingWidget</name>
<message>
<location filename="../../components/sentencecard/loadingwidget.cpp" line="+71"/>
<source>Searching for example sentences...</source>
<translation>揾紧例句…</translation>
</message>
</context>
<context>
<name>MAC_APPLICATION_MENU</name>
<message>
<source>Services</source>
<translation>服务</translation>
</message>
<message>
<source>Hide %1</source>
<translation>隐藏 %1</translation>
</message>
<message>
<source>Hide Others</source>
<translation>隐藏其他</translation>
</message>
<message>
<source>Show All</source>
<translation>全部显示</translation>
</message>
<message>
<source>Preferences...</source>
<translation>偏好设置…</translation>
</message>
<message>
<source>Quit %1</source>
<translation>结束 %1</translation>
</message>
<message>
<source>About %1</source>
<translation>关于 %1</translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../../windows/mainwindow.cpp" line="+84"/>
<source>Database migration finished!</source>
<translation>数据库迁移成功!</translation>
</message>
<message>
<location line="+1"/>
<source>Database migration failed!</source>
<translation>数据库迁移失败!</translation>
</message>
<message>
<location line="+160"/>
<location line="+161"/>
<source>&File</source>
<translation>文件</translation>
</message>
<message>
<location line="-160"/>
<location line="+161"/>
<source>&Edit</source>
<translation>编辑</translation>
</message>
<message>
<location line="-160"/>
<location line="+162"/>
<source>&Window</source>
<translation>窗口</translation>
</message>
<message>
<location line="-160"/>
<location line="+161"/>
<source>&Help</source>
<translation>帮助</translation>
</message>
<message>
<location line="-159"/>
<source>&About</source>
<translation>关于粤语词典</translation>
</message>
<message>
<location line="+1"/>
<source>Show the application's About box</source>
<translation>打开“关于粤语词典”嘅窗口</translation>
</message>
<message>
<location line="+3"/>
<source>Preferences</source>
<translation>偏好设置…</translation>
</message>
<message>
<location line="+2"/>
<source>Settings</source>
<translation>偏好设置…</translation>
</message>
<message>
<location line="+2"/>
<location line="+171"/>
<source>Change settings</source>
<translation>更改设置</translation>
</message>
<message>
<location line="-169"/>
<source>Close Window</source>
<translation>关闭窗口</translation>
</message>
<message>
<location line="+2"/>
<source>Undo</source>
<translation>撤销</translation>
</message>
<message>
<location line="+1"/>
<source>Redo</source>
<translation>重做</translation>
</message>
<message>
<location line="+1"/>
<source>Cut</source>
<translation>剪切</translation>
</message>
<message>
<location line="+1"/>
<source>Copy</source>
<translation>拷貝</translation>
</message>
<message>
<location line="+1"/>
<source>Paste</source>
<translation>粘贴</translation>
</message>
<message>
<location line="+2"/>
<source>Start a New Search</source>
<translation>重新搜索</translation>
</message>
<message>
<location line="+1"/>
<source>Select Search Bar Contents</source>
<translation>全选搜索栏内文字</translation>
</message>
<message>
<location line="+2"/>
<source>Jump to First Item in Search Results</source>
<translation>跳转到第一个搜索结果</translation>
</message>
<message>
<location line="+2"/>
<source>Open Selected Entry in New Window</source>
<translation>喺新窗口显示啱啱选择嘅结果</translation>
</message>
<message>
<location line="+1"/>
<source>Search Simplified Chinese</source>
<translation>用简体中文揾</translation>
</message>
<message>
<location line="+1"/>
<source>Search Traditional Chinese</source>
<translation>用繁体中文揾</translation>
</message>
<message>
<location line="+634"/>
<source>Migrating database to new version...
This might take a few minutes.
Hang tight!</source>
<translation>数据库迁移已启动,请稍等一阵</translation>
</message>
<message>
<location line="-633"/>
<source>Search Jyutping</source>
<translation>用粤语拼音揾</translation>
</message>
<message>
<location line="+1"/>
<source>Search Pinyin</source>
<translation>用汉语拼音揾</translation>
</message>
<message>
<location line="+1"/>
<source>Search English</source>
<translation>用英文揾</translation>
</message>
<message>
<location line="+2"/>
<source>View Search History</source>
<translation>打开历史记录</translation>
</message>
<message>
<location line="+1"/>
<source>Open List of Saved Words</source>
<translation>显示所有已保存嘅词语</translation>
</message>
<message>
<location line="+1"/>
<source>Minimize</source>
<translation>最小化</translation>
</message>
<message>
<location line="+1"/>
<source>Zoom</source>
<translation>缩放</translation>
</message>
<message>
<location line="+1"/>
<source>Bring All to Front</source>
<translation>前置全部窗口</translation>
</message>
<message>
<location line="+2"/>
<source>%1 Help</source>
<translation>%1 帮助</translation>
</message>
<message>
<location line="+2"/>
<source>Check for Updates...</source>
<translation>检查更新…</translation>
</message>
<message>
<location line="-41"/>
<location line="+160"/>
<source>&Search</source>
<translation>搜索</translation>
</message>
<message>
<location line="+454"/>
<source>Checking for update...</source>
<translation>检查紧更新…</translation>
</message>
</context>
<context>
<name>NoUpdateDialog</name>
<message>
<location filename="../../dialogs/noupdatedialog.cpp" line="+14"/>
<source>No update found!</source>
<translation>冇揾到可用嘅更新!</translation>
</message>
<message>
<location line="+1"/>
<source>You are on the newest version, %1.</source>
<translation>你已经使用最新嘅版本,%1.</translation>
</message>
</context>
<context>
<name>OverwriteConflictingDictionaryDialog</name>
<message>
<location filename="../../dialogs/overwriteconflictingdictionarydialog.cpp" line="+14"/>
<source>Would you like to overwrite dictionaries you already have?</source>
<translation>是否要覆盖已在数据库嘅同名词典?</translation>
</message>
<message>
<location line="+5"/>
<source>The dictionaries to be overwritten are:
- %1</source>
<translation>同名词典列表:
- %1</translation>
</message>
</context>
<context>
<name>QMessageBox</name>
<message>
<source>Help</source>
<translation>帮助</translation>
</message>
<message>
<source>OK</source>
<translation>确定</translation>
</message>
<message>
<source>Cancel</source>
<translation>取消</translation>
</message>
<message>
<source>&Yes</source>
<translation>是</translation>
</message>
<message>
<source>About Qt</source>
<translation>关于Qt</translation>
</message>
<message>
<source><p>This program uses Qt version %1.</p></source>
<translation type="obsolete"><p>这个程序使用的是Qt %1版。</p></translation>
</message>
<message>
<source>Show Details...</source>
<translation>显示详细信息…</translation>
</message>
<message>
<source>Hide Details...</source>
<translation>隐藏详细信息…</translation>
</message>
</context>
<context>
<name>QPlatformTheme</name>
<message>
<source>Cancel</source>
<translation>取消</translation>
</message>
<message>
<source>&Yes</source>
<translation>是</translation>
</message>
<message>
<source>OK</source>
<translation>确定</translation>
</message>
</context>
<context>
<name>ResetSettingsDialog</name>
<message>
<location filename="../../dialogs/resetsettingsdialog.cpp" line="+14"/>
<source>Are you sure you want to reset all settings?</source>
<translation>你确定要重置全部设置吗?</translation>
</message>
<message>
<location line="+1"/>
<source>There is no way to restore them!</source>
<translation>重置之后,无法恢复你嘅设置!</translation>
</message>
</context>
<context>
<name>ResultListModel</name>
<message>
<location filename="../../components/entrysearchresult/resultlistmodel.cpp" line="+85"/>
<location line="+1"/>
<source>Welcome!</source>
<translation>欢迎使用粤语词典!</translation>
</message>
<message>
<location line="+6"/>
<source>Start typing to search for words</source>
<translation>开始输入并搜索</translation>
</message>
<message>
<location line="+11"/>
<location line="+1"/>
<source>No results...</source>
<translation>揾唔到结果</translation>
</message>
<message>
<location line="+5"/>
<source>Simplified (SC) and Traditional (TC) Chinese, Jyutping (JP), Pinyin (PY), and English (EN) are options to the right of the search bar.</source>
<translation>你喺搜索栏旁边可以选择使用边种语言进行搜索。可选择嘅语言包括简体中文,繁体中文,粤语拼音(粤拼),汉语拼音,同埋英文。</translation>
</message>
<message>
<location line="+6"/>
<source>Try switching between languages!</source>
<translation>试吓用搜索栏旁边嘅按钮选择搜索语言!</translation>
</message>
<message>
<location line="+5"/>
<location line="+1"/>
<source>Nothing saved...</source>
<translation>你仲未保存词语㖞!</translation>
</message>
<message>
<location line="+5"/>
<source>Clicking the "save" button when viewing a word or phrase adds it to this list. Try adding a word that sounds cool!</source>
<translation>揿“保存”掣嚟保存词语。最好加个得意啲嘅!</translation>
</message>
<message>
<location line="+6"/>
<source>Save a word to get started!</source>
<translation>—</translation>
</message>
</context>
<context>
<name>SQLDatabaseUtils</name>
<message>
<location filename="../../logic/database/sqldatabaseutils.cpp" line="+472"/>
<source>Failed to delete source from database...</source>
<translation>移除词典失败</translation>
</message>
<message>
<location line="+19"/>
<source>Failed to remove definitions...</source>
<translation>移除解释失败</translation>
</message>
<message>
<location line="+6"/>
<source>Failed to remove sentences...</source>
<translation>移除例句失败</translation>
</message>
<message>
<location line="+352"/>
<source>Database versions do not match. Only dictionaries with the same versions can be added.</source>
<translation>数据库版本唔匹配!净系可以添加一样版本嘅词典。</translation>
</message>
<message>
<location line="+3"/>
<source>Current version is %1, file version is %2.</source>
<translation>当前版本:%1,文件版本:%2。</translation>
</message>
<message>
<location line="+31"/>
<source>Could not add new dictionaries. We couldn't remove a dictionary that you already had installed with the same name.</source>
<translation>添加词典失败。无法移除一部同名嘅词典。</translation>
</message>
<message>
<location line="+3"/>
<source>Try manually deleting the dictionaries yourself before adding the new dictionary.</source>
<translation>在添加新词典之前,请试试手动移除同名嘅词典。</translation>
</message>
<message>
<location line="+67"/>
<source>Unable to add definitions...</source>
<translation>添加解释失败</translation>
</message>
<message>
<location line="+4"/>
<source>Unable to add sentences...</source>
<translation>添加例句失败</translation>
</message>
<message>
<location line="-16"/>
<source>Could not insert source. Could it be a duplicate of a dictionary you already installed?</source>
<translation>添加词典失败。你系咪已经添加咗呢个词典㗎?</translation>
</message>
</context>
<context>
<name>SearchHistoryListDelegate</name>
<message>
<location filename="../../components/historyview/searchhistorylistdelegate.cpp" line="+118"/>
<source>After searching for a word, you will find it in this list. Selecting a word will allow you to do the same search again.</source>
<translation>你查词典之后就会喺呢度揾到你嘅搜素历史。如果你想再次搜素,你可以选择表中嘅任何一个词语。</translation>
</message>
</context>
<context>
<name>SearchHistoryListModel</name>
<message>
<location filename="../../components/historyview/searchhistorylistmodel.cpp" line="+39"/>
<source>No search history...</source>
<translation>冇搜素历史…</translation>
</message>
</context>
<context>
<name>SearchHistoryTab</name>
<message>
<location filename="../../components/historyview/searchhistorytab.cpp" line="+83"/>
<source>Clear All Search History</source>
<translation>清除搜索历史</translation>
</message>
</context>
<context>
<name>SearchLineEdit</name>
<message>
<location filename="../../components/mainwindow/searchlineedit.cpp" line="+146"/>
<source>Search</source>
<translation>揾粤语词典…</translation>
</message>
</context>
<context>
<name>SearchOptionsRadioGroupBox</name>
<message>
<location filename="../../components/mainwindow/searchoptionsradiogroupbox.cpp" line="+116"/>
<source>SC</source>
<translation>简体中文</translation>
</message>
<message>
<location line="+6"/>
<source>Search Simplified Chinese</source>
<translation>用简体中文揾</translation>
</message>
<message>
<location line="-5"/>
<source>TC</source>
<translation>繁体中文</translation>
</message>
<message>
<location line="+6"/>
<source>Search Traditional Chinese</source>
<translation>用繁体中文揾</translation>
</message>
<message>
<location line="-5"/>
<source>JP</source>
<translation>粤语拼音</translation>
</message>
<message>
<location line="+6"/>
<source>Search Jyutping</source>
<translation>用粤语拼音揾</translation>
</message>
<message>
<location line="-5"/>
<source>PY</source>
<translation>汉语拼音</translation>
</message>
<message>
<location line="+6"/>
<source>Search Pinyin</source>
<translation>用汉语拼音揾</translation>
</message>
<message>
<location line="-5"/>
<source>EN</source>
<translation>英文</translation>
</message>
<message>
<location line="+6"/>
<source>Search English</source>
<translation>用英文揾</translation>
</message>
</context>
<context>
<name>SentenceSplitter</name>
<message>
<location filename="../../components/sentencewindow/sentencesplitter.cpp" line="+84"/>
<source>Sentences for %1 (%2 result)</source>
<translation>用“%1“造句:(%2 个结果)</translation>
</message>
<message>
<location line="+4"/>
<source>Sentences for %1 (%2 results)</source>
<translation>用“%1“造句:(%2 个结果)</translation>
</message>
</context>
<context>
<name>SettingsTab</name>
<message>
<location filename="../../components/settings/settingstab.cpp" line="+198"/>
<source>Reset all settings</source>
<translation>重置所有设置</translation>
</message>
<message>
<location line="-46"/>
<source>Simplified/Traditional display options:</source>
<translation>简体/繁体中文显示设置:</translation>
</message>
<message>
<location line="+2"/>
<source>Jyutping/Pinyin display options:</source>
<translation>拼音显示设置:</translation>
</message>
<message>
<location line="+2"/>
<source>Pinyin display options:</source>
<translation>汉语拼音显示设置:</translation>
</message>
<message>
<location line="+3"/>
<source>Colour words by tone using:</source>
<translation>使用拼音填色:</translation>
</message>
<message>
<location line="+2"/>
<source>Jyutping tone colours:</source>
<translation>粤语拼音声调颜色:</translation>
</message>
<message>
<location line="+2"/>
<source>Pinyin tone colours:</source>
<translation>汉语拼音声调颜色:</translation>
</message>
<message>
<location line="-29"/>
<source>Only Simplified</source>
<translation>仅显示简体中文</translation>
</message>
<message>
<location line="+1"/>
<source>Only Traditional</source>
<translation>仅显示繁体中文</translation>
</message>
<message>
<location line="+1"/>
<source>Both, Prefer Simplified</source>
<translation>优先显示简体中文</translation>
</message>
<message>
<location line="+1"/>
<source>Both, Prefer Traditional</source>
<translation>优先显示繁体中文</translation>
</message>
<message>
<location line="+2"/>
<source>Only Jyutping</source>
<translation>仅显示粤语拼音</translation>
</message>
<message>
<location line="+1"/>
<source>Only Pinyin</source>
<translation>仅显示汉语拼音</translation>
</message>
<message>
<location line="+1"/>
<source>Both, Prefer Jyutping</source>
<translation>优先显示粤语拼音</translation>
</message>
<message>
<location line="+1"/>
<source>Both, Prefer Pinyin</source>
<translation>优先显示汉语拼音</translation>
</message>
<message>
<location line="+2"/>
<source>Pinyin with diacritics</source>
<translation>用符号嘅拼音</translation>
</message>
<message>
<location line="+1"/>
<source>Pinyin with numbers</source>
<translation>用数字嘅拼音</translation>
</message>
<message>
<location line="+2"/>
<source>No colours</source>
<translation>唔填色</translation>
</message>
<message>
<location line="+1"/>
<source>Jyutping</source>
<translation>粤语拼音</translation>
</message>
<message>
<location line="+1"/>
<source>Pinyin</source>
<translation>汉语拼音</translation>
</message>
<message>
<location line="+21"/>
<location line="+14"/>
<source>No Tone</source>
<translation>未知声调</translation>
</message>
<message>
<location line="-10"/>
<location line="+18"/>
<source>Tone %1</source>
<translation>第 %1 声</translation>
</message>
<message>
<location line="-4"/>
<source>Neutral</source>
<translation>轻声</translation>
</message>
</context>
<context>
<name>SettingsWindow</name>
<message>
<location filename="../../windows/settingswindow.cpp" line="+127"/>
<source>General</source>
<translation>通用</translation>
</message>
<message>
<location line="+1"/>
<source>Dictionaries</source>
<translation>词典</translation>
</message>
<message>
<location line="+1"/>
<source>Advanced</source>
<translation>高级设置</translation>
</message>
<message>
<location line="+1"/>
<source>Contact</source>
<translation>联系我哋</translation>
</message>
<message>
<location line="+3"/>
<source>Preferences</source>
<translation>设置</translation>
</message>
<message>
<location line="+2"/>
<source>Settings</source>
<translation>设置</translation>
</message>
</context>
<context>
<name>UpdateWindow</name>
<message>
<location filename="../../windows/updatewindow.cpp" line="+151"/>
<source>Update Available!</source>
<translation>更新可用!</translation>
</message>
<message>
<location line="-16"/>
<source>A new version of %1 is available!</source>
<translation>%1嘅新版本已可用!</translation>
</message>
<message>
<location line="+4"/>
<source>%1 version %2 is available — you have version %3. Click "Download" to get the new version.</source>
<translation>%1 %2 已可用 — 你所使用嘅版本系 %3。点击“下载”按钮以获取新版本。</translation>
</message>
<message>
<location line="+7"/>
<source>Cancel</source>
<translation>取消</translation>
</message>
<message>
<location line="+1"/>
<source>Show Details</source>
<translation>显示详细信息…</translation>
</message>
<message>
<location line="+1"/>
<source>Download</source>
<translation>下载</translation>
</message>
<message>
<location line="+22"/>
<source>Hide details</source>
<translation>隐藏详细信息…</translation>
</message>
<message>
<location line="+19"/>
<source>Show details</source>
<translation>显示详细信息…</translation>
</message>
</context>
<context>
<name>ViewHistoryListModel</name>
<message>
<location filename="../../components/historyview/viewhistorylistmodel.cpp" line="+37"/>
<location line="+1"/>
<source>No viewed items...</source>
<translation>冇查看历史…</translation>
</message>
<message>
<location line="+4"/>
<source>After viewing an entry, you can find it in this list. Selecting an item in this list will let you see that entry again.</source>
<translation>你查看词语之后就会喺呢度揾到你嘅查看历史。你选择表中嘅一个词语就可以喺词典度睇返嗰个词语。</translation>
</message>
<message>
<location line="+6"/>
<source>—</source>
<translation>—</translation>
</message>
</context>
<context>
<name>ViewHistoryTab</name>
<message>
<location filename="../../components/historyview/viewhistorytab.cpp" line="+83"/>
<source>Clear All View History</source>
<translation>清除查看历史</translation>
</message>
</context>
<context>
<name>strings</name>
<message>
<location filename="../../logic/strings/strings.h" line="+16"/>
<location line="+71"/>
<source>JP</source>
<translation>粤拼</translation>
</message>
<message>
<location line="-70"/>
<location line="+71"/>
<source>PY</source>
<translation>拼音</translation>
</message>
<message>
<location line="-70"/>
<source>DEFINITIONS</source>
<translation>解释</translation>
</message>
<message>
<location line="+2"/>
<source>SENTENCES</source>
<translation>例句</translation>
</message>
<message>
<location line="+2"/>
<source>Jyut Dictionary</source>
<translation>粤语词典</translation>
</message>
<message>
<location line="+2"/>
<source>A free, open-source offline Cantonese Dictionary.</source>
<translation>一个免费、自由、开源及脱机嘅粤语词典。</translation>
</message>
<message>
<location line="+2"/>
<source>Icon based on <a href=https://commons.wikimedia.org/wiki/Commons:Ancient_Chinese_characters_project style="color: %1; text-decoration: none">Wikimedia Ancient Chinese characters project</a> files.<br>UI icons from <a href=https://feathericons.com style="color: %1; text-decoration: none">Feather Icons</a> and <a href=https://github.com/microsoft/fluentui-system-icons style="color: %1; text-decoration: none">Fluent UI System Icons</a>.<br>Made with <a href="#" style="color: %1; text-decoration: none">Qt</a>.</source>
<translation>图标使用 <a href=https://commons.wikimedia.org/wiki/Commons:Ancient_Chinese_characters_project style="color: %1; text-decoration: none">Wikimedia Commons 古汉字计划</a> 嘅图片创造。<br>界面图标来源:<a href=https://feathericons.com style="color: %1; text-decoration: none">Feather Icons</a>同埋<a href=https://github.com/microsoft/fluentui-system-icons style="color: %1; text-decoration: none">Fluent UI System Icons</a>。<br>使用 <a href="#" style="color: %1; text-decoration: none">Qt</a> 编程。</translation>
</message>
<message>
<location line="+12"/>
<source>%1 is made with ❤️ by Aaron Tan.</source>
<translation>%1由谭可峰精心打造。</translation>
</message>
<message>
<location line="+3"/>
<source>Donate 💵, report a bug 🐛, or just say hi 👋!</source>
<translation>捐款 💵, 报告缺陷 🐛, 或者发送一个问候 👋!</translation>
</message>
<message>
<location line="+3"/>
<source>Donate, report a bug, or just say hi!</source>
<translation>捐款, 报告缺陷, 或者发送一个问候!</translation>
</message>
<message>
<location line="+1"/>
<source><a href=https://www.pleco.com style="color: %1; text-decoration: none">Pleco Dictionary</a>, <a href=http://www.cantonese.sheik.co.uk/dictionary/ style="color: %1; text-decoration: none">CantoDict</a>, <a href=https://words.hk style="color: %1; text-decoration: none">words.hk</a></source>
<translation><a href=https://www.pleco.com style="color: %1; text-decoration: none">Pleco 汉语词典</a>、<a href=http://www.cantonese.sheik.co.uk/dictionary/ style="color: %1; text-decoration: none">CantoDict</a>、<a href=https://words.hk style="color: %1; text-decoration: none">words.hk 粤典</a></translation>
</message>
<message>
<location line="+8"/>
<source>A voice for "Chinese - Hong Kong" could not be found.</source>
<translation>揾唔到 “粤语(香港)”语音引擎。</translation>
</message>
<message>
<location line="+8"/>
<source>A voice for "Chinese - Taiwan" could not be found.</source>
<translation>揾唔到「国语(台湾)」语音引擎。</translation>
</message>
<message>
<location line="+8"/>
<source>A voice for "Chinese - Mainland China" could not be found.</source>
<translation>揾唔到 “普通话(中国大陆)” 语音引擎。</translation>
</message>
<message>
<location line="+8"/>
<source>English</source>
<translation>英文</translation>
</message>
<message>
<location line="+1"/>
<source>French</source>
<translation>法文</translation>
</message>
<message>
<location line="+1"/>
<source>German</source>
<translation>德文</translation>
</message>
<message>
<location line="+1"/>
<source>Cantonese</source>
<translation>粤语</translation>
</message>
<message>
<location line="+1"/>
<source>Mandarin</source>
<translation>普通话</translation>
</message>
<message>
<location line="+1"/>
<source>Chinese</source>
<translation>中文</translation>
</message>
<message>
<location line="+2"/>
<source>SC</source>
<translation>简体中文</translation>
</message>
<message>
<location line="+1"/>
<source>TC</source>
<translation>繁体中文</translation>
</message>
<message>
<location line="+1"/>
<source>CN</source>
<translation>中文</translation>
</message>
<message>
<location line="+3"/>
<source>EN</source>
<translation>英文</translation>
</message>
<message>
<location line="-32"/>
<source>Unable to use text to speech.
Debug: Locale: %1, Language: Chinese - Hong Kong</source>
<translation>播放失败
调试: 区域设置: %1, 语言: 粤语 - 香港</translation>
</message>
<message>
<location line="+8"/>
<source>Unable to use text to speech.
Debug: Locale: %1, Language: Chinese - Taiwan</source>
<translation>播放失败
调试: 区域设置: %1, 语言: 国语 - 台湾</translation>
</message>
<message>
<location line="+7"/>
<source>Unable to use text to speech.
Debug: Locale: %1, Language: Chinese - Mainland</source>
<translation>播放失败
调试: 区域设置: %1, 语言: 普通话 - 中国大陆</translation>
</message>
</context>
</TS> | the_stack |
import React, { useState, useMemo, useCallback, ReactNode, useEffect, useRef } from 'react';
import { Tooltip, Button } from 'antd';
import moment from 'moment';
import { cloneDeep } from 'lodash';
import Grid from '@grid';
import ConfigModal from './config';
import { SmartGridType, SmartGridProps, ViewConfig } from './interface';
import formatSchema, { formatColumnFields } from './formatschema';
import ViewPicker from './viewpicker';
import { useTableConfig, useLocalStorage } from './hooks';
import withKeyevent from '@keyevent';
import Header from '@header';
import { generateUuid, deepCopy4JSON, JSONisEqual } from '@util';
import Receiver from './locale/Receiver';
const viewVersionFormat: string = 'YYYY-MM-DD HH:mm:SSSS';
const GlobalProps: Partial<SmartGridProps<any>> = {}
export const setProps = (extraProps: Partial<SmartGridProps<any>>) => {
Object.assign(GlobalProps, extraProps)
}
const GetLocale = ({setLocale}) => {
return (
<Receiver>
{
(locale) => {
setLocale(locale)
return null
}
}
</Receiver>
)
}
function SmartGrid<T>(props: SmartGridProps<T>): React.ReactElement {
const {
gridKey: originGridKey,
title,
schema,
viewSchema,
bindKeys,
headerRight,
onReload,
dataSource,
withoutAnimation = false,
headerProps = {},
onViewChange,
customViews: customViewsProp,
companyViews: companyViewsProp,
lastViewKey: lastViewKeyProp,
onCustomViewsChange,
onCompanyViewsChange,
companyViewAuth,
userId,
getCustomViews,
getCompanyViews,
setCustomViews: setCustomViewsProp,
setCompanyViews: setCompanyViewsProp,
initView,
showDisplayConfig = false,
prefixCls: customizePrefixCls,
height,
style,
hideHeader = false,
onReady,
...restProps
} = Object.assign({}, GlobalProps, props);
const [locale,setLocale] = useState(null)
const { columns, systemViews } = useMemo(() => formatSchema(schema, originGridKey,locale), [schema,locale]);
const [baseView] = systemViews;
const [gridKey, setGridKey] = useState(originGridKey);
const [configModalVisible, setConfigModalVisible] = useState(false);
const [activeView, setActiveView] = useState<ViewConfig>(baseView as ViewConfig);
const { panelConfig } = activeView;
const [lastViewKey, setLastViewKey] = useLocalStorage<string>(`grid-last-view-key:${originGridKey}:${userId}`, '');
const [customViews, setCustomViews] = useLocalStorage<ViewConfig[]>(`grid-custom-views:${originGridKey}:${userId}`, [] as ViewConfig[]);
const [companyViews, setCompanyViews] = useLocalStorage<ViewConfig[]>(`grid-company-views:${originGridKey}`, [] as ViewConfig[]);
const apiRef: any = useRef(null)
const managerRef: any = useRef(null)
//Grid渲染完成之后的回调方法
const handleReady = useCallback((params, manager) => {
apiRef.current = params
managerRef.current = manager
onReady && onReady(params, manager)
}, [onReady])
useEffect(() => {
customViewsProp && setCustomViews(customViewsProp)
}, [customViewsProp])
useEffect(() => {
companyViewsProp && setCompanyViews(companyViewsProp)
}, [companyViewsProp])
const originCustomViewsRef = useRef(null);
const originCompanyViewsRef = useRef(null);
useEffect(() => {
if (getCustomViews) {
getCustomViews(`grid-custom-views:${originGridKey}:${userId}`).then(views => {
originCustomViewsRef.current = deepCopy4JSON(views)
setCustomViews(views)
})
}
}, [originGridKey, getCustomViews])
useEffect(() => {
if (getCompanyViews) {
getCompanyViews(`grid-company-views:${originGridKey}`).then(views => {
originCompanyViewsRef.current = deepCopy4JSON(views)
setCompanyViews(views)
})
}
}, [originGridKey, getCompanyViews])
/** 直接设置视图配置 */
useEffect(() => {
if (viewSchema) {
setActiveView({
...activeView,
...viewSchema
});
}
}, [viewSchema]);
/** 切换初始视图 */
useEffect(() => {
let usedView;
const [baseView] = systemViews;
const viewKey = lastViewKeyProp || lastViewKey;
if(!originGridKey){
usedView = initView;
}else{
usedView = initView || [...systemViews, ...companyViews, ...customViews].find((sV: ViewConfig) => sV.viewId === viewKey);
}
if (!usedView) {
usedView = baseView;
}
setActiveView(cloneDeep(usedView));
if (viewKey !== usedView.viewId)
setLastViewKey(usedView.viewId);
// onViewChange && onViewChange(usedView); 接口自定义视图,customViewsProp属性冲突
}, [systemViews, customViews, companyViews, lastViewKey, lastViewKeyProp]);
/** 手动切换视图 */
const handlerChangeView = useCallback(view => {
if(view.viewId === lastViewKey) return;
managerRef.current && managerRef.current.clearLocalStorageColumns()
onViewChange && onViewChange(view);
setLastViewKey(view.viewId);
}, [originGridKey, lastViewKey, onViewChange]);
/** 保存自定义、共享视图 */
const handlerSaveViews = useCallback((params) => {
const { views, operateView, hideModal } = params;
if (operateView.viewId.startsWith('company')) {
onCompanyViewsChange && onCompanyViewsChange(views)
setCompanyViewsProp && setCompanyViewsProp(`grid-company-views:${originGridKey}`, views)
setCompanyViews(views);
} else {
onCustomViewsChange && onCustomViewsChange(views)
setCustomViewsProp && setCustomViewsProp(`grid-custom-views:${originGridKey}:${userId}`, views)
setCustomViews(views);
}
hideModal && hideModal();
}, []);
/** 修改视图 */
const handlerSaveConfig = useCallback(config => {
const newView = { ...config }
newView.version = moment().format(viewVersionFormat);
setLastViewKey(newView.viewId)
const viewList = newView.viewId.startsWith('company') ? companyViews : customViews;
const curViewIndex = viewList.findIndex((cV: ViewConfig) => cV.viewId === newView.viewId);
if (~curViewIndex) {
viewList[curViewIndex] = newView;
}
handlerSaveViews({
operateView: newView,
type: 'edit',
views: [...viewList]
});
setConfigModalVisible(false);
}, [customViews, companyViews]);
/** 另存视图 */
const onViewSaveAs = useCallback((vals, hideModal) => {
const { type, name, panelConfig } = vals;
const newView: ViewConfig = {
viewId: `${type}-${userId}-${generateUuid(8)}`,
name,
version: moment().format(viewVersionFormat),
panelConfig,
};
const oldViews = type === 'company' ? companyViews : customViews;
handlerSaveViews({
operateView: newView,
type: 'add',
views: [
...oldViews,
newView
]
});
setLastViewKey(newView.viewId);
hideModal && hideModal();
setConfigModalVisible(false);
}, [customViews, companyViews, userId]);
const handleSync = useCallback(() => {
const columnFieldsMap = activeView.panelConfig.columnFields.reduce((memo, columnField) => ({
...memo,
[columnField.fieldName]: columnField
}), {})
const columnDefs = managerRef.current.agGridColumnApi.getColumnState().filter(def => {
return def.colId !== 'defalutSelection' && def.colId !== 'g-index'
});
columnDefs.sort((prev, next) => {
if (
prev.pinned === 'left' && next.pinned !== 'left' ||
prev.pinned !== 'right' && next.pinned === 'right'
) {
return -1;
}
})
activeView.panelConfig.columnFields = columnDefs.map(columnDef => Object.assign({}, columnFieldsMap[columnDef.colId], {
fixed: columnDef.pinned,
sort: columnDef.sort,
sortIndex: columnDef.sortIndex,
hide: columnDef.hide,
width: columnDef.width
}))
handlerSaveConfig(activeView)
}, [activeView])
const [finalColumns] = useMemo(() => useTableConfig({
tableConfig: panelConfig,
columns,
tableKey: originGridKey,
}), [originGridKey,panelConfig,columns]);
// 动态列修改用户自定义视图
useEffect(() => {
setCustomViews((_customViews: ViewConfig[]) => {
for (const _customView of _customViews) {
const __columnFields = _customView.panelConfig.columnFields;
_customView.panelConfig.columnFields = formatColumnFields(__columnFields, columns)
}
if (setCustomViewsProp && originCustomViewsRef.current && !JSONisEqual(originCustomViewsRef.current, _customViews)) {
setCustomViewsProp(`grid-custom-views:${originGridKey}:${userId}`, _customViews)
}
return [..._customViews];
})
setCompanyViews((_companyViews: ViewConfig[]) => {
for (const _companyView of _companyViews) {
const __columnFields = _companyView.panelConfig.columnFields;
_companyView.panelConfig.columnFields = formatColumnFields(__columnFields, columns)
}
if (setCompanyViewsProp && originCompanyViewsRef.current && !JSONisEqual(originCompanyViewsRef.current, _companyViews)) {
setCompanyViewsProp(`grid-company-views:${originGridKey}`, _companyViews)
}
return [..._companyViews];
})
}, [columns, originGridKey, setCustomViewsProp, setCompanyViewsProp])
useEffect(() => {
setGridKey('gridKey:' + originGridKey + ':' + activeView.viewId +':' + activeView.version);
}, [finalColumns, originGridKey, activeView])
const titleRef = useRef(null);
const TableTitle = useMemo(() => (
<Receiver>
{(locale) => <ViewPicker
viewName={activeView.name}
viewId={activeView.viewId}
userId={userId}
customViews={customViews}
companyViews={companyViews}
systemViews={systemViews}
switchActiveView={handlerChangeView}
updateView={handlerSaveViews}
withoutAnimation={withoutAnimation}
splitLine={!!title}
config={
<>
<Tooltip title={locale.sync}>
<Button
size="small"
icon="sync"
style={{marginRight: 5}}
onClick={handleSync}
disabled={activeView.viewId.startsWith('system')}
/>
</Tooltip>
<Tooltip title={locale.config}>
<Button
size="small"
icon="setting"
style={{marginRight: 0}}
onClick={setConfigModalVisible.bind(null, true)}
/>
</Tooltip>
</>
}
getPopupContainer={() => titleRef.current || document.body}
/>}
</Receiver>
), [activeView, customViews, companyViews, systemViews, titleRef, title, userId]);
const HeaderRightElem: ReactNode = useMemo(()=>(
<>
{headerRight}
{onReload && (
<Receiver>
{
(locale) => <Tooltip title={locale.reload}>
<Button size="small" icon="reload" className="" onClick={() => onReload()} />
</Tooltip>
}
</Receiver>
)}
</>
), [headerRight, onReload]);
const gridHeight = useMemo(() => {
if (!height) return;
if (hideHeader) return height;
return typeof height !== 'number' ? `calc(${height} - 30px)` : height - 30;
}, [height, hideHeader])
return (
<div className="gant-smart-table-wrapper" style={{ ...style, height }}>
<GetLocale setLocale={setLocale}/>
{!hideHeader && <Header
title={
<div ref={titleRef}>
{title}
{TableTitle}
</div>
}
extra={HeaderRightElem}
{...headerProps}
></Header>}
{
withKeyevent(
bindKeys, true
)(
<Grid
dataSource={dataSource}
columns={finalColumns}
height={
gridHeight
}
onReady={handleReady}
key={originGridKey ? gridKey : undefined}
{...restProps}
/>
)
}
<ConfigModal
visible={configModalVisible}
originColumns={columns}
withoutAnimation={withoutAnimation}
userId={userId}
companyViewAuth={companyViewAuth}
showDisplayConfig={showDisplayConfig}
dataSource={activeView}
gridKey={originGridKey}
customViews={customViews}
companyViews={companyViews}
systemViews={systemViews}
onSaveViews={handlerSaveViews}
onSaveAs={onViewSaveAs}
onOk={handlerSaveConfig}
onCancel={() => setConfigModalVisible(false)}
onViewChange={onViewChange}
/>
</div>
);
}
const SmartGridFn: SmartGridType = SmartGrid;
export default SmartGridFn; | the_stack |
import * as blockstack from 'blockstack';
import * as express from 'express';
import * as crypto from 'crypto';
import * as jsontokens from 'jsontokens';
import * as logger from 'winston';
import {
gaiaConnect,
gaiaUploadProfileAll,
makeAssociationToken,
getGaiaAddressFromProfile,
} from './data';
import { getApplicationKeyInfo, getOwnerKeyInfo, extractAppKey } from './keys';
import { nameLookup, makeProfileJWT } from './utils';
import { CLINetworkAdapter } from './network';
import { GaiaHubConfig } from '@stacks/storage';
export const SIGNIN_CSS = `
h1 {
font-family: monospace;
font-size: 24px;
font-style: normal;
font-variant: normal;
font-weight: 700;
line-height: 26.4px;
}
h3 {
font-family: monospace;
font-size: 14px;
font-style: normal;
font-variant: normal;
font-weight: 700;
line-height: 15.4px;
}
p {
font-family: monospace;
font-size: 14px;
font-style: normal;
font-variant: normal;
font-weight: 400;
line-height: 20px;
}
b {
background-color: #e8e8e8;
}
pre {
font-family: monospace;
font-size: 13px;
font-style: normal;
font-variant: normal;
font-weight: 400;
line-height: 18.5714px;
}`;
export const SIGNIN_HEADER = `<html><head><style>${SIGNIN_CSS}</style></head></body><h3>Blockstack CLI Sign-in</h3><br>`;
export const SIGNIN_DESC = '<p>Sign-in request for <b>"{appName}"</b></p>';
export const SIGNIN_SCOPES = '<p>Requested scopes: <b>"{appScopes}"</b></p>';
export const SIGNIN_FMT_NAME = '<p><a href="{authRedirect}">{blockstackID}</a> ({idAddress})</p>';
export const SIGNIN_FMT_ID = '<p><a href="{authRedirect}">{idAddress}</a> (anonymous)</p>';
export const SIGNIN_FOOTER = '</body></html>';
export interface NamedIdentityType {
name: string;
idAddress: string;
privateKey: string;
index: number;
// eslint-disable-next-line @typescript-eslint/ban-types
profile: Object;
profileUrl: string;
}
interface AuthRequestType {
jti: string;
iat: number;
exp: number;
iss: null | string;
public_keys: string[];
domain_name: string;
manifest_uri: string;
redirect_uri: string;
version: string;
do_not_include_profile: boolean;
supports_hub_url: boolean;
scopes: string[];
}
// new ecdsa private key each time
const authTransitNonce = crypto.randomBytes(32).toString('hex');
/*
* Get the app private key
*/
async function getAppPrivateKey(
network: CLINetworkAdapter,
mnemonic: string,
id: NamedIdentityType,
appOrigin: string
): Promise<string> {
const appKeyInfo = await getApplicationKeyInfo(
network,
mnemonic,
id.idAddress,
appOrigin,
id.index
);
let appPrivateKey;
try {
const existingAppAddress = getGaiaAddressFromProfile(network, id.profile, appOrigin);
appPrivateKey = extractAppKey(network, appKeyInfo, existingAppAddress);
} catch (e) {
appPrivateKey = extractAppKey(network, appKeyInfo);
}
return appPrivateKey;
}
/*
* Make a sign-in link
*/
async function makeSignInLink(
network: CLINetworkAdapter,
authPort: number,
mnemonic: string,
authRequest: AuthRequestType,
hubUrl: string,
id: NamedIdentityType
): Promise<string> {
const appOrigin = authRequest.domain_name;
const appPrivateKey = await getAppPrivateKey(network, mnemonic, id, appOrigin);
const associationToken = makeAssociationToken(appPrivateKey, id.privateKey);
const authResponseTmp = blockstack.makeAuthResponse(
id.privateKey,
{},
id.name,
{ email: undefined, profileUrl: id.profileUrl },
undefined,
appPrivateKey,
undefined,
authRequest.public_keys[0],
hubUrl,
blockstack.config.network.blockstackAPIUrl,
associationToken
);
// pass along some helpful data from the authRequest
const authResponsePayload = jsontokens.decodeToken(authResponseTmp).payload;
const id_public = Object.assign({}, id);
id_public.profile = {};
// @ts-ignore
id_public.privateKey = undefined;
(authResponsePayload as any).metadata = {
id: id_public,
profileUrl: id.profileUrl,
appOrigin: appOrigin,
redirect_uri: authRequest.redirect_uri,
scopes: authRequest.scopes,
salt: crypto.randomBytes(16).toString('hex'),
nonce: authTransitNonce,
// fill in more CLI-specific fields here
};
const tokenSigner = new jsontokens.TokenSigner('ES256k', id.privateKey);
const authResponse = tokenSigner.sign(authResponsePayload);
return blockstack.updateQueryStringParameter(
`http://localhost:${authPort}/signin`,
'authResponse',
authResponse
);
}
/*
* Make the sign-in page
*/
async function makeAuthPage(
network: CLINetworkAdapter,
authPort: number,
mnemonic: string,
hubUrl: string,
manifest: any,
authRequest: AuthRequestType,
ids: NamedIdentityType[]
): Promise<string> {
let signinBody = SIGNIN_HEADER;
const signinDescription = SIGNIN_DESC.replace(/{appName}/, manifest.name || '(Unknown app)');
const signinScopes = SIGNIN_SCOPES.replace(
/{appScopes}/,
authRequest.scopes.length > 0 ? authRequest.scopes.join(', ') : '(none)'
);
signinBody = `${signinBody}${signinDescription}${signinScopes}`;
for (let i = 0; i < ids.length; i++) {
let signinEntry;
if (ids[i].name) {
signinEntry = SIGNIN_FMT_NAME.replace(
/{authRedirect}/,
await makeSignInLink(network, authPort, mnemonic, authRequest, hubUrl, ids[i])
)
.replace(/{blockstackID}/, ids[i].name)
.replace(/{idAddress}/, ids[i].idAddress);
} else {
signinEntry = SIGNIN_FMT_ID.replace(
/{authRedirect}/,
await makeSignInLink(network, authPort, mnemonic, authRequest, hubUrl, ids[i])
).replace(/{idAddress}/, ids[i].idAddress);
}
signinBody = `${signinBody}${signinEntry}`;
}
signinBody = `${signinBody}${SIGNIN_FOOTER}`;
return signinBody;
}
/*
* Find all identity addresses that have names attached to them.
* Fills in identities.
*/
async function loadNamedIdentitiesLoop(
network: CLINetworkAdapter,
mnemonic: string,
index: number,
identities: NamedIdentityType[]
): Promise<NamedIdentityType[]> {
// 65536 is a ridiculously huge number
if (index > 65536) {
throw new Error('Too many names');
}
const keyInfo = await getOwnerKeyInfo(network, mnemonic, index);
const nameList = await network.getNamesOwned(keyInfo.idAddress.slice(3));
if (nameList.length === 0) {
// out of names
return identities;
}
for (let i = 0; i < nameList.length; i++) {
const identity: NamedIdentityType = {
name: nameList[i],
idAddress: keyInfo.idAddress,
privateKey: keyInfo.privateKey,
index: index,
profile: {},
profileUrl: '',
};
identities.push(identity);
}
return await loadNamedIdentitiesLoop(network, mnemonic, index + 1, identities);
}
/*
* Load all named identities for a mnemonic.
* Keep loading until we find an ID-address that does not have a name.
*/
export function loadNamedIdentities(
network: CLINetworkAdapter,
mnemonic: string
): Promise<NamedIdentityType[]> {
return loadNamedIdentitiesLoop(network, mnemonic, 0, []);
}
/*
* Generate identity info for an unnamed ID
*/
async function loadUnnamedIdentity(
network: CLINetworkAdapter,
mnemonic: string,
index: number
): Promise<NamedIdentityType> {
const keyInfo = await getOwnerKeyInfo(network, mnemonic, index);
const idInfo = {
name: '',
idAddress: keyInfo.idAddress,
privateKey: keyInfo.privateKey,
index: index,
profile: {},
profileUrl: '',
};
return idInfo;
}
/*
* Send a JSON HTTP response
*/
// eslint-disable-next-line @typescript-eslint/ban-types
function sendJSON(res: express.Response, data: Object, statusCode: number) {
logger.info(`Respond ${statusCode}: ${JSON.stringify(data)}`);
res.writeHead(statusCode, { 'Content-Type': 'application/json' });
res.write(JSON.stringify(data));
res.end();
}
/*
* Get all of a 12-word phrase's identities, profiles, and Gaia connections.
* Returns a Promise to an Array of NamedIdentityType instances.
*
* NOTE: should be the *only* promise chain running!
*/
async function getIdentityInfo(
network: CLINetworkAdapter,
mnemonic: string,
_appGaiaHub: string,
_profileGaiaHub: string
): Promise<NamedIdentityType[]> {
network.setCoerceMainnetAddress(false);
let identities: NamedIdentityType[];
try {
// load up all of our identity addresses and profile URLs
identities = await loadNamedIdentities(network, mnemonic);
const nameInfoPromises = identities.map(id => {
const lookup: Promise<{
profile: any;
profileUrl?: string;
zonefile?: string;
} | null> = nameLookup(network, id.name, true).catch(() => null);
return lookup;
});
let nameDatas = await Promise.all(nameInfoPromises);
network.setCoerceMainnetAddress(false);
nameDatas = nameDatas.filter(p => p !== null && p !== undefined);
for (let i = 0; i < nameDatas.length; i++) {
if (nameDatas[i]!.hasOwnProperty('error') && (nameDatas[i] as any).error) {
// no data for this name
identities[i].profileUrl = '';
} else {
identities[i].profileUrl = nameDatas[i]!.profileUrl!;
identities[i].profile = nameDatas[i]!.profile;
}
}
const nextIndex = identities.length + 1;
// ignore identities with no data
identities = identities.filter(id => !!id.profileUrl);
// add in the next non-named identity
identities.push(await loadUnnamedIdentity(network, mnemonic, nextIndex));
} catch (e) {
network.setCoerceMainnetAddress(false);
throw e;
}
return identities;
}
/*
* Handle GET /auth?authRequest=...
* If the authRequest is verifiable and well-formed, and if we can fetch the application
* manifest, then we can render an auth page to the user.
* Serves back the sign-in page on success.
* Serves back an error page on error.
* Returns a Promise that resolves to nothing.
*
* NOTE: should be the *only* promise chain running!
*/
export async function handleAuth(
network: CLINetworkAdapter,
mnemonic: string,
gaiaHubUrl: string,
profileGaiaHub: string,
port: number,
req: express.Request,
res: express.Response
): Promise<any> {
const authToken = req.query.authRequest as string;
if (!authToken) {
return Promise.resolve().then(() => {
sendJSON(res, { error: 'No authRequest given' }, 400);
});
}
let errorMsg = '';
let identities: NamedIdentityType[] = [];
try {
identities = await getIdentityInfo(network, mnemonic, gaiaHubUrl, profileGaiaHub);
errorMsg = 'Unable to verify authentication token';
const valid = await blockstack.verifyAuthRequest(authToken);
if (!valid) {
errorMsg = 'Invalid authentication token: could not verify';
throw new Error(errorMsg);
}
errorMsg = 'Unable to fetch app manifest';
const appManifest = await blockstack.fetchAppManifest(authToken);
errorMsg = 'Unable to decode token';
const decodedAuthToken = jsontokens.decodeToken(authToken);
const decodedAuthPayload = decodedAuthToken.payload;
if (!decodedAuthPayload) {
errorMsg = 'Invalid authentication token: no payload';
throw new Error(errorMsg);
}
errorMsg = 'Unable to make auth page';
// make sign-in page
const authPage = await makeAuthPage(
network,
port,
mnemonic,
gaiaHubUrl,
appManifest,
decodedAuthPayload as unknown as AuthRequestType,
identities
);
res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': authPage.length });
res.write(authPage);
res.end();
} catch (e: any) {
if (!errorMsg) {
errorMsg = e.message;
}
console.log(e.stack);
logger.error(errorMsg);
sendJSON(res, { error: `Unable to authenticate app request: ${errorMsg}` }, 400);
}
}
/*
* Update a named identity's profile with new app data, if necessary.
* Indicates whether or not the profile was changed.
*/
function updateProfileApps(
network: CLINetworkAdapter,
id: NamedIdentityType,
appOrigin: string,
appGaiaConfig: GaiaHubConfig,
profile?: any
): Promise<{ profile: any; changed: boolean }> {
let needProfileUpdate = false;
// go get the profile from the profile URL in the id
const profilePromise = Promise.resolve().then(() => {
if (profile === null || profile === undefined) {
return nameLookup(network, id.name).catch(_e => null);
} else {
return { profile: profile };
}
});
return profilePromise.then(profileData => {
if (profileData) {
profile = profileData.profile;
}
if (!profile) {
// instantiate
logger.debug(`Profile for ${id.name} is ${JSON.stringify(profile)}`);
logger.debug(`Instantiating profile for ${id.name}`);
needProfileUpdate = true;
profile = {
type: '@Person',
account: [],
apps: {},
};
}
// do we need to update the Gaia hub read URL in the profile?
if (profile.apps === null || profile.apps === undefined) {
needProfileUpdate = true;
logger.debug(`Adding multi-reader Gaia links to profile for ${id.name}`);
profile.apps = {};
}
const gaiaPrefix = `${appGaiaConfig.url_prefix}${appGaiaConfig.address}/`;
if (!profile.apps.hasOwnProperty(appOrigin) || !profile.apps[appOrigin]) {
needProfileUpdate = true;
logger.debug(
`Setting Gaia read URL ${gaiaPrefix} for ${appOrigin} ` + `in profile for ${id.name}`
);
profile.apps[appOrigin] = gaiaPrefix;
} else if (!profile.apps[appOrigin].startsWith(gaiaPrefix)) {
needProfileUpdate = true;
logger.debug(
`Overriding Gaia read URL for ${appOrigin} from ${profile.apps[appOrigin]} ` +
`to ${gaiaPrefix} in profile for ${id.name}`
);
profile.apps[appOrigin] = gaiaPrefix;
}
return { profile, changed: needProfileUpdate };
});
}
/*
* Updates a named identitie's profile's API settings, if necessary.
* Indicates whether or not the profile data changed.
*/
function updateProfileAPISettings(
network: CLINetworkAdapter,
id: NamedIdentityType,
appGaiaConfig: GaiaHubConfig,
profile?: any
): Promise<{ profile: any; changed: boolean }> {
let needProfileUpdate = false;
// go get the profile from the profile URL in the id
const profilePromise = Promise.resolve().then(() => {
if (profile === null || profile === undefined) {
return nameLookup(network, id.name).catch(_e => null);
} else {
return { profile: profile };
}
});
return profilePromise.then(profileData => {
if (profileData) {
profile = profileData.profile;
}
if (!profile) {
// instantiate
logger.debug(`Profile for ${id.name} is ${JSON.stringify(profile)}`);
logger.debug(`Instantiating profile for ${id.name}`);
needProfileUpdate = true;
profile = {
type: '@Person',
account: [],
api: {},
};
}
// do we need to update the API settings in the profile?
if (profile.api === null || profile.api === undefined) {
needProfileUpdate = true;
logger.debug(`Adding API settings to profile for ${id.name}`);
profile.api = {
gaiaHubConfig: {
url_prefix: appGaiaConfig.url_prefix,
},
gaiaHubUrl: appGaiaConfig.server,
};
}
if (
!profile.hasOwnProperty('api') ||
!profile.api.hasOwnProperty('gaiaHubConfig') ||
!profile.api.gaiaHubConfig.hasOwnProperty('url_prefix') ||
!profile.api.gaiaHubConfig.url_prefix ||
!profile.api.hasOwnProperty('gaiaHubUrl') ||
!profile.api.gaiaHubUrl
) {
logger.debug(`Existing profile for ${id.name} is ${JSON.stringify(profile)}`);
logger.debug(`Updating API settings to profile for ${id.name}`);
profile.api = {
gaiaHubConfig: {
url_prefix: appGaiaConfig.url_prefix,
},
gaiaHubUrl: appGaiaConfig.server,
};
}
return { profile, changed: needProfileUpdate };
});
}
/*
* Handle GET /signin?encAuthResponse=...
* Takes an encrypted authResponse from the page generated on GET /auth?authRequest=....,
* verifies it, updates the name's profile's app's entry with the latest Gaia
* hub information (if necessary), and redirects the user back to the application.
*
* If adminKey is given, then the new app private key will be automatically added
* as an authorized writer to the Gaia hub.
*
* Redirects the user on success.
* Sends the user an error page on failure.
* Returns a Promise that resolves to nothing.
*/
export async function handleSignIn(
network: CLINetworkAdapter,
mnemonic: string,
appGaiaHub: string,
profileGaiaHub: string,
req: express.Request,
res: express.Response
): Promise<any> {
const authResponseQP = req.query.authResponse as string;
if (!authResponseQP) {
return Promise.resolve().then(() => {
sendJSON(res, { error: 'No authResponse given' }, 400);
});
}
const nameLookupUrl = `${network.legacyNetwork.blockstackAPIUrl}/v1/names/`;
let errorMsg = '';
let errorStatusCode = 400;
let authResponsePayload: any;
let id: NamedIdentityType;
let profileUrl: string;
let appOrigin: string;
let redirectUri: string;
let scopes: string[];
let authResponse: string;
let hubConfig: GaiaHubConfig;
let needProfileAPIUpdate = false;
let profileAPIUpdate: boolean;
try {
const valid = await blockstack.verifyAuthResponse(authResponseQP, nameLookupUrl);
if (!valid) {
errorMsg = `Unable to verify authResponse token ${authResponseQP}`;
throw new Error(errorMsg);
}
const authResponseToken = jsontokens.decodeToken(authResponseQP);
authResponsePayload = authResponseToken.payload;
id = authResponsePayload.metadata.id;
profileUrl = authResponsePayload.metadata.profileUrl;
appOrigin = authResponsePayload.metadata.appOrigin;
redirectUri = authResponsePayload.metadata.redirect_uri;
scopes = authResponsePayload.metadata.scopes;
const nonce = authResponsePayload.metadata.nonce;
if (nonce != authTransitNonce) {
throw new Error('Invalid auth response: not generated by this authenticator');
}
// restore
id.privateKey = (await getOwnerKeyInfo(network, mnemonic, id.index)).privateKey;
const appPrivateKey = await getAppPrivateKey(network, mnemonic, id, appOrigin);
// remove sensitive (CLI-specific) information
authResponsePayload.metadata = {
profileUrl: profileUrl,
};
authResponse = new jsontokens.TokenSigner('ES256K', id.privateKey).sign(authResponsePayload);
logger.debug(`App ${appOrigin} requests scopes ${JSON.stringify(scopes)}`);
// connect to the app gaia hub
const appHubConfig = await gaiaConnect(network, appGaiaHub, appPrivateKey);
hubConfig = appHubConfig;
let newProfileData = await updateProfileAPISettings(network, id, hubConfig);
needProfileAPIUpdate = newProfileData.changed;
profileAPIUpdate = newProfileData.profile;
newProfileData = await updateProfileApps(network, id, appOrigin, hubConfig, profileAPIUpdate);
const profile = newProfileData.profile;
const needProfileSigninUpdate = newProfileData.changed && scopes.includes('store_write');
logger.debug(`Resulting profile for ${id.name} is ${JSON.stringify(profile)}`);
let gaiaUrls: any;
// sign and replicate new profile if we need to.
// otherwise do nothing
if (needProfileSigninUpdate) {
logger.debug(`Upload new profile with new sign-in data to ${profileGaiaHub}`);
const profileJWT = makeProfileJWT(profile, id.privateKey);
gaiaUrls = await gaiaUploadProfileAll(
network,
[profileGaiaHub],
profileJWT,
id.privateKey,
id.name
);
} else if (needProfileAPIUpdate) {
// API settings changed, but we won't be adding an app entry
logger.debug(`Upload new profile with new API settings to ${profileGaiaHub}`);
const profileJWT = makeProfileJWT(profileAPIUpdate, id.privateKey);
gaiaUrls = await gaiaUploadProfileAll(
network,
[profileGaiaHub],
profileJWT,
id.privateKey,
id.name
);
} else {
logger.debug(`Gaia read URL for ${appOrigin} is ${profile.apps[appOrigin]}`);
gaiaUrls = { dataUrls: [], error: null };
}
if (gaiaUrls.hasOwnProperty('error') && gaiaUrls.error) {
errorMsg = `Failed to upload new profile: ${gaiaUrls.error}`;
errorStatusCode = 502;
throw new Error(errorMsg);
}
// success!
// redirect to application
logger.debug(`Handled sign-in to ${appOrigin} using ${id.name}`);
const appUri = blockstack.updateQueryStringParameter(redirectUri, 'authResponse', authResponse);
logger.info(`Redirect to ${appUri}`);
res.writeHead(302, { Location: appUri });
res.end();
} catch (e) {
logger.error(e);
logger.error(errorMsg);
sendJSON(res, { error: `Unable to process signin request: ${errorMsg}` }, errorStatusCode);
}
} | the_stack |
import ErrorStackParser from 'error-stack-parser';
import {EventEmitter} from 'events';
import debounce from 'lodash/debounce';
import cloneDeep from 'lodash/fp/cloneDeep';
import get from 'lodash/fp/get';
import isEmpty from 'lodash/fp/isEmpty';
import merge from 'lodash/fp/merge';
import set from 'lodash/fp/set';
import {ArkhamConstants} from '../constants/ArkhamConstants';
import {FluxAction, FluxMiddlewareType, FluxOptions, FluxPluginType, FluxStore} from './Flux.types';
/**
* FluxFramework
* @type {EventEmitter}
*/
export class FluxFramework extends EventEmitter {
static initFlux: boolean = false;
isInit: boolean = false;
// Public properties
pluginTypes: string[] = ['preDispatch', 'postDispatch'];
// Private properties
private state: any = {};
private storeActions: any = {};
private defaultOptions: FluxOptions = {
name: 'arkhamjs',
routerType: 'browser',
scrollToTop: true,
state: null,
storage: null,
storageWait: 300,
stores: [],
title: 'ArkhamJS'
};
private middleware: any = {};
private options: FluxOptions = this.defaultOptions;
/**
* Create a new instance of Flux. Note that the Flux object
* is a Singleton pattern, so only one should ever exist.
*
* @constructor
* @this {FluxFramework}
*/
constructor() {
super();
// Methods
this.addMiddleware = this.addMiddleware.bind(this);
this.addStores = this.addStores.bind(this);
this.clearAppData = this.clearAppData.bind(this);
this.clearMiddleware = this.clearMiddleware.bind(this);
this.deregister = this.deregister.bind(this);
this.dispatch = this.dispatch.bind(this);
this.getOptions = this.getOptions.bind(this);
this.getState = this.getState.bind(this);
this.getStore = this.getStore.bind(this);
this.init = this.init.bind(this);
this.off = this.off.bind(this);
this.register = this.register.bind(this);
this.removeMiddleware = this.removeMiddleware.bind(this);
this.removeStores = this.removeStores.bind(this);
this.reset = this.reset.bind(this);
this.setState = this.setState.bind(this);
// Add middleware plugin types
this.pluginTypes.forEach((type: string) => this.middleware[`${type}List`] = []);
}
/**
* Add middleware to framework.
*
* @param {array} middleware An array of middleware to add to the framework.
*/
addMiddleware(middleware: FluxMiddlewareType[]): void {
middleware.forEach((middleObj: FluxMiddlewareType) => {
// Make sure middleware is either a class or object.
if(!!middleObj && ((typeof middleObj === 'function') || (typeof middleObj === 'object'))) {
const middleName: string = middleObj.name || '';
if(!middleName) {
throw Error('Unknown middleware is not configured properly. Requires name property. Cannot add to Flux.');
}
// Sort middleware plugins for efficiency
this.pluginTypes.forEach((type: string) => {
const method = middleObj[type];
const plugin: FluxPluginType = {method, name: middleName};
this.middleware[`${type}List`] = this.addPlugin(type, plugin);
});
} else {
throw Error('Unknown middleware is not configured properly. Cannot add to Flux.');
}
});
}
/**
* Remove all app data from storage.
*
* @returns {Promise<boolean>} Whether app data was successfully removed.
*/
clearAppData(): Promise<boolean> {
// Set all store data to initial state
Object
.keys(this.storeActions)
.forEach((storeName: string) => {
const storeFn = this.storeActions[storeName];
this.state[storeFn.name] = cloneDeep(storeFn.initialState);
});
const {name, storage} = this.options;
if(storage) {
return storage.setStorageData(name, this.state);
}
return Promise.resolve(true);
}
/**
* Remove all middleware.
*
* @returns {boolean} Whether middleware was successfully removed.
*/
clearMiddleware(): boolean {
// Set all store data to initial state
Object
.keys(this.middleware)
.forEach((pluginType: string) => {
this.middleware[pluginType] = [];
});
return true;
}
/**
* De-registers named stores.
*
* @param {array} storeNames An array of store names to remove from the framework.
*/
removeStores(storeNames: string[]): void {
storeNames.forEach((name: string) => this.deregister(name));
}
/**
* Dispatches an action to all stores.
*
* @param {object} action to dispatch to all the stores.
* @param {boolean} silent To silence any events.
* @returns {Promise} The promise is resolved when and if the app saves data to storage, returning
* the action.
*/
async dispatch(action: FluxAction, silent: boolean = false): Promise<FluxAction> {
if(!action) {
throw new Error('ArkhamJS Error: Flux.dispatch requires an action.');
}
let clonedAction: FluxAction = cloneDeep(action);
// Log duration of dispatch
const startTime: number = Date.now();
// Get stack
let stack = [];
try {
const stackProperty: string = 'stackTraceLimit';
const {stackTraceLimit}: any = Error;
Error[stackProperty] = Infinity;
stack = ErrorStackParser.parse(new Error());
Error[stackProperty] = stackTraceLimit;
} catch(error) {}
// Get options
const options = cloneDeep(this.options);
// App info
const appInfo = {duration: 0, options, stack};
// Apply middleware before the action is processed
const {postDispatchList = [], preDispatchList = []} = this.middleware;
if(preDispatchList.length) {
clonedAction = await Promise
.all(
preDispatchList.map((plugin: FluxPluginType) => plugin.method(
cloneDeep(clonedAction), cloneDeep(this.state), appInfo)
)
)
.then(
(actions) => actions.reduce((updatedAction, action) =>
merge(updatedAction, action), clonedAction) as FluxAction
)
.catch((error) => {
throw error;
});
}
const {type, ...data} = clonedAction;
// Require a type
if(!type || type === '') {
console.warn('ArkhamJS Warning: Flux.dispatch is missing an action type for the payload:', data);
return Promise.resolve(clonedAction);
}
// When an action comes in, it must be completely handled by all stores
Object
.keys(this.storeActions)
.forEach((storeName: string) => {
const storeFn = this.storeActions[storeName];
const state = cloneDeep(this.state[storeName]) || cloneDeep(storeFn.initialState) || {};
this.state[storeName] = cloneDeep(storeFn.action(type, data, state)) || state;
});
// Save cache in storage
const {storage} = this.options;
if(storage) {
try {
await this.updateStorage();
} catch(error) {}
}
const endTime: number = +(new Date());
const duration: number = endTime - startTime;
appInfo.duration = duration;
if(postDispatchList.length) {
clonedAction = await Promise
.all(
postDispatchList.map(
async (plugin: FluxPluginType) => plugin.method(cloneDeep(clonedAction), cloneDeep(this.state), appInfo)
)
)
.then(
(actions) => actions.reduce((updatedAction, action) =>
merge(updatedAction, action), clonedAction) as FluxAction
)
.catch((error) => {
throw error;
});
}
if(!silent) {
this.emit(type, clonedAction);
this.emit('arkhamjs', this.state);
}
return Promise.resolve(clonedAction);
}
/**
* Get the current Flux options.
*
* @returns {FluxOptions} the Flux options object.
*/
getOptions(): FluxOptions {
return this.options;
}
/**
* Get the current state object.
*
* @param {string|array} [name] (optional) The name of the store for an object, otherwise it will return all store
* objects. You can also use an array to specify a property path within the object.
* @param {any} [defaultValue] (optional) A default value to return if null.
* @returns {any} the state object or a property value within.
*/
getState(path: string | string[] = '', defaultValue?): any {
let storeValue;
if(!path) {
storeValue = this.state || {};
} else {
storeValue = get(path, this.state);
}
const value = storeValue ? cloneDeep(storeValue) : storeValue;
return value === undefined ? defaultValue : value;
}
/**
* Get a store object registered with Flux.
*
* @param {string} name The name of the store.
* @returns {FluxStore} the store object.
*/
getStore(name: string = ''): FluxStore {
return this.storeActions[name];
}
/**
* Initialize and set configuration options.
*
* @param {object} options Configuration options.
*/
async init(options: FluxOptions = {}, reset: boolean = false): Promise<FluxFramework> {
// Should reset previous params
if(reset) {
this.isInit = false;
this.reset(false);
}
// Set options
const updatedOptions = {...options};
if(this.isInit) {
// Remove the name from options if already initialized, otherwise the root app will not be able to access
// the state tree
updatedOptions.name = this.options.name;
}
this.options = {...this.defaultOptions, ...updatedOptions};
const {debug, middleware, name, stores} = this.options;
// Update default store
try {
await this.useStorage(name);
} catch(error) {
console.error('Arkham Error: There was an error while using storage.', name);
throw error;
}
if(!!stores && stores.length) {
try {
await this.addStores(stores);
} catch(error) {
console.error('Arkham Error: There was an error while adding stores.', stores);
throw error;
}
}
if(!!middleware && middleware.length) {
this.addMiddleware(middleware);
}
const windowProperty: string = 'arkhamjs';
if(debug) {
window[windowProperty] = this;
} else {
delete window[windowProperty];
}
this.isInit = true;
this.emit(ArkhamConstants.INIT);
return this;
}
/**
* Adds an initialization listener.
*
* @param {function} [listener] The callback associated with the subscribed event.
*/
onInit(listener: (...args: any[]) => void): void {
this.on(ArkhamConstants.INIT, listener);
if(this.isInit) {
listener();
}
}
/**
* Removes the initialization listener.
*
* @param {function} [listener] The callback associated with the subscribed event.
*/
offInit(listener: (...args: any[]) => void): void {
this.off(ArkhamConstants.INIT, listener);
}
/**
* Removes an event listener.
*
* @param {string} [eventType] Event to unsubscribe.
* @param {function} [listener] The callback associated with the subscribed event.
*/
off(eventType: string, listener: (...args: any[]) => void): this {
return this.removeListener(eventType, listener);
}
/**
* Adds an event listener.
*
* @param {string} [eventType] Event to subscribe.
* @param {function} [listener] The callback associated with the subscribed event.
*/
on(eventType: string, listener: (...args: any[]) => void): this {
return this.addListener(eventType, listener);
}
/**
* Registers new Stores.
*
* @param {array} stores Store class.
* @returns {Promise<object[]>} the class object(s).
*/
async addStores(stores: any[]): Promise<object[]> {
const registeredStores: FluxStore[] = stores.map((store: FluxStore) => this.register(store));
// Save cache in session storage
const {name, storage} = this.options;
if(storage) {
try {
await storage.setStorageData(name, this.state);
} catch(error) {
throw error;
}
}
// Return classes
return registeredStores;
}
/**
* Remove middleware from framework.
*
* @param {array} string middleware names to remove.
* @returns {Promise<object[]>} the class object(s).
*/
removeMiddleware(names: string[]): void {
names.forEach((name: string) => {
// Remove middleware plugins
this.pluginTypes.forEach((type: string) => {
this.middleware[`${type}List`] = this.removePlugin(type, name);
});
});
}
/**
* Reset framework.
*
* @param {array} string middleware names to remove.
* @returns {Promise<object[]>} the class object(s).
*/
async reset(clearStorage: boolean = true): Promise<void> {
const {name, storage} = this.options;
// Clear persistent cache
if(storage && clearStorage) {
try {
await storage.setStorageData(name, {});
} catch(error) {
throw error;
}
}
// Clear all properties
this.middleware = {};
this.options = {...this.defaultOptions};
this.state = {};
this.storeActions = {};
this.isInit = false;
}
/**
* Sets the current state object.
*
* @param {string|array} [name] The name of the store to set. You can also use an array to specify a property path
* within the object.
* @param {any} [value] The value to set.
*/
setState(path: string | string[] = '', value): Promise<boolean> {
if(!!path) {
this.state = set(path, cloneDeep(value), this.state);
}
// Update persistent cache
const {storage} = this.options;
if(storage) {
return this.updateStorage();
}
return Promise.resolve(false);
}
private addPlugin(type: string, plugin: FluxPluginType): FluxPluginType[] {
const list = this.middleware[`${type}List`] || [];
const {method, name} = plugin;
if(method && typeof method === 'function') {
// Check if plugin already exists
const exists: boolean = !!list.filter((obj: FluxPluginType) => obj.name === name).length;
// Do not add duplicate plugins
if(!exists) {
list.push({method, name});
}
} else if(method !== undefined) {
throw Error(`${plugin.name} middleware is not configured properly. Method is not a function.`);
}
return list;
}
private deregister(name: string = ''): void {
delete this.storeActions[name];
delete this.state[name];
}
private register(storeFn): FluxStore {
if(!storeFn) {
throw Error('Store is undefined. Cannot register with Flux.');
}
const isFnc: boolean = typeof storeFn === 'function';
if(!isFnc) {
throw Error(`${storeFn} is not a store function. Cannot register with Flux.`);
}
// Create store object
const {name} = storeFn;
const initialState: any = storeFn();
const storeAction = {
action: storeFn,
initialState: storeFn(),
name
};
if(!isEmpty(name) && !this.storeActions[name]) {
// Save store object
this.storeActions[name] = storeAction;
// Get default values
if(!this.state[name]) {
if(initialState) {
this.state[name] = cloneDeep(initialState);
} else {
this.state[name] = {};
}
}
}
// Return store class
return this.storeActions[name];
}
private removePlugin(type: string, name: string): FluxPluginType[] {
const list = this.middleware[`${type}List`] || [];
// remove all occurrences of the plugin
return list.filter((obj: FluxPluginType) => obj.name !== name);
}
private updateStorage = () => Promise.resolve(false);
private async useStorage(name: string): Promise<void> {
const {storage, state, storageWait} = this.options;
// Cache
if(storage) {
try {
this.state = state || await storage.getStorageData(name) || {};
this.updateStorage = debounce(
() => storage.setStorageData(name, this.state),
storageWait,
{leading: true, trailing: true}
);
} catch(error) {
console.error(`ArkhamJS Error: Using storage, "${name}".`);
throw error;
}
} else {
this.state = state || {};
}
return null;
}
}
export const Flux: FluxFramework = new FluxFramework(); | the_stack |
import env from './core/env';
import * as zrUtil from './core/util';
import Handler from './Handler';
import Storage from './Storage';
import {PainterBase} from './PainterBase';
import Animation from './animation/Animation';
import HandlerProxy from './dom/HandlerProxy';
import Element, { ElementEventCallback } from './Element';
import { Dictionary, ElementEventName, RenderedEvent, WithThisType } from './core/types';
import { LayerConfig } from './canvas/Layer';
import { GradientObject } from './graphic/Gradient';
import { PatternObject } from './graphic/Pattern';
import { EventCallback } from './core/Eventful';
import TSpan from './graphic/TSpan';
import ZRImage from './graphic/Image';
import Displayable from './graphic/Displayable';
import { lum } from './tool/color';
import { DARK_MODE_THRESHOLD } from './config';
import Path from './graphic/Path';
import Group from './graphic/Group';
const useVML = !env.canvasSupported;
type PainterBaseCtor = {
new(dom: HTMLElement, storage: Storage, ...args: any[]): PainterBase
}
const painterCtors: Dictionary<PainterBaseCtor> = {};
let instances: { [key: number]: ZRender } = {};
function delInstance(id: number) {
delete instances[id];
}
function isDarkMode(backgroundColor: string | GradientObject | PatternObject): boolean {
if (!backgroundColor) {
return false;
}
if (typeof backgroundColor === 'string') {
return lum(backgroundColor, 1) < DARK_MODE_THRESHOLD;
}
else if ((backgroundColor as GradientObject).colorStops) {
const colorStops = (backgroundColor as GradientObject).colorStops;
let totalLum = 0;
const len = colorStops.length;
// Simply do the math of average the color. Not consider the offset
for (let i = 0; i < len; i++) {
totalLum += lum(colorStops[i].color, 1);
}
totalLum /= len;
return totalLum < DARK_MODE_THRESHOLD;
}
// Can't determine
return false;
}
class ZRender {
dom: HTMLElement
id: number
storage: Storage
painter: PainterBase
handler: Handler
animation: Animation
private _sleepAfterStill = 10;
private _stillFrameAccum = 0;
private _needsRefresh = true
private _needsRefreshHover = true
/**
* If theme is dark mode. It will determine the color strategy for labels.
*/
private _darkMode = false;
private _backgroundColor: string | GradientObject | PatternObject;
constructor(id: number, dom: HTMLElement, opts?: ZRenderInitOpt) {
opts = opts || {};
/**
* @type {HTMLDomElement}
*/
this.dom = dom;
this.id = id;
const storage = new Storage();
let rendererType = opts.renderer || 'canvas';
// TODO WebGL
if (useVML) {
throw new Error('IE8 support has been dropped since 5.0');
}
if (!painterCtors[rendererType]) {
// Use the first registered renderer.
rendererType = zrUtil.keys(painterCtors)[0];
}
if (!painterCtors[rendererType]) {
throw new Error(`Renderer '${rendererType}' is not imported. Please import it first.`);
}
opts.useDirtyRect = opts.useDirtyRect == null
? false
: opts.useDirtyRect;
const painter = new painterCtors[rendererType](dom, storage, opts, id);
this.storage = storage;
this.painter = painter;
const handerProxy = (!env.node && !env.worker)
? new HandlerProxy(painter.getViewportRoot(), painter.root)
: null;
this.handler = new Handler(storage, painter, handerProxy, painter.root);
this.animation = new Animation({
stage: {
update: () => this._flush(true)
}
});
this.animation.start();
}
/**
* 添加元素
*/
add(el: Element) {
if (!el) {
return;
}
this.storage.addRoot(el);
el.addSelfToZr(this);
this.refresh();
}
/**
* 删除元素
*/
remove(el: Element) {
if (!el) {
return;
}
this.storage.delRoot(el);
el.removeSelfFromZr(this);
this.refresh();
}
/**
* Change configuration of layer
*/
configLayer(zLevel: number, config: LayerConfig) {
if (this.painter.configLayer) {
this.painter.configLayer(zLevel, config);
}
this.refresh();
}
/**
* Set background color
*/
setBackgroundColor(backgroundColor: string | GradientObject | PatternObject) {
if (this.painter.setBackgroundColor) {
this.painter.setBackgroundColor(backgroundColor);
}
this.refresh();
this._backgroundColor = backgroundColor;
this._darkMode = isDarkMode(backgroundColor);
}
getBackgroundColor() {
return this._backgroundColor;
}
/**
* Force to set dark mode
*/
setDarkMode(darkMode: boolean) {
this._darkMode = darkMode;
}
isDarkMode() {
return this._darkMode;
}
/**
* Repaint the canvas immediately
*/
refreshImmediately(fromInside?: boolean) {
// const start = new Date();
if (!fromInside) {
// Update animation if refreshImmediately is invoked from outside.
// Not trigger stage update to call flush again. Which may refresh twice
this.animation.update(true);
}
// Clear needsRefresh ahead to avoid something wrong happens in refresh
// Or it will cause zrender refreshes again and again.
this._needsRefresh = false;
this.painter.refresh();
// Avoid trigger zr.refresh in Element#beforeUpdate hook
this._needsRefresh = false;
// const end = new Date();
// const log = document.getElementById('log');
// if (log) {
// log.innerHTML = log.innerHTML + '<br>' + (end - start);
// }
}
/**
* Mark and repaint the canvas in the next frame of browser
*/
refresh() {
this._needsRefresh = true;
// Active the animation again.
this.animation.start();
}
/**
* Perform all refresh
*/
flush() {
this._flush(false);
}
private _flush(fromInside?: boolean) {
let triggerRendered;
const start = new Date().getTime();
if (this._needsRefresh) {
triggerRendered = true;
this.refreshImmediately(fromInside);
}
if (this._needsRefreshHover) {
triggerRendered = true;
this.refreshHoverImmediately();
}
const end = new Date().getTime();
if (triggerRendered) {
this._stillFrameAccum = 0;
this.trigger('rendered', {
elapsedTime: end - start
} as RenderedEvent);
}
else if (this._sleepAfterStill > 0) {
this._stillFrameAccum++;
// Stop the animiation after still for 10 frames.
if (this._stillFrameAccum > this._sleepAfterStill) {
this.animation.stop();
}
}
}
/**
* Set sleep after still for frames.
* Disable auto sleep when it's 0.
*/
setSleepAfterStill(stillFramesCount: number) {
this._sleepAfterStill = stillFramesCount;
}
/**
* Wake up animation loop. But not render.
*/
wakeUp() {
this.animation.start();
// Reset the frame count.
this._stillFrameAccum = 0;
}
/**
* Add element to hover layer
*/
addHover(el: Displayable) {
// deprecated.
}
/**
* Add element from hover layer
*/
removeHover(el: Path | TSpan | ZRImage) {
// deprecated.
}
/**
* Clear all hover elements in hover layer
*/
clearHover() {
// deprecated.
}
/**
* Refresh hover in next frame
*/
refreshHover() {
this._needsRefreshHover = true;
}
/**
* Refresh hover immediately
*/
refreshHoverImmediately() {
this._needsRefreshHover = false;
if (this.painter.refreshHover && this.painter.getType() === 'canvas') {
this.painter.refreshHover();
}
}
/**
* Resize the canvas.
* Should be invoked when container size is changed
*/
resize(opts?: {
width?: number| string
height?: number | string
}) {
opts = opts || {};
this.painter.resize(opts.width, opts.height);
this.handler.resize();
}
/**
* Stop and clear all animation immediately
*/
clearAnimation() {
this.animation.clear();
}
/**
* Get container width
*/
getWidth(): number {
return this.painter.getWidth();
}
/**
* Get container height
*/
getHeight(): number {
return this.painter.getHeight();
}
/**
* Export the canvas as Base64 URL
* @param {string} type
* @param {string} [backgroundColor='#fff']
* @return {string} Base64 URL
*/
// toDataURL: function(type, backgroundColor) {
// return this.painter.getRenderedCanvas({
// backgroundColor: backgroundColor
// }).toDataURL(type);
// },
/**
* Converting a path to image.
* It has much better performance of drawing image rather than drawing a vector path.
*/
pathToImage(e: Path, dpr: number) {
if (this.painter.pathToImage) {
return this.painter.pathToImage(e, dpr);
}
}
/**
* Set default cursor
* @param cursorStyle='default' 例如 crosshair
*/
setCursorStyle(cursorStyle: string) {
this.handler.setCursorStyle(cursorStyle);
}
/**
* Find hovered element
* @param x
* @param y
* @return {target, topTarget}
*/
findHover(x: number, y: number): {
target: Displayable
topTarget: Displayable
} {
return this.handler.findHover(x, y);
}
on<Ctx>(eventName: ElementEventName, eventHandler: ElementEventCallback<Ctx, ZRenderType>, context?: Ctx): this
// eslint-disable-next-line max-len
on<Ctx>(eventName: string, eventHandler: WithThisType<EventCallback<any[]>, unknown extends Ctx ? ZRenderType : Ctx>, context?: Ctx): this
// eslint-disable-next-line max-len
on<Ctx>(eventName: string, eventHandler: (...args: any) => any, context?: Ctx): this {
this.handler.on(eventName, eventHandler, context);
return this;
}
/**
* Unbind event
* @param eventName Event name
* @param eventHandler Handler function
*/
// eslint-disable-next-line max-len
off(eventName?: string, eventHandler?: EventCallback) {
this.handler.off(eventName, eventHandler);
}
/**
* Trigger event manually
*
* @param eventName Event name
* @param event Event object
*/
trigger(eventName: string, event?: unknown) {
this.handler.trigger(eventName, event);
}
/**
* Clear all objects and the canvas.
*/
clear() {
const roots = this.storage.getRoots();
for (let i = 0; i < roots.length; i++) {
if (roots[i] instanceof Group) {
roots[i].removeSelfFromZr(this);
}
}
this.storage.delAllRoots();
this.painter.clear();
}
/**
* Dispose self.
*/
dispose() {
this.animation.stop();
this.clear();
this.storage.dispose();
this.painter.dispose();
this.handler.dispose();
this.animation =
this.storage =
this.painter =
this.handler = null;
delInstance(this.id);
}
}
export interface ZRenderInitOpt {
renderer?: string // 'canvas' or 'svg
devicePixelRatio?: number
width?: number | string // 10, 10px, 'auto'
height?: number | string
useDirtyRect?: boolean
}
/**
* Initializing a zrender instance
*/
export function init(dom: HTMLElement, opts?: ZRenderInitOpt) {
const zr = new ZRender(zrUtil.guid(), dom, opts);
instances[zr.id] = zr;
return zr;
}
/**
* Dispose zrender instance
*/
export function dispose(zr: ZRender) {
zr.dispose();
}
/**
* Dispose all zrender instances
*/
export function disposeAll() {
for (let key in instances) {
if (instances.hasOwnProperty(key)) {
instances[key].dispose();
}
}
instances = {};
}
/**
* Get zrender instance by id
*/
export function getInstance(id: number): ZRender {
return instances[id];
}
export function registerPainter(name: string, Ctor: PainterBaseCtor) {
painterCtors[name] = Ctor;
}
/**
* @type {string}
*/
export const version = '5.2.1';
export interface ZRenderType extends ZRender {}; | the_stack |
import {
CdmArgumentDefinition,
CdmAttributeGroupDefinition,
CdmCollection,
CdmConstantEntityDefinition,
CdmCorpusContext,
CdmDataTypeDefinition,
CdmDataTypeReference,
CdmDocumentDefinition,
CdmEntityDefinition,
CdmImport,
cdmLogCode,
CdmObject,
cdmObjectType,
CdmParameterDefinition,
CdmPurposeDefinition,
CdmTraitCollection,
CdmTraitDefinition,
CdmTraitReference,
CdmTraitReferenceBase,
Logger
} from '../../internal';
import { isCdmTraitDefinition } from '../../Utilities/cdmObjectTypeGuards';
/**
* Dictionary used to cache documents with trait definitions by file name.
*/
const cachedDefDocs: Map<[CdmCorpusContext, string], CdmDocumentDefinition> = new Map<[CdmCorpusContext, string], CdmDocumentDefinition>();
/**
* Set of extensions that are officially supported and have their definitions in the extensions folder.
*/
const supportedExtensions: Set<string> = new Set(['pbi']);
/**
* Constant used to store the prefix that is the mark of extension traits.
*/
const extensionTraitNamePrefix: string = 'is.extension.';
export const extensionDocName: string = 'custom.extension.cdm.json';
/**
* Adds the list of documents with extensions schema definitions to the manifest.
* @param ctx The context
* @param importDocs The list of paths of documents with relevant schema definitions.
* @param document The manifest that needs to import the docs.
*/
export function addImportDocsToManifest(ctx: CdmCorpusContext, importDocs: CdmImport[], document: CdmDocumentDefinition): void {
for (const importDoc of importDocs) {
if (!document.imports.allItems.find((importPresent: CdmImport) => importPresent.corpusPath === importDoc.corpusPath)) {
document.imports.push(importDoc);
}
}
}
/**
* For all the definitions (name, type) we have found for extensions, search in CDM Standard Schema for definition files.
* If we find a definition in a CDM Standard Schema file, we add that file to importsList.
* At the same time, the found definition is removed from extensionTraitDefList.
* When this function returns, extensionTraitDefList only contains definitions that are not present in any CDM Standard Schema file,
* and a list of CDM Standard Schema files with relevant definitions is returned.
* @param ctx The context
* @param extensionTraitDefList The list of all definitions for all found extensions.
* Function modifies this list by removing definitions found in CDM Standard Schema files.
* @param localExtensionTraitDefList The list of all definitions for all found extensions in local scope.
* @returns A list of CDM Standard Schema files to import.
*/
export async function standardImportDetection(
ctx: CdmCorpusContext,
extensionTraitDefList: CdmTraitDefinition[],
localExtensionTraitDefList: CdmTraitDefinition[]): Promise<CdmImport[]> {
const importsList: CdmImport[] = [];
let hasCustomExtensionImport: boolean = false;
for (let traitIndex: number = localExtensionTraitDefList.length - 1; traitIndex >= 0; traitIndex--) {
const extensionTraitDef: CdmTraitDefinition = localExtensionTraitDefList[traitIndex];
if (!traitDefIsExtension(extensionTraitDef)) {
Logger.error(this.ctx, this.TAG, this.standardImportDetection.name, null, cdmLogCode.ErrPersistModelJsonInvalidExtensionTrait, extensionTraitDef.traitName, extensionTraitNamePrefix);
return undefined;
}
const extensionBreakdown: string[] = removeExtensionTraitNamePrefix(extensionTraitDef.traitName)
.split(':');
if (extensionBreakdown.length > 1) {
const extensionName: string = extensionBreakdown[0];
if (!supportedExtensions.has(extensionName)) {
if (!hasCustomExtensionImport) {
const importObject: CdmImport = ctx.corpus.MakeObject<CdmImport>(cdmObjectType.import);
importObject.corpusPath = extensionDocName;
importsList.push(importObject);
hasCustomExtensionImport = true;
}
continue;
}
const fileName: string = `${extensionName}.extension.cdm.json`;
const fileCorpusPath: string = `cdm:/extensions/${fileName}`;
const extensionDoc: CdmDocumentDefinition = await fetchDefDoc(ctx, fileName);
/**
* If no document was found for that extensionName, the trait does not have a document with it's definition.
* Trait will be kept in extensionTraitDefList (a document with its definition will be created locally)
*/
if (extensionDoc === undefined) {
continue;
}
/**
* There is a document with extensionName, now we search for the trait in this document.
* If we find it, we remove the trait from extensionTraitDefList and add the document to imports
*/
const matchingTrait: CdmTraitDefinition = extensionDoc.definitions.allItems.find(
(
definition:
| CdmTraitDefinition
| CdmDataTypeDefinition
| CdmPurposeDefinition
| CdmAttributeGroupDefinition
| CdmEntityDefinition
| CdmConstantEntityDefinition
) => isCdmTraitDefinition(definition) && definition.getName() === extensionTraitDef.traitName
) as CdmTraitDefinition;
if (matchingTrait) {
const parameterList: CdmCollection<CdmParameterDefinition> = matchingTrait.parameters;
if (
!extensionTraitDef.parameters.allItems.some(
(extensionParameter: CdmParameterDefinition): boolean =>
!parameterList.allItems.some(
(defParameter: CdmParameterDefinition): boolean => defParameter.name === extensionParameter.name
)
)
) {
extensionTraitDefList.splice(extensionTraitDefList.indexOf(extensionTraitDef), 1);
if (!importsList.some((importDoc: CdmImport) => importDoc.corpusPath === fileCorpusPath)) {
const importObject: CdmImport = ctx.corpus.MakeObject<CdmImport>(cdmObjectType.import);
importObject.corpusPath = fileCorpusPath;
importsList.push(importObject);
}
}
}
}
}
return importsList;
}
export function processExtensionFromJson(
ctx: CdmCorpusContext,
sourceObject: object,
baseProperties: string[],
traitRefSet: CdmTraitCollection,
extensionTraitDefList: CdmTraitDefinition[],
localExtensionTraitDefList?: CdmTraitDefinition[]
): void {
const extensionKeys: string[] = Object.keys(sourceObject);
for (const baseKey of baseProperties) {
const index: number = extensionKeys.indexOf(baseKey);
if (index > -1) {
extensionKeys.splice(index, 1);
}
}
for (const extensionKey of extensionKeys) {
const traitName: string = addExtensionTraitNamePrefix(extensionKey);
let extensionTraitDef: CdmTraitDefinition =
extensionTraitDefList.find((trait: CdmTraitDefinition) => trait.traitName === traitName);
const traitExists: boolean = !!extensionTraitDef;
if (!traitExists) {
extensionTraitDef = ctx.corpus.MakeObject<CdmTraitDefinition>(cdmObjectType.traitDef, traitName);
extensionTraitDef.extendsTrait = ctx.corpus.MakeObject<CdmTraitReference>(cdmObjectType.traitRef, 'is.extension', true);
}
const extensionTraitRef: CdmTraitReference = ctx.corpus.MakeObject<CdmTraitReference>(cdmObjectType.traitRef, traitName);
const extensionValue = sourceObject[extensionKey];
const isArray: boolean = Array.isArray(extensionValue);
if (extensionValue !== null && typeof extensionValue === 'object' && !isArray) {
const extVals = Object.keys(extensionValue)
.filter((extension: string) => !extension.startsWith('_'));
for (const extensionProperty of extVals) {
const extensionPropertyValue: object = extensionValue[extensionProperty];
const extensionArgument: CdmArgumentDefinition = ctx.corpus.MakeObject<CdmArgumentDefinition>(
cdmObjectType.argumentDef,
extensionProperty
);
let extensionParameter: CdmParameterDefinition = extensionTraitDef.parameters.allItems.find(
(parameter: CdmParameterDefinition) => parameter.name === extensionProperty
);
const parameterExists: boolean = !!extensionParameter;
if (!parameterExists) {
extensionParameter = ctx.corpus.MakeObject<CdmParameterDefinition>(cdmObjectType.parameterDef, extensionProperty);
extensionParameter.dataTypeRef = ctx.corpus.MakeObject<CdmDataTypeReference>(
cdmObjectType.dataTypeRef,
convertObjectTypeToString(typeof extensionPropertyValue),
true
);
}
extensionArgument.value = extensionPropertyValue;
extensionTraitRef.arguments.push(extensionArgument);
if (!parameterExists) {
extensionTraitDef.parameters.push(extensionParameter);
}
}
} else {
const extensionArgument: CdmArgumentDefinition =
ctx.corpus.MakeObject<CdmArgumentDefinition>(cdmObjectType.argumentDef, traitName);
let extensionParameter: CdmParameterDefinition = extensionTraitDef.parameters.allItems.find(
(parameter: CdmParameterDefinition) => parameter.name === traitName
);
const parameterExists: boolean = !!extensionParameter;
if (!parameterExists) {
extensionParameter = ctx.corpus.MakeObject<CdmParameterDefinition>(cdmObjectType.parameterDef, traitName);
extensionParameter.dataTypeRef = ctx.corpus.MakeObject<CdmDataTypeReference>(
cdmObjectType.dataTypeRef,
convertObjectTypeToString(typeof extensionValue),
true
);
}
extensionArgument.value = extensionValue;
extensionTraitRef.arguments.push(extensionArgument);
if (!parameterExists) {
extensionTraitDef.parameters.push(extensionParameter);
}
}
if (!traitExists) {
extensionTraitDefList.push(extensionTraitDef);
}
if (localExtensionTraitDefList) {
localExtensionTraitDefList.push(extensionTraitDef);
}
traitRefSet.push(extensionTraitRef);
}
}
export function convertObjectTypeToString(objType: string): string {
return objType === 'array' ? 'object' : objType;
}
export function processExtensionTraitToObject(extensionTraitRef: CdmTraitReference, destination: object): void {
const originalPropName: string = extensionTraitRef.namedReference.substr(13);
if (extensionTraitRef.arguments.length === 1 && extensionTraitRef.arguments.allItems[0].name === extensionTraitRef.namedReference) {
destination[originalPropName] = extensionTraitRef.arguments.allItems[0].value;
return;
}
const valueObject: object = {};
for (const argument of extensionTraitRef.arguments) {
valueObject[argument.name] = argument.value;
}
destination[originalPropName] = valueObject;
}
/**
* Checks whether the trait reference base is an extension (by checking whether its name has the extension prefix)
* @param trait The trait to be checked
* @returns Whether the trait is an extension.
*/
export function traitRefIsExtension(trait: CdmTraitReferenceBase): boolean {
return traitNameHasExtensionMark(trait.namedReference);
}
/**
* Tries to fetch the document with definitions that corresponds to the provided fileName.
* Caches results in a dictionary.
* Returns null if no such document was found.
* @param ctx The context
* @param fileName The name of the file to be fetched or retrieved from the cache.
* @returns The retrieved document or null if no such document was found.
*/
async function fetchDefDoc(ctx: CdmCorpusContext, fileName: string): Promise<CdmDocumentDefinition> {
// Since the CachedDefDocs is a static property and there might be multiple corpus running,
// we need to make sure that each corpus will have its own cached def document.
// This is achieved by adding the context as part of the key to the document.
const key: [CdmCorpusContext, string] = [ctx, fileName];
if (cachedDefDocs.has(key)) {
// We already loaded this document and it is in the cache (dictionary)
return cachedDefDocs.get(key);
}
// We retrieve the document and cache in the dictionary for future reference.
const path: string = `/extensions/${fileName}`;
const absPath: string = ctx.corpus.storage.createAbsoluteCorpusPath(path, ctx.corpus.storage.fetchRootFolder('cdm'));
const document: CdmObject = await ctx.corpus.fetchObjectAsync(absPath);
if (document) {
const extensionDoc: CdmDocumentDefinition = document as CdmDocumentDefinition;
cachedDefDocs.set(key, extensionDoc);
return extensionDoc;
}
}
/**
* Checks whether a trait name has the specific mark of an extension.
* @param traitName The name of the trait that is to be checked whether it has the extension mark.
* @returns Whether the traitName has the mark of an extension.
*/
function traitNameHasExtensionMark(traitName: string): boolean {
if (!traitName) {
return false;
}
return traitName.startsWith(extensionTraitNamePrefix);
}
/**
* Checks whether a trait definition is an extension.
* @param trait The trait to be checked
* @returns Whether the trait is an extension.
*/
function traitDefIsExtension(trait: CdmTraitDefinition): boolean {
return traitNameHasExtensionMark(trait.traitName);
}
/**
* Removes the prefix that was added to the traitName to mark it as an extension.
* @param traitName The name of the trait that contains the extension prefix.
* @returns The name of the trait after the extension prefix was removed.
*/
function removeExtensionTraitNamePrefix(traitName: string): string {
return traitName.substr(extensionTraitNamePrefix.length);
}
/**
* Adds a prefix to a trait name to mark it as an extension.
* @param traitName The name of the trait without extension prefix.
* @returns The name of the trait after the extension prefix was added.
*/
function addExtensionTraitNamePrefix(traitName: string): string {
return `${extensionTraitNamePrefix}${traitName}`;
} | the_stack |
import {Highlight, Text2HtmlConverter, TextRenderer} from './renderer';
import {SlElement} from '@app/utils/sl-element';
import {LvUtils} from '@app/utils/utils';
const exceptionMessageClass = 'exception-message';
const exceptionFileNameClass = 'ex-stacktrace-source';
const MAX_MESSAGE_LENGTH = 1024;
export class JavaExceptionRenderer implements TextRenderer {
private rgxHeader: RegExp;
private rgxCausedBy: RegExp;
private rgxItem: RegExp;
private rgxItemSearch: RegExp;
private rgxEnd: RegExp = /\n\t\.\.\. (\d+) (?:common frames omitted|more)$/ymg;
private static EX_I_CLASSLOADER = 1;
private static EX_I_MODULE = 2;
private static EX_I_PACKAGE = 3;
private static EX_I_CLASS = 4;
private static EX_I_METHOD = 5;
private static EX_I_SUBMITTED_FROM = 6;
private static EX_I_SOURCE = 7;
private static EX_I_JARNAME = 8;
private readonly homePackages: string[];
constructor(args: {homePackages: string[]}) {
this.homePackages = args.homePackages || [];
for (let i = 0; i < this.homePackages.length; i++) {
if (!this.homePackages[i].endsWith('.')) { this.homePackages[i] += '.'; }
}
let rgxIdent = '[a-zA-Z_$][a-zA-Z_$0-9]*';
let rgxHeader = `((?:${rgxIdent}\\.)+${rgxIdent})(?:: ([^\n]*))?`;
this.rgxHeader = new RegExp(`^${rgxHeader}$`, 'mg');
this.rgxCausedBy = new RegExp(`\nCaused by: ${rgxHeader}$`, 'ymg');
let rgxItem: string = '\n\tat ' +
'(?:' +
'([^/@\n]+/)??' +
'([^/@\n]+(?:@[^/\n]+)?/)?' +
`((?:${rgxIdent}\\.)+)?(${rgxIdent})\\.(${rgxIdent}|<\\w+>)` +
'|' +
'(-+ submitted from -+)\\.' +
')' +
'\\(' +
'(' +
'[a-zA-Z_$][a-zA-Z_$0-9]*\\.[a-zA-Z]+(?::-?\\d{1,9})?|<\\w+>|Native Method|Unknown Source' +
')' +
'\\)' +
'( ~?\\[[^\\[\\]\\s]+:[^\\[\\]\\s]+\\])?' + // EX_I_JARNAME
'$';
this.rgxItem = new RegExp(rgxItem, 'ymg');
this.rgxItemSearch = new RegExp(rgxItem, 'mg');
}
tryRender(s: string, textRenderer: Text2HtmlConverter): Highlight[] {
this.rgxHeader.lastIndex = 0;
let headerMatch = this.rgxHeader.exec(s);
if (!headerMatch) { return null; }
while (true) { // find last match
let next = this.rgxHeader.exec(s);
if (!next) { break; }
headerMatch = next;
}
let e = document.createElement('SPAN');
e.className = 'ex-wrapper';
let img: HTMLImageElement = <HTMLImageElement>(document.createElement('IMG'));
img.src = 'assets/java-exception.png';
(<SlElement>(<any>img)).virtual = true;
e.appendChild(img);
let exClass = document.createElement('SPAN');
exClass.className = 'exception-class';
exClass.innerText = headerMatch[1];
e.appendChild(exClass);
let headerEnd = headerMatch.index + headerMatch[0].length;
this.rgxItemSearch.lastIndex = headerEnd;
let firstItem = this.rgxItemSearch.exec(s);
if (!firstItem) { return null; }
if (firstItem.index - headerEnd > MAX_MESSAGE_LENGTH) { return null; }
if (headerMatch[2] != null) {
e.appendChild(document.createTextNode(': '));
let exMessage = document.createElement('SPAN');
exMessage.className = exceptionMessageClass;
textRenderer(exMessage, 'text/exception-message', headerMatch[2] + s.substring(headerEnd, firstItem.index));
e.appendChild(exMessage);
}
let traceItems = [firstItem];
let idx = this.rgxItemSearch.lastIndex;
while (idx < s.length) {
this.rgxItem.lastIndex = idx;
let itemRes = this.rgxItem.exec(s);
if (itemRes) {
traceItems.push(itemRes);
} else {
this.rgxCausedBy.lastIndex = idx;
itemRes = this.rgxCausedBy.exec(s);
if (itemRes) {
this.appendStacktraceItems(e, traceItems, true);
traceItems.length = 0;
e.appendChild(document.createTextNode('\nCaused by: '));
let exCauseClass = document.createElement('SPAN');
exCauseClass.className = 'exception-class';
exCauseClass.innerText = itemRes[1];
e.appendChild(exCauseClass);
let message = itemRes[2];
if (message != null) {
e.appendChild(document.createTextNode(': '));
let exMessage = document.createElement('SPAN');
exMessage.className = exceptionMessageClass;
textRenderer(exMessage, 'text', message);
e.appendChild(exMessage);
}
} else {
this.rgxEnd.lastIndex = idx;
itemRes = this.rgxEnd.exec(s);
if (itemRes) {
// text like "... 83 common frames omitted"
this.appendStacktraceItems(e, traceItems, false);
traceItems.length = 0;
e.appendChild(document.createTextNode('\n'));
let dots = document.createElement('DIV');
dots.style.whiteSpace = 'pre-wrap';
dots.innerText = itemRes[0].substr(1);
e.appendChild(dots);
} else {
break;
}
}
}
idx += itemRes[0].length;
}
if (
idx < s.length &&
!(idx === s.length - 1 && s[idx] === '\n') // See ExceptionRendererTest.exceptionWithLineEnd()
) {
return null;
}
this.appendStacktraceItems(e, traceItems, true);
return [{start: headerMatch.index, end: idx, e}];
}
private appendStacktraceItems(e: HTMLElement, m: string[][], bigExpanderAtEnd: boolean) {
if (m.length === 0) { return; }
let nonHomeLines: string[][] = [];
for (let line of m) {
if (this.isHomePackage(line[JavaExceptionRenderer.EX_I_PACKAGE])) {
if (nonHomeLines.length <= 3) {
for (let l of nonHomeLines) { this.appendStacktraceItem(e, l); }
} else {
this.appendStacktraceItem(e, nonHomeLines[0]);
this.appendCollapsableStackTrace(
e,
nonHomeLines,
1,
nonHomeLines.length - 1,
false
);
this.appendStacktraceItem(e, nonHomeLines[nonHomeLines.length - 1]);
}
nonHomeLines.length = 0;
this.appendStacktraceItem(e, line);
} else {
nonHomeLines.push(line);
}
}
if (nonHomeLines.length > 0) {
this.appendStacktraceItem(e, nonHomeLines[0]);
if (nonHomeLines.length > 1) {
let i = 1;
if (nonHomeLines.length === m.length) {
// All lines are non-home
this.appendStacktraceItem(e, nonHomeLines[1]);
i = 2;
}
if (nonHomeLines.length - i > (bigExpanderAtEnd ? 2 : 1)) {
this.appendCollapsableStackTrace(
e,
nonHomeLines,
i,
nonHomeLines.length,
bigExpanderAtEnd
);
} else {
for (; i < nonHomeLines.length; i++) {
this.appendStacktraceItem(e, nonHomeLines[i]);
}
}
}
}
}
private appendCollapsableStackTrace(e: HTMLElement,
m: string[][],
start: number,
end: number,
bigExpander: boolean) {
if (start === end) { return; }
LvUtils.assert(start < end);
let collWrapper = document.createElement('DIV');
collWrapper.className = 'coll-wrapper collapsed';
if (bigExpander) {
let expanderDown = document.createElement('DIV');
expanderDown.className = 'ex-coll-expander-down coll-expander lv-virtual';
expanderDown.title = 'Expand ' + (end - start) + ' hidden elements';
(<SlElement>expanderDown).virtual = true;
collWrapper.appendChild(expanderDown);
} else {
let expanderWrapper = document.createElement('DIV');
expanderWrapper.className = 'ex-coll-plus-wrapper';
(<SlElement>expanderWrapper).virtual = true;
let expander = document.createElement('DIV');
expander.className = 'coll-expander';
expander.title = 'Expand ' + (end - start) + ' hidden elements';
expanderWrapper.appendChild(expander);
collWrapper.appendChild(expanderWrapper);
}
let collBody = document.createElement('DIV');
collBody.className = 'coll-body coll-body-1px ex-coll-body';
let collapser = document.createElement('DIV');
collapser.className = 'coll-collapser lv-virtual';
let collapserTop = document.createElement('DIV');
collapserTop.className = 'top';
collapser.appendChild(collapserTop);
let collapserMiddle = document.createElement('DIV');
collapserMiddle.className = 'middle';
collapser.appendChild(collapserMiddle);
let collapserBottom = document.createElement('DIV');
collapserBottom.className = 'down';
collapser.appendChild(collapserBottom);
collBody.appendChild(collapser);
for (let i = start; i < end; i++) {
this.appendStacktraceItem(collBody, m[i]);
}
collWrapper.appendChild(collBody);
e.appendChild(collWrapper);
}
private appendStacktraceItem(e: HTMLElement, m: string[]) {
e.appendChild(document.createTextNode('\n'));
let line = document.createElement('DIV');
line.className = 'ex-stacktrace-line';
line.appendChild(document.createTextNode('\tat '));
let methodName;
if (m[JavaExceptionRenderer.EX_I_SUBMITTED_FROM] != null) {
line.appendChild(document.createTextNode(m[JavaExceptionRenderer.EX_I_SUBMITTED_FROM]));
methodName = '';
} else {
if (m[JavaExceptionRenderer.EX_I_CLASSLOADER]) {
let classLoaderSpan = document.createElement('SPAN');
classLoaderSpan.innerText = m[JavaExceptionRenderer.EX_I_CLASSLOADER];
classLoaderSpan.classList.add('ex-classloader');
line.appendChild(classLoaderSpan);
}
if (m[JavaExceptionRenderer.EX_I_MODULE]) {
let moduleSpan = document.createElement('SPAN');
moduleSpan.innerText = m[JavaExceptionRenderer.EX_I_MODULE];
moduleSpan.classList.add('ex-module');
line.appendChild(moduleSpan);
}
let packageName = m[JavaExceptionRenderer.EX_I_PACKAGE];
if (packageName) {
LvUtils.assert(packageName.endsWith('.'));
let packageSpan = document.createElement('SPAN');
packageSpan.innerText = packageName.substring(0, packageName.length - 1);
packageSpan.classList.add('ex-stacktrace-package');
if (this.isHomePackage(packageName)) {
packageSpan.classList.add('ex-stacktrace-package-home');
}
line.appendChild(packageSpan);
let dotBeforeClassSpan = document.createElement('SPAN');
dotBeforeClassSpan.innerText = '.';
dotBeforeClassSpan.className = 'dot-before-class';
line.appendChild(dotBeforeClassSpan);
}
let classSpan = document.createElement('SPAN');
classSpan.innerText = m[JavaExceptionRenderer.EX_I_CLASS];
classSpan.className = 'ex-stacktrace-class';
line.appendChild(classSpan);
methodName = m[JavaExceptionRenderer.EX_I_METHOD];
}
let methodSpan = document.createElement('SPAN');
methodSpan.innerText = '.' + methodName + '(';
methodSpan.className = 'ex-stacktrace-method';
line.appendChild(methodSpan);
let srcSpan = document.createElement('SPAN');
srcSpan.innerText = m[JavaExceptionRenderer.EX_I_SOURCE];
srcSpan.className = exceptionFileNameClass;
line.appendChild(srcSpan);
let finalBracketSpan = document.createElement('SPAN');
finalBracketSpan.innerText = ')';
finalBracketSpan.className = 'ex-stacktrace-method';
line.appendChild(finalBracketSpan);
if (m[JavaExceptionRenderer.EX_I_JARNAME]) {
let jarnameSpan = document.createElement('SPAN');
jarnameSpan.innerText = m[JavaExceptionRenderer.EX_I_JARNAME];
jarnameSpan.className = exceptionFileNameClass;
line.appendChild(jarnameSpan);
}
e.appendChild(line);
}
private isHomePackage(pkg: string): boolean {
if (!pkg) { return false; }
for (let p of this.homePackages) {
if (pkg.startsWith(p)) { return true; }
}
return false;
}
} | 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 { PersistedState } from './persisted_state';
describe('Persisted State Provider', () => {
describe('state creation', () => {
let persistedState: PersistedState;
test('should create an empty state instance', () => {
persistedState = new PersistedState();
expect(persistedState.get()).toEqual({});
});
test('should create a state instance with data', () => {
const val = { red: 'blue' };
persistedState = new PersistedState(val);
expect(persistedState.get()).toEqual(val);
// ensure we get a copy of the state, not the actual state object
expect(persistedState.get()).not.toBe(val);
});
test('should create a copy of the state passed in', () => {
const val = { red: 'blue' };
persistedState = new PersistedState(val);
expect(persistedState.get()).toEqual(val);
expect(persistedState.get()).not.toBe(val);
});
test('should throw if given an invalid value', () => {
expect(() => new PersistedState('bananas')).toThrow(Error);
});
});
describe('mutation', () => {
test('should not mutate the internal object', () => {
const persistedStateValue = { hello: 'world' };
const insertedObj = { farewell: 'cruel world' };
const persistedState = new PersistedState(persistedStateValue);
expect({
...persistedState.get(),
...insertedObj,
}).toHaveProperty('farewell');
expect(persistedState.get()).not.toHaveProperty('farewell');
});
});
describe('JSON importing and exporting', () => {
let persistedStateValue: any;
beforeEach(() => {
persistedStateValue = { one: 1, two: 2, 'meaning of life': 42 };
});
describe('exporting state to JSON', () => {
test('should return the full JSON representation', () => {
const persistedState = new PersistedState(persistedStateValue);
const json = persistedState.toJSON();
expect(json).toEqual(persistedStateValue);
});
});
describe('importing state from JSON string (hydration)', () => {
test('should set the state from JSON string input', () => {
const stateJSON = JSON.stringify(persistedStateValue);
const persistedState = new PersistedState();
expect(persistedState.get()).toEqual({});
persistedState.fromString(stateJSON);
expect(persistedState.get()).toEqual(persistedStateValue);
});
});
});
describe('get state', () => {
test('should perform deep gets with various formats', () => {
const obj = {
red: {
green: {
blue: 'yellow',
},
},
orange: [1, 2, false, 4],
purple: {
violet: '',
},
};
const persistedState = new PersistedState(obj);
expect(persistedState.get()).toEqual(obj);
expect(persistedState.get('red')).toEqual({ green: { blue: 'yellow' } });
expect(persistedState.get('red.green')).toEqual({ blue: 'yellow' });
expect(persistedState.get('red[green]')).toEqual({ blue: 'yellow' });
expect(persistedState.get(['red', 'green'])).toEqual({ blue: 'yellow' });
expect(persistedState.get('red.green.blue')).toEqual('yellow');
expect(persistedState.get('red[green].blue')).toEqual('yellow');
expect(persistedState.get('red.green[blue]')).toEqual('yellow');
expect(persistedState.get('red[green][blue]')).toEqual('yellow');
expect(persistedState.get('red.green.blue')).toEqual('yellow');
expect(persistedState.get('orange')).toEqual([1, 2, false, 4]);
expect(persistedState.get('orange[0]')).toEqual(1);
expect(persistedState.get('orange[2]')).toEqual(false);
expect(persistedState.get('purple')).toEqual({ violet: '' });
});
test('should perform deep gets with arrays', () => {
const persistedState = new PersistedState({
hello: { nouns: ['world', 'humans', 'everyone'] },
});
expect(persistedState.get()).toEqual({ hello: { nouns: ['world', 'humans', 'everyone'] } });
expect(persistedState.get('hello')).toEqual({ nouns: ['world', 'humans', 'everyone'] });
expect(persistedState.get('hello.nouns')).toEqual(['world', 'humans', 'everyone']);
});
});
describe('set state', () => {
describe('path format support', () => {
test('should create deep objects from dot notation', () => {
const persistedState = new PersistedState();
persistedState.set('one.two.three', 4);
expect(persistedState.get()).toEqual({ one: { two: { three: 4 } } });
});
test('should create deep objects from array notation', () => {
const persistedState = new PersistedState();
persistedState.set('one[two][three]', 4);
expect(persistedState.get()).toEqual({ one: { two: { three: 4 } } });
});
test('should create deep objects from arrays', () => {
const persistedState = new PersistedState();
persistedState.set(['one', 'two', 'three'], 4);
expect(persistedState.get()).toEqual({ one: { two: { three: 4 } } });
});
test('should create deep objects with an existing path', () => {
const persistedState = new PersistedState({}, 'deep.path');
persistedState.set('green[red].blue', 4);
expect(persistedState.get()).toEqual({ green: { red: { blue: 4 } } });
});
});
describe('simple replace operations', () => {
let persistedState;
test('should replace value with string', () => {
persistedState = new PersistedState({ hello: 'world' });
expect(persistedState.get()).toEqual({ hello: 'world' });
persistedState.set('hello', 'fare thee well');
expect(persistedState.get()).toEqual({ hello: 'fare thee well' });
});
test('should replace value with array', () => {
persistedState = new PersistedState({ hello: ['world', 'everyone'] });
expect(persistedState.get()).toEqual({ hello: ['world', 'everyone'] });
persistedState.set('hello', ['people']);
expect(persistedState.get()).toEqual({ hello: ['people'] });
});
test('should replace value with object', () => {
persistedState = new PersistedState({ hello: 'world' });
expect(persistedState.get()).toEqual({ hello: 'world' });
persistedState.set('hello', { message: 'fare thee well' });
expect(persistedState.get()).toEqual({ hello: { message: 'fare thee well' } });
});
test('should replace value with object, removing old properties', () => {
persistedState = new PersistedState({ hello: { message: 'world' } });
expect(persistedState.get()).toEqual({ hello: { message: 'world' } });
persistedState.set('hello', { length: 5 });
expect(persistedState.get()).toEqual({ hello: { length: 5 } });
});
});
describe('deep replace operations', () => {
let persistedState;
test('should append to the object', () => {
persistedState = new PersistedState({ hello: { message: 'world' } });
expect(persistedState.get()).toEqual({ hello: { message: 'world' } });
persistedState.set('hello.length', 5);
expect(persistedState.get()).toEqual({ hello: { message: 'world', length: 5 } });
});
test('should change the value in the array', () => {
persistedState = new PersistedState({ hello: { nouns: ['world', 'humans', 'everyone'] } });
persistedState.set('hello.nouns[1]', 'aliens');
expect(persistedState.get()).toEqual({ hello: { nouns: ['world', 'aliens', 'everyone'] } });
expect(persistedState.get('hello')).toEqual({ nouns: ['world', 'aliens', 'everyone'] });
expect(persistedState.get('hello.nouns')).toEqual(['world', 'aliens', 'everyone']);
});
});
});
describe('internal state tracking', () => {
test('should be an empty object', () => {
const persistedState = new PersistedState();
expect(persistedState).toHaveProperty('_defaultState', {});
});
test('should store the default state value', () => {
const val = { one: 1, two: 2 };
const persistedState = new PersistedState(val);
expect(persistedState).toHaveProperty('_defaultState', val);
});
test('should keep track of changes', () => {
const val = { one: 1, two: 2 };
const persistedState = new PersistedState(val);
persistedState.set('two', 22);
expect(persistedState).toHaveProperty('_defaultState', val);
expect(persistedState).toHaveProperty('_changedState', { two: 22 });
});
});
describe('events', () => {
let persistedState: PersistedState;
let emitSpy: jest.SpyInstance;
const getByType = (type: string): any[] => {
return emitSpy.mock.calls.filter(([callType]) => callType === type);
};
const watchEmitter = (state: any) => {
return jest.spyOn(state, 'emit');
};
beforeEach(() => {
persistedState = new PersistedState({ checker: { events: 'event tests' } });
emitSpy = watchEmitter(persistedState);
});
afterEach(() => {
emitSpy.mockRestore();
});
test('should emit set when setting values', () => {
expect(getByType('set')).toHaveLength(0);
persistedState.set('checker.time', 'now');
expect(getByType('set')).toHaveLength(1);
});
test('should not emit when setting value silently', () => {
expect(getByType('set')).toHaveLength(0);
persistedState.setSilent('checker.time', 'now');
expect(getByType('set')).toHaveLength(0);
});
test('should emit change when changing values', () => {
expect(getByType('change')).toHaveLength(0);
persistedState.set('checker.time', 'now');
expect(getByType('change')).toHaveLength(1);
});
test('should not emit when changing values silently', () => {
expect(getByType('change')).toHaveLength(0);
persistedState.setSilent('checker.time', 'now');
expect(getByType('change')).toHaveLength(0);
});
test('should not emit change when values are identical', () => {
expect(getByType('change')).toHaveLength(0);
// check both forms of setting the same value
persistedState.set('checker', { events: 'event tests' });
expect(getByType('change')).toHaveLength(0);
persistedState.set('checker.events', 'event tests');
expect(getByType('change')).toHaveLength(0);
});
test('should emit change when values change', () => {
expect(getByType('change')).toHaveLength(0);
persistedState.set('checker.events', 'i changed');
expect(getByType('change')).toHaveLength(1);
});
});
}); | the_stack |
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
Input,
isDevMode,
OnDestroy,
OnInit,
Output,
Renderer2,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import { TsWindowService } from '@terminus/ngx-tools/browser';
import {
TsStyleThemeTypes,
tsStyleThemeTypesArray,
} from '@terminus/ui/utilities';
// Unique ID for each instance
let nextUniqueId = 0;
/**
* Define the allowed {@link TsButtonComponent} action types
*/
export type TsButtonActionTypes
= 'Button'
| 'Submit'
| 'Menu'
| 'Reset'
;
/**
* Define the allowed {@link TsButtonComponent} action types
*/
export type TsButtonFunctionTypes
= 'button'
| 'search'
| 'submit'
;
/**
* Define the allowed {@link TsButtonComponent} format types
*/
export type TsButtonFormatTypes
= 'filled'
| 'hollow'
| 'collapsable'
| 'collapsible'
;
/**
* @internal
*/
export const tsButtonFormatTypesArray = [
'filled',
'hollow',
// @deprecated Use 'collapsible' instead.
'collapsable',
'collapsible',
];
const DEFAULT_COLLAPSE_DELAY_MS = 4000;
/**
* A presentational component to render a button
*
* #### QA CSS CLASSES
* - `qa-button`: Placed on the button element used for this component
*
* @example
* <ts-button
* actionName="Submit"
* theme="primary"
* format="filled"
* buttonType="search"
* iconName="search"
* [isDisabled]="false"
* [showProgress]="true"
* [collapsed]="false"
* collapseDelay="500"
* tabIndex="2"
* (clicked)="myMethod($event)"
* >Click Me!</ts-button>
*
* <example-url>https://getterminus.github.io/ui-demos-release/components/button</example-url>
*/
@Component({
selector: 'ts-button',
templateUrl: './button.component.html',
styleUrls: ['./button.component.scss'],
host: { class: 'ts-button' },
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
exportAs: 'tsButton',
})
export class TsButtonComponent implements OnInit, OnDestroy {
/**
* Store a reference to the timeout needed for collapsible buttons
*/
private collapseTimeoutId!: number;
/**
* Define the delay before the rounded button automatically collapses
*/
public collapseDelay: number | undefined;
/**
* The flag that defines if the button is collapsed or expanded
*/
public isCollapsed = false;
/**
* A flag to determine if click events should be intercepted.
*
* Set by {@link TsConfirmationDirective}
*/
public interceptClick = false;
/**
* Store the original event from a click (used when `interceptClick` is true)
*
* @internal
*
* Used by {@link TsConfirmationDirective}
*/
public originalClickEvent!:MouseEvent;
/**
* Define the default component ID
*/
public readonly uid = `ts-button-${nextUniqueId++}`;
/**
* Getter returning a boolean based on both the component `isDisabled` flag and the FormControl's disabled status
*/
public get shouldBeDisabled(): boolean {
return this.isDisabled || this.showProgress;
}
/**
* Provide access to the inner button element
*/
@ViewChild('button', { static: true })
public button!: ElementRef;
/**
* Define the action for the aria-label. {@link TsButtonActionTypes}
*/
@Input()
public actionName: TsButtonActionTypes = 'Button';
/**
* Define the button type. {@link TsButtonFunctionTypes}
*/
@Input()
public buttonType: TsButtonFunctionTypes = 'button';
/**
* Define the collapsed value and trigger the delay if needed
*
* @param value
*/
@Input()
public set collapsed(value: boolean) {
this.isCollapsed = value;
// If the value is `false` and a collapse delay is set
if (!value && this.collapseDelay) {
// Trigger the delayed close
this.collapseWithDelay(this.collapseDelay);
}
}
/**
* Define the button format. {@link TsButtonFormatTypes}
*
* @param value
*/
@Input()
public set format(value: TsButtonFormatTypes) {
if (!value) {
return;
}
// Verify the value is allowed
if (tsButtonFormatTypesArray.indexOf(value) < 0 && isDevMode()) {
// eslint-disable-next-line no-console
console.warn(`TsButtonComponent: "${value}" is not an allowed format. See TsButtonFormatTypes for available options.`);
return;
}
if (value === 'collapsable' && isDevMode()) {
// eslint-disable-next-line no-console
console.warn(`TsButtonComponent: "collapsable" has been deprecated. Please use "collapsible" instead.`);
}
this._format = value;
if (this._format === 'collapsable' || this._format === 'collapsible') {
if (!this.collapseDelay) {
this.collapseDelay = DEFAULT_COLLAPSE_DELAY_MS;
}
} else if (this.collapseDelay) {
// If the format is NOT collapsible, remove the delay
this.collapseDelay = undefined;
}
this.updateClasses(value);
}
public get format(): TsButtonFormatTypes {
return this._format;
}
private _format!: TsButtonFormatTypes;
/**
* Define a Material icon to include
*/
@Input()
public iconName: string | undefined;
/**
* Define if the button is disabled
*/
@Input()
public isDisabled = false;
/**
* Define an ID for the component
*
* @param value
*/
@Input()
public set id(value: string) {
this._id = value || this.uid;
}
public get id(): string {
return this._id;
}
protected _id: string = this.uid;
/**
* Define if the progress indicator should show
*/
@Input()
public showProgress = false;
/**
* Define the tabindex for the button
*/
@Input()
public tabIndex = 0;
/**
* Define the theme
*
* @param value
*/
@Input()
public set theme(value: TsStyleThemeTypes) {
if (!value) {
return;
}
// Verify the value is allowed
if (tsStyleThemeTypesArray.indexOf(value) < 0 && isDevMode()) {
// eslint-disable-next-line no-console
console.warn(`TsButtonComponent: "${value}" is not an allowed theme. See TsStyleThemeTypes for available options.`);
return;
}
this._theme = value;
this.updateClasses(value);
}
public get theme(): TsStyleThemeTypes {
return this._theme;
}
private _theme!: TsStyleThemeTypes;
/**
* Pass the click event through to the parent
*/
@Output()
public readonly clicked = new EventEmitter<MouseEvent>();
constructor(
private changeDetectorRef: ChangeDetectorRef,
private windowService: TsWindowService,
private renderer: Renderer2,
) {}
/**
* Collapse after delay (if set)
*/
public ngOnInit(): void {
if (this.collapseDelay) {
this.collapseTimeoutId = this.collapseWithDelay(this.collapseDelay);
}
// NOTE: Update classes in ngOnInit because this.button is only available here
// It there is a theme then update classes
// Otherwise set a default theme
if (this.theme) {
this.updateClasses(this.theme);
} else {
this.theme = 'primary';
}
// It there is a format then update classes
// Otherwise set a filled format
if (this.format) {
this.updateClasses(this.format);
} else {
this.format = 'filled';
}
// If the format is `collapsible`, verify an `iconName` is set
if ((this.format === 'collapsable' || this.format === 'collapsible') && !this.iconName && isDevMode()) {
throw new Error('`iconName` must be defined for collapsible buttons.');
}
}
/**
* Clear any existing timeout
*/
public ngOnDestroy(): void {
// istanbul ignore else
if (this.collapseTimeoutId) {
this.windowService.nativeWindow.clearTimeout(this.collapseTimeoutId);
}
}
/**
* Handle button clicks
*
* @internal
*
* @param event - The MouseEvent
*/
public clickedButton(event: MouseEvent): void {
if (this.interceptClick) {
// Save the original event but don't emit the originalClickEvent
this.originalClickEvent = event;
} else {
// Allow the click to propagate
this.clicked.emit(event);
}
}
/**
* Collapse the button after a delay
*
* NOTE: I'm not entirely sure why this `detectChanges` is needed. Supposedly zone.js should be patching setTimeout automatically.
*
* @param delay - The time to delay before collapsing the button
* @returns The ID of the timeout
*/
private collapseWithDelay(delay: number): number {
return this.windowService.nativeWindow.setTimeout(() => {
this.isCollapsed = true;
this.changeDetectorRef.detectChanges();
}, delay);
}
/**
* Update button classes (theme|format)
*
* @param classname - The classname to add to the button
*/
private updateClasses(classname: string): void {
const themeOptions = ['primary', 'accent', 'warn'];
const formatOptions = ['filled', 'hollow', 'collapsable', 'collapsible'];
const isTheme = themeOptions.indexOf(classname) >= 0;
const isFormat = formatOptions.indexOf(classname) >= 0;
// NOTE: Underscore dangle name controlled by Material
// NOTE: This 'any' is needed since the `mat-raised-button` directive overwrites elementRef
// NOTE: Need to check if button is already available (could be undefined during initialization)
// eslint-disable-next-line @typescript-eslint/no-explicit-any, no-underscore-dangle
const buttonEl = this.button ? (this.button as any)._elementRef.nativeElement : null;
const themeClasses = themeOptions.map(theme => `c-button--${theme}`);
const formatClasses = formatOptions.map(format => `c-button--${format}`);
// If dealing with a theme class. Update only in case if button is available
// istanbul ignore else
if (isTheme && buttonEl) {
for (const themeClass of themeClasses) {
this.renderer.removeClass(buttonEl, themeClass);
}
this.renderer.addClass(buttonEl, `c-button--${classname}`);
}
// Update only in case if button is available
// istanbul ignore else
if (isFormat && buttonEl) {
for (const formatClass of formatClasses) {
this.renderer.removeClass(buttonEl, formatClass);
}
this.renderer.addClass(buttonEl, `c-button--${classname}`);
}
}
} | the_stack |
import BScroll from '@better-scroll/core'
import { IndicatorOptions, Ratio, Postion, ValueSign } from './types'
import {
EventRegister,
EventEmitter,
getRect,
getClientSize,
getNow,
between,
Probe,
TouchEvent,
style,
} from '@better-scroll/shared-utils'
const resolveRatioOption = (ratioConfig?: Ratio) => {
let ret = {
ratioX: 0,
ratioY: 0,
}
/* istanbul ignore if */
if (!ratioConfig) {
return ret
}
if (typeof ratioConfig === 'number') {
ret.ratioX = ret.ratioY = ratioConfig
} else if (typeof ratioConfig === 'object' && ratioConfig) {
ret.ratioX = ratioConfig.x || 0
ret.ratioY = ratioConfig.y || 0
}
return ret
}
const handleBubbleAndCancelable = (e: TouchEvent) => {
e.preventDefault()
e.stopPropagation()
}
export default class Indicator {
wrapper: HTMLElement
indicatorEl: HTMLElement
maxScrollX: number
minScrollX: number
ratioX: number
maxScrollY: number
minScrollY: number
translateXSign: ValueSign
translateYSign: ValueSign
ratioY: number
currentPos: Postion = {
x: 0,
y: 0,
}
moved: boolean
startTime: number
initiated: boolean
lastPointX: number
lastPointY: number
startEventRegister: EventRegister
moveEventRegister: EventRegister
endEventRegister: EventRegister
hooksFn: [EventEmitter, string, Function][] = []
constructor(public scroll: BScroll, public options: IndicatorOptions) {
this.handleDOM()
this.handleHooks()
this.handleInteractive()
}
private handleDOM() {
const {
relationElement,
relationElementHandleElementIndex = 0,
} = this.options
this.wrapper = relationElement
this.indicatorEl = this.wrapper.children[
relationElementHandleElementIndex
] as HTMLElement
}
private handleHooks() {
const scroll = this.scroll
const scrollHooks = scroll.hooks
const translaterHooks = scroll.scroller.translater.hooks
const animaterHooks = scroll.scroller.animater.hooks
this.registerHooks(
scrollHooks,
scrollHooks.eventTypes.refresh,
this.refresh
)
this.registerHooks(
translaterHooks,
translaterHooks.eventTypes.translate,
(pos: Postion) => {
this.updatePosition(pos)
}
)
this.registerHooks(
animaterHooks,
animaterHooks.eventTypes.time,
this.transitionTime
)
this.registerHooks(
animaterHooks,
animaterHooks.eventTypes.timeFunction,
this.transitionTimingFunction
)
}
private transitionTime(time: number = 0) {
this.indicatorEl.style[style.transitionDuration as any] = time + 'ms'
}
private transitionTimingFunction(easing: string) {
this.indicatorEl.style[style.transitionTimingFunction as any] = easing
}
private handleInteractive() {
if (this.options.interactive !== false) {
this.registerEvents()
}
}
private registerHooks(hooks: EventEmitter, name: string, handler: Function) {
hooks.on(name, handler, this)
this.hooksFn.push([hooks, name, handler])
}
private registerEvents() {
const { disableMouse, disableTouch } = this.scroll.options
const startEvents = []
const moveEvents = []
const endEvents = []
if (!disableMouse) {
startEvents.push({
name: 'mousedown',
handler: this.start.bind(this),
})
moveEvents.push({
name: 'mousemove',
handler: this.move.bind(this),
})
endEvents.push({
name: 'mouseup',
handler: this.end.bind(this),
})
}
if (!disableTouch) {
startEvents.push({
name: 'touchstart',
handler: this.start.bind(this),
})
moveEvents.push({
name: 'touchmove',
handler: this.move.bind(this),
})
endEvents.push(
{
name: 'touchend',
handler: this.end.bind(this),
},
{
name: 'touchcancel',
handler: this.end.bind(this),
}
)
}
this.startEventRegister = new EventRegister(this.indicatorEl, startEvents)
this.moveEventRegister = new EventRegister(window, moveEvents)
this.endEventRegister = new EventRegister(window, endEvents)
}
refresh() {
const {
x,
y,
hasHorizontalScroll,
hasVerticalScroll,
maxScrollX: maxBScrollX,
maxScrollY: maxBScrollY,
} = this.scroll
const { ratioX, ratioY } = resolveRatioOption(this.options.ratio)
const { width: wrapperWidth, height: wrapperHeight } = getClientSize(
this.wrapper
)
const { width: indicatorWidth, height: indicatorHeight } = getRect(
this.indicatorEl
)
if (hasHorizontalScroll) {
this.maxScrollX = wrapperWidth - indicatorWidth
this.translateXSign =
this.maxScrollX > 0 ? ValueSign.Positive : ValueSign.NotPositive
this.minScrollX = 0
// ensure positive
this.ratioX = ratioX ? ratioX : Math.abs(this.maxScrollX / maxBScrollX)
}
if (hasVerticalScroll) {
this.maxScrollY = wrapperHeight - indicatorHeight
this.translateYSign =
this.maxScrollY > 0 ? ValueSign.Positive : ValueSign.NotPositive
this.minScrollY = 0
this.ratioY = ratioY ? ratioY : Math.abs(this.maxScrollY / maxBScrollY)
}
this.updatePosition({
x,
y,
})
}
private start(e: TouchEvent) {
if (this.BScrollIsDisabled()) {
return
}
let point = (e.touches ? e.touches[0] : e) as Touch
handleBubbleAndCancelable(e)
this.initiated = true
this.moved = false
this.lastPointX = point.pageX
this.lastPointY = point.pageY
this.startTime = getNow()
this.scroll.scroller.hooks.trigger(
this.scroll.scroller.hooks.eventTypes.beforeScrollStart
)
}
private BScrollIsDisabled() {
return !this.scroll.enabled
}
private move(e: TouchEvent) {
if (!this.initiated) {
return
}
let point = (e.touches ? e.touches[0] : e) as Touch
const pointX = point.pageX
const pointY = point.pageY
handleBubbleAndCancelable(e)
let deltaX = pointX - this.lastPointX
let deltaY = pointY - this.lastPointY
this.lastPointX = pointX
this.lastPointY = pointY
if (!this.moved && !this.indicatorNotMoved(deltaX, deltaY)) {
this.moved = true
this.scroll.scroller.hooks.trigger(
this.scroll.scroller.hooks.eventTypes.scrollStart
)
}
if (this.moved) {
const newPos = this.getBScrollPosByRatio(this.currentPos, deltaX, deltaY)
this.syncBScroll(newPos)
}
}
private end(e: TouchEvent) {
if (!this.initiated) {
return
}
this.initiated = false
handleBubbleAndCancelable(e)
if (this.moved) {
const { x, y } = this.scroll
this.scroll.scroller.hooks.trigger(
this.scroll.scroller.hooks.eventTypes.scrollEnd,
{
x,
y,
}
)
}
}
private getBScrollPosByRatio(
currentPos: Postion,
deltaX: number,
deltaY: number
) {
const { x: currentX, y: currentY } = currentPos
const {
hasHorizontalScroll,
hasVerticalScroll,
minScrollX: BScrollMinScrollX,
maxScrollX: BScrollMaxScrollX,
minScrollY: BScrollMinScrollY,
maxScrollY: BScrollMaxScrollY,
} = this.scroll
let { x, y } = this.scroll
if (hasHorizontalScroll) {
const newPosX = between(
currentX + deltaX,
Math.min(this.minScrollX, this.maxScrollX),
Math.max(this.minScrollX, this.maxScrollX)
)
const roundX = Math.round((newPosX / this.ratioX) * this.translateXSign)
x = between(roundX, BScrollMaxScrollX, BScrollMinScrollX)
}
if (hasVerticalScroll) {
const newPosY = between(
currentY + deltaY,
Math.min(this.minScrollY, this.maxScrollY),
Math.max(this.minScrollY, this.maxScrollY)
)
const roundY = Math.round((newPosY / this.ratioY) * this.translateYSign)
y = between(roundY, BScrollMaxScrollY, BScrollMinScrollY)
}
return { x, y }
}
private indicatorNotMoved(deltaX: number, deltaY: number): boolean {
const { x, y } = this.currentPos
const xNotMoved =
(x === this.minScrollX && deltaX <= 0) ||
(x === this.maxScrollX && deltaX >= 0)
const yNotMoved =
(y === this.minScrollY && deltaY <= 0) ||
(y === this.maxScrollY && deltaY >= 0)
return xNotMoved && yNotMoved
}
private syncBScroll(newPos: Postion) {
const timestamp = getNow()
const { options, scroller } = this.scroll
const { probeType, momentumLimitTime } = options
scroller.translater.translate(newPos)
// dispatch scroll in interval time
if (timestamp - this.startTime > momentumLimitTime) {
this.startTime = timestamp
if (probeType === Probe.Throttle) {
scroller.hooks.trigger(scroller.hooks.eventTypes.scroll, newPos)
}
}
// dispatch scroll all the time
if (probeType > Probe.Throttle) {
scroller.hooks.trigger(scroller.hooks.eventTypes.scroll, newPos)
}
}
updatePosition(BScrollPos: Postion) {
const newIndicatorPos = this.getIndicatorPosByRatio(BScrollPos)
this.applyTransformProperty(newIndicatorPos)
this.currentPos = { ...newIndicatorPos }
}
private applyTransformProperty(pos: Postion) {
const translateZ = this.scroll.options.translateZ
const transformProperties = [
`translateX(${pos.x}px)`,
`translateY(${pos.y}px)`,
`${translateZ}`,
]
this.indicatorEl.style[style.transform as any] = transformProperties.join(
' '
)
}
private getIndicatorPosByRatio(BScrollPos: Postion) {
const { x, y } = BScrollPos
const { hasHorizontalScroll, hasVerticalScroll } = this.scroll
const position = { ...this.currentPos }
if (hasHorizontalScroll) {
const roundX = Math.round(this.ratioX * x * this.translateXSign)
// maybe maxScrollX is negative
position.x = between(
roundX,
Math.min(this.minScrollX, this.maxScrollX),
Math.max(this.minScrollX, this.maxScrollX)
)
}
if (hasVerticalScroll) {
const roundY = Math.round(this.ratioY * y * this.translateYSign)
// maybe maxScrollY is negative
position.y = between(
roundY,
Math.min(this.minScrollY, this.maxScrollY),
Math.max(this.minScrollY, this.maxScrollY)
)
}
return position
}
destroy() {
if (this.options.interactive !== false) {
this.startEventRegister.destroy()
this.moveEventRegister.destroy()
this.endEventRegister.destroy()
}
this.hooksFn.forEach((item) => {
const hooks = item[0]
const hooksName = item[1]
const handlerFn = item[2]
hooks.off(hooksName, handlerFn)
})
this.hooksFn.length = 0
}
} | the_stack |
import {
defineComponent,
PropType,
reactive,
onMounted,
Teleport,
watch,
onBeforeUnmount,
CSSProperties,
computed
} from 'vue';
import {
allToolbar,
highlightUrl,
iconfontUrl,
prettierUrl,
cropperUrl,
screenfullUrl,
mermaidUrl,
katexJsUrl,
katexCssUrl
} from './config';
import { useKeyBoard, useProvide } from './capi';
import ToolBar from './layouts/Toolbar';
import Content from './layouts/Content';
import Catalog from './layouts/Catalog';
import bus from './utils/event-bus';
import './styles/index.less';
import '@vavt/markdown-theme/css/all.css';
declare global {
interface Window {
hljs: any;
prettier: any;
prettierPlugins: any;
Cropper: any;
screenfull: any;
mermaid: any;
}
}
export interface ToolbarTips {
bold?: string;
underline?: string;
italic?: string;
strikeThrough?: string;
title?: string;
sub?: string;
sup?: string;
quote?: string;
unorderedList?: string;
orderedList?: string;
codeRow?: string;
code?: string;
link?: string;
image?: string;
table?: string;
mermaid?: string;
katex?: string;
revoke?: string;
next?: string;
save?: string;
prettier?: string;
pageFullscreen?: string;
fullscreen?: string;
preview?: string;
htmlPreview?: string;
catalog?: string;
github?: string;
'-'?: string;
'='?: string;
}
export interface StaticTextDefaultValue {
toolbarTips?: ToolbarTips;
titleItem?: {
h1?: string;
h2?: string;
h3?: string;
h4?: string;
h5?: string;
h6?: string;
};
imgTitleItem?: {
link: string;
upload: string;
clip2upload: string;
};
linkModalTips?: {
title?: string;
descLable?: string;
descLablePlaceHolder?: string;
urlLable?: string;
UrlLablePlaceHolder?: string;
buttonOK?: string;
};
clipModalTips?: {
title?: string;
buttonUpload?: string;
};
copyCode?: {
text?: string;
tips?: string;
};
mermaid?: {
// 流程图
flow?: string;
// 时序图
sequence?: string;
// 甘特图
gantt?: string;
// 类图
class?: string;
// 状态图
state?: string;
// 饼图
pie?: string;
// 关系图
relationship?: string;
// 旅程图
journey?: string;
};
katex?: {
inline: string;
block: string;
};
}
export interface StaticTextDefault {
'zh-CN': StaticTextDefaultValue;
'en-US': StaticTextDefaultValue;
}
export type StaticTextDefaultKey = keyof StaticTextDefault;
export type ToolbarNames = keyof ToolbarTips;
export interface SettingType {
pageFullScreen: boolean;
fullscreen: boolean;
preview: boolean;
htmlPreview: boolean;
}
export const prefix = 'md';
export interface HeadList {
text: string;
level: 1 | 2 | 3 | 4 | 5 | 6;
}
export type PreviewThemes = 'default' | 'github' | 'vuepress';
// marked heading方法
export type MarkedHeading = (
text: string,
level: 1 | 2 | 3 | 4 | 5 | 6,
raw: string,
// marked@2.1.3
slugger: {
seen: { [slugValue: string]: number };
slug(
value: string,
options?: {
dryrun: boolean;
}
): string;
}
) => string;
export type MarkedHeadingId = (text: string, level: number) => string;
const markedHeadingId: MarkedHeadingId = (text) => text;
const props = {
modelValue: {
type: String as PropType<string>,
default: ''
},
// 主题,支持light和dark
theme: {
type: String as PropType<'light' | 'dark'>,
default: 'light'
},
// 外层扩展类名
editorClass: {
type: String,
default: ''
},
// 如果项目中有使用highlight.js或者没有外网访问权限,可以直接传递实例hljs并且手动导入css
hljs: {
type: Object,
default: null
},
// 可以手动提供highlight.js的cdn链接
highlightJs: {
type: String as PropType<string>,
default: highlightUrl.js
},
highlightCss: {
type: String as PropType<string>,
default: ''
},
historyLength: {
type: Number as PropType<number>,
default: 10
},
onChange: {
type: Function as PropType<(v: string) => void>
},
onSave: {
type: Function as PropType<(v: string) => void>
},
onUploadImg: {
type: Function as PropType<
(files: FileList, callBack: (urls: string[]) => void) => void
>
},
pageFullScreen: {
type: Boolean as PropType<boolean>,
default: false
},
preview: {
type: Boolean as PropType<boolean>,
default: true
},
htmlPreview: {
type: Boolean as PropType<boolean>,
default: false
},
previewOnly: {
type: Boolean as PropType<boolean>,
default: false
},
language: {
type: String as PropType<StaticTextDefaultKey | string>,
default: 'zh-CN'
},
// 语言扩展,以标准的形式定义内容,设置language为key值即可替换
languageUserDefined: {
type: Object as PropType<{ [key: string]: StaticTextDefaultValue }>,
default: () => ({})
},
// 工具栏选择显示
toolbars: {
type: Array as PropType<Array<ToolbarNames>>,
default: allToolbar
},
// 工具栏选择不显示
toolbarsExclude: {
type: Array as PropType<Array<ToolbarNames>>,
default: []
},
prettier: {
type: Boolean as PropType<boolean>,
default: true
},
prettierCDN: {
type: String as PropType<string>,
default: prettierUrl.main
},
prettierMDCDN: {
type: String as PropType<string>,
default: prettierUrl.markdown
},
// html变化事件
onHtmlChanged: {
type: Function as PropType<(h: string) => void>
},
// 图片裁剪对象
Cropper: {
type: Function,
default: null
},
cropperCss: {
type: String as PropType<string>,
default: cropperUrl.css
},
cropperJs: {
type: String as PropType<string>,
default: cropperUrl.js
},
iconfontJs: {
type: String as PropType<string>,
default: iconfontUrl
},
onGetCatalog: {
type: Function as PropType<(list: HeadList[]) => void>
},
editorId: {
type: String as PropType<string>,
default: 'md-editor-v3'
},
tabWidth: {
type: Number as PropType<number>,
default: 2
},
// 预览中代码是否显示行号
showCodeRowNumber: {
type: Boolean as PropType<boolean>,
default: false
},
screenfull: {
type: Object,
default: null
},
screenfullJs: {
type: String as PropType<string>,
default: screenfullUrl
},
// 预览内容样式
previewTheme: {
type: String as PropType<PreviewThemes>,
default: 'default'
},
markedHeading: {
type: Function as PropType<MarkedHeading>,
default: (text: string, level: number, raw: string) => {
// 我们默认同一级别的标题,你不会定义两个相同的
const id = markedHeadingId(raw, level);
// 如果标题有markdown语法内容,会按照该语法添加标题,而不再自定义,但是仍然支持目录定位
if (text !== raw) {
return `<h${level} id="${id}">${text}</h${level}>`;
} else {
return `<h${level} id="${id}"><a href="#${id}">${raw}</a></h${level}>`;
}
}
},
style: {
type: Object as PropType<CSSProperties | string>,
default: () => ({})
},
markedHeadingId: {
type: Function as PropType<MarkedHeadingId>,
default: markedHeadingId
},
// 表格预设格子数
tableShape: {
type: Array as PropType<Array<number>>,
default: () => [6, 4]
},
// mermaid实例
mermaid: {
type: Object
},
// mermaid script链接
mermaidJs: {
type: String as PropType<string>,
default: mermaidUrl
},
// 不使用该功能
noMermaid: {
type: Boolean as PropType<boolean>,
default: false
},
// 不能保证文本正确的情况,在marked编译md文本后通过该方法处理
// 推荐DOMPurify、sanitize-html
sanitize: {
type: Function as PropType<(html: string) => string>,
default: (html: string) => html
},
placeholder: {
type: String as PropType<string>,
default: ''
},
katex: {
type: Object
},
// katex script链接
katexJs: {
type: String as PropType<string>,
default: katexJsUrl
},
// katex css链接
katexCss: {
type: String as PropType<string>,
default: katexCssUrl
},
// 不使用该函数功能
noKatex: {
type: Boolean as PropType<boolean>,
default: false
}
};
export default defineComponent({
name: 'MdEditorV3',
props,
setup(props, context) {
// 下面的内容不使用响应式(解构会失去响应式能力)
// eslint-disable-next-line vue/no-setup-props-destructure
const {
hljs,
previewOnly,
iconfontJs,
prettier,
prettierCDN,
prettierMDCDN,
Cropper,
cropperCss,
cropperJs,
editorId,
screenfull,
screenfullJs
} = props;
// 快捷键监听
useKeyBoard(props, context);
// ~~
useProvide(props);
// ----编辑器设置----
const setting = reactive<SettingType>({
pageFullScreen: props.pageFullScreen,
fullscreen: false,
preview: props.preview,
htmlPreview: props.preview ? false : props.htmlPreview
});
const updateSetting = (v: any, k: keyof typeof setting) => {
setting[k] = v;
if (k === 'preview' && setting.preview) {
setting.htmlPreview = false;
} else if (k === 'htmlPreview' && setting.htmlPreview) {
setting.preview = false;
}
};
// 将在客户端挂载时获取该样式
let bodyOverflowHistory = '';
const adjustBody = () => {
if (setting.pageFullScreen || setting.fullscreen) {
document.body.style.overflow = 'hidden';
} else {
document.body.style.overflow = bodyOverflowHistory;
}
};
// 变化是调整一次
watch(() => [setting.pageFullScreen, setting.fullscreen], adjustBody);
// 进入时若默认全屏,调整一次
onMounted(() => {
// 监听上传图片
if (!previewOnly) {
bus.on(editorId, {
name: 'uploadImage',
callback(files: FileList, cb: () => void) {
const insertHanlder = (urls: Array<string>) => {
urls.forEach((url) => {
// 利用事件循环机制,保证两次插入分开进行
setTimeout(() => {
bus.emit(editorId, 'replace', 'image', {
desc: '',
url
});
}, 0);
});
cb && cb();
};
if (props.onUploadImg) {
props.onUploadImg(files, insertHanlder);
} else {
context.emit('onUploadImg', files, insertHanlder);
}
}
});
}
bodyOverflowHistory = document.body.style.overflow;
adjustBody();
});
// ----end----
// 卸载组件前清空全部事件监听
onBeforeUnmount(() => {
bus.clear(editorId);
});
const catalogShow = computed(() => {
return (
!props.toolbarsExclude.includes('catalog') && props.toolbars.includes('catalog')
);
});
return () => (
<div
id={editorId}
class={[
prefix,
props.editorClass,
props.theme === 'dark' && `${prefix}-dark`,
setting.fullscreen || setting.pageFullScreen ? `${prefix}-fullscreen` : '',
previewOnly && `${prefix}-previewOnly`
]}
style={props.style}
>
{!previewOnly && (
<ToolBar
prettier={prettier}
screenfull={screenfull}
screenfullJs={screenfullJs}
toolbars={props.toolbars}
toolbarsExclude={props.toolbarsExclude}
setting={setting}
updateSetting={updateSetting}
tableShape={props.tableShape}
/>
)}
<Content
hljs={hljs}
value={props.modelValue}
onChange={(value: string) => {
if (props.onChange) {
props.onChange(value);
} else {
context.emit('update:modelValue', value);
}
}}
setting={setting}
onHtmlChanged={(html: string) => {
if (props.onHtmlChanged) {
props.onHtmlChanged(html);
} else {
context.emit('onHtmlChanged', html);
}
}}
onGetCatalog={(list: HeadList[]) => {
if (props.onGetCatalog) {
props.onGetCatalog(list);
} else {
context.emit('onGetCatalog', list);
}
}}
markedHeading={props.markedHeading}
mermaid={props.mermaid}
mermaidJs={props.mermaidJs}
noMermaid={props.noMermaid}
sanitize={props.sanitize}
placeholder={props.placeholder}
katex={props.katex}
katexJs={props.katexJs}
katexCss={props.katexCss}
noKatex={props.noKatex}
/>
{catalogShow.value && <Catalog markedHeadingId={props.markedHeadingId} />}
{!previewOnly && (
<Teleport to="head">
<script src={iconfontJs} />
</Teleport>
)}
{prettier && !previewOnly && (
<Teleport to="head">
<script src={prettierCDN} />
<script src={prettierMDCDN} />
</Teleport>
)}
{!previewOnly && Cropper === null && (
<Teleport to="head">
<link href={cropperCss} rel="stylesheet" />
<script src={cropperJs}></script>
</Teleport>
)}
</div>
);
}
}); | the_stack |
import { HttpClient, HttpResponse, HttpEvent } from '@angular/common/http';
import { Inject, Injectable, Optional } from '@angular/core';
import { APIClientInterface } from './api-client.interface';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { USE_DOMAIN, USE_HTTP_OPTIONS, APIClient } from './api-client.service';
import { DefaultHttpOptions, HttpOptions } from './types';
import * as models from './models';
import * as guards from './guards';
@Injectable()
export class GuardedAPIClient extends APIClient implements APIClientInterface {
constructor(
readonly httpClient: HttpClient,
@Optional() @Inject(USE_DOMAIN) domain?: string,
@Optional() @Inject(USE_HTTP_OPTIONS) options?: DefaultHttpOptions,
) {
super(httpClient, domain, options);
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
auth(
args: Exclude<APIClientInterface['authParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
auth(
args: Exclude<APIClientInterface['authParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
auth(
args: Exclude<APIClientInterface['authParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
auth(
args: Exclude<APIClientInterface['authParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.auth(args, requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
authRef(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
authRef(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
authRef(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
authRef(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.authRef(requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
passwordRestoreRequest(
args: Exclude<APIClientInterface['passwordRestoreRequestParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
passwordRestoreRequest(
args: Exclude<APIClientInterface['passwordRestoreRequestParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
passwordRestoreRequest(
args: Exclude<APIClientInterface['passwordRestoreRequestParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
passwordRestoreRequest(
args: Exclude<APIClientInterface['passwordRestoreRequestParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.passwordRestoreRequest(args, requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
passwordRestoreEmailRequest(
args: Exclude<APIClientInterface['passwordRestoreEmailRequestParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
passwordRestoreEmailRequest(
args: Exclude<APIClientInterface['passwordRestoreEmailRequestParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
passwordRestoreEmailRequest(
args: Exclude<APIClientInterface['passwordRestoreEmailRequestParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
passwordRestoreEmailRequest(
args: Exclude<APIClientInterface['passwordRestoreEmailRequestParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.passwordRestoreEmailRequest(args, requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Response generated for [ 200 ] HTTP response code.
*/
passwordRestoreCheckRestoreGuid(
args: Exclude<APIClientInterface['passwordRestoreCheckRestoreGuidParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
passwordRestoreCheckRestoreGuid(
args: Exclude<APIClientInterface['passwordRestoreCheckRestoreGuidParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
passwordRestoreCheckRestoreGuid(
args: Exclude<APIClientInterface['passwordRestoreCheckRestoreGuidParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
passwordRestoreCheckRestoreGuid(
args: Exclude<APIClientInterface['passwordRestoreCheckRestoreGuidParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.passwordRestoreCheckRestoreGuid(args, requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Get list of roles to permissions mapping
* Response generated for [ 200 ] HTTP response code.
*/
getAclList(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.AclItem[]>;
getAclList(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.AclItem[]>>;
getAclList(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.AclItem[]>>;
getAclList(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.AclItem[] | HttpResponse<models.AclItem[]> | HttpEvent<models.AclItem[]>> {
return super.getAclList(requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isAclItem(item)) ) || console.error(`TypeGuard for response 'models.AclItem[]' caught inconsistency.`, res)));
}
/**
* Get structure entities list
* Response generated for [ 200 ] HTTP response code.
*/
getStructureEntitiesList(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Structure[]>;
getStructureEntitiesList(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Structure[]>>;
getStructureEntitiesList(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Structure[]>>;
getStructureEntitiesList(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Structure[] | HttpResponse<models.Structure[]> | HttpEvent<models.Structure[]>> {
return super.getStructureEntitiesList(requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isStructure(item)) ) || console.error(`TypeGuard for response 'models.Structure[]' caught inconsistency.`, res)));
}
/**
* Add a new structure entity
* Response generated for [ 200 ] HTTP response code.
*/
addStructureEntity(
args: Exclude<APIClientInterface['addStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Structure>;
addStructureEntity(
args: Exclude<APIClientInterface['addStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Structure>>;
addStructureEntity(
args: Exclude<APIClientInterface['addStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Structure>>;
addStructureEntity(
args: Exclude<APIClientInterface['addStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Structure | HttpResponse<models.Structure> | HttpEvent<models.Structure>> {
return super.addStructureEntity(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isStructure(res) || console.error(`TypeGuard for response 'models.Structure' caught inconsistency.`, res)));
}
/**
* Update an existing structure entity
* Response generated for [ 200 ] HTTP response code.
*/
updateStructureEntity(
args: Exclude<APIClientInterface['updateStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Structure>;
updateStructureEntity(
args: Exclude<APIClientInterface['updateStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Structure>>;
updateStructureEntity(
args: Exclude<APIClientInterface['updateStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Structure>>;
updateStructureEntity(
args: Exclude<APIClientInterface['updateStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Structure | HttpResponse<models.Structure> | HttpEvent<models.Structure>> {
return super.updateStructureEntity(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isStructure(res) || console.error(`TypeGuard for response 'models.Structure' caught inconsistency.`, res)));
}
/**
* Deletes a structure entity
* Response generated for [ 200 ] HTTP response code.
*/
deleteStructureEntity(
args: Exclude<APIClientInterface['deleteStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteStructureEntity(
args: Exclude<APIClientInterface['deleteStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteStructureEntity(
args: Exclude<APIClientInterface['deleteStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteStructureEntity(
args: Exclude<APIClientInterface['deleteStructureEntityParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.deleteStructureEntity(args, requestHttpOptions, observe);
}
/**
* Get reports list
* [Screenshot from design](http://prntscr.com/hy4z8d)
*
* Response generated for [ 200 ] HTTP response code.
*/
getReportsList(
args: Exclude<APIClientInterface['getReportsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getReportsList(
args: Exclude<APIClientInterface['getReportsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getReportsList(
args: Exclude<APIClientInterface['getReportsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
getReportsList(
args: Exclude<APIClientInterface['getReportsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.getReportsList(args, requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Get report details
* [Screenshot from design](http://prntscr.com/hywkd5)
*
* Response generated for [ 200 ] HTTP response code.
*/
getReportDetails(
args: Exclude<APIClientInterface['getReportDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ReportItem[]>;
getReportDetails(
args: Exclude<APIClientInterface['getReportDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ReportItem[]>>;
getReportDetails(
args: Exclude<APIClientInterface['getReportDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ReportItem[]>>;
getReportDetails(
args: Exclude<APIClientInterface['getReportDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.ReportItem[] | HttpResponse<models.ReportItem[]> | HttpEvent<models.ReportItem[]>> {
return super.getReportDetails(args, requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isReportItem(item)) ) || console.error(`TypeGuard for response 'models.ReportItem[]' caught inconsistency.`, res)));
}
/**
* Get report preview
* [Screenshot from design](http://prntscr.com/i3z8zb)
*
* Response generated for [ 200 ] HTTP response code.
*/
getReportPreview(
args: Exclude<APIClientInterface['getReportPreviewParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getReportPreview(
args: Exclude<APIClientInterface['getReportPreviewParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getReportPreview(
args: Exclude<APIClientInterface['getReportPreviewParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
getReportPreview(
args: Exclude<APIClientInterface['getReportPreviewParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.getReportPreview(args, requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Get import history
* [Screenshot from design](http://prntscr.com/i3ym4j)
*
* Response generated for [ 200 ] HTTP response code.
*/
getImportHistory(
args: Exclude<APIClientInterface['getImportHistoryParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ImportHistoryItem[]>;
getImportHistory(
args: Exclude<APIClientInterface['getImportHistoryParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ImportHistoryItem[]>>;
getImportHistory(
args: Exclude<APIClientInterface['getImportHistoryParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ImportHistoryItem[]>>;
getImportHistory(
args: Exclude<APIClientInterface['getImportHistoryParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.ImportHistoryItem[] | HttpResponse<models.ImportHistoryItem[]> | HttpEvent<models.ImportHistoryItem[]>> {
return super.getImportHistory(args, requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isImportHistoryItem(item)) ) || console.error(`TypeGuard for response 'models.ImportHistoryItem[]' caught inconsistency.`, res)));
}
/**
* Upload a completed template
* [Screenshot from design](http://prntscr.com/hy521p)
*
* Response generated for [ 200 ] HTTP response code.
*/
uploadFile(
args: Exclude<APIClientInterface['uploadFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<number>;
uploadFile(
args: Exclude<APIClientInterface['uploadFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<number>>;
uploadFile(
args: Exclude<APIClientInterface['uploadFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<number>>;
uploadFile(
args: Exclude<APIClientInterface['uploadFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<number | HttpResponse<number> | HttpEvent<number>> {
return super.uploadFile(args, requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'number' || console.error(`TypeGuard for response 'number' caught inconsistency.`, res)));
}
/**
* Get list of current Import template columns
* [Screenshot from design](http://prntscr.com/hy52hi)
*
* Response generated for [ 200 ] HTTP response code.
*/
listTemplateColumns(
args: Exclude<APIClientInterface['listTemplateColumnsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Column[]>;
listTemplateColumns(
args: Exclude<APIClientInterface['listTemplateColumnsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Column[]>>;
listTemplateColumns(
args: Exclude<APIClientInterface['listTemplateColumnsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Column[]>>;
listTemplateColumns(
args: Exclude<APIClientInterface['listTemplateColumnsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Column[] | HttpResponse<models.Column[]> | HttpEvent<models.Column[]>> {
return super.listTemplateColumns(args, requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isColumn(item)) ) || console.error(`TypeGuard for response 'models.Column[]' caught inconsistency.`, res)));
}
/**
* Get list of current Import template columns
* [Screenshot from design](http://prntscr.com/hy52zr)
*
* Response generated for [ 200 ] HTTP response code.
*/
listReportColumns(
args: Exclude<APIClientInterface['listReportColumnsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Column[]>;
listReportColumns(
args: Exclude<APIClientInterface['listReportColumnsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Column[]>>;
listReportColumns(
args: Exclude<APIClientInterface['listReportColumnsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Column[]>>;
listReportColumns(
args: Exclude<APIClientInterface['listReportColumnsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Column[] | HttpResponse<models.Column[]> | HttpEvent<models.Column[]>> {
return super.listReportColumns(args, requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isColumn(item)) ) || console.error(`TypeGuard for response 'models.Column[]' caught inconsistency.`, res)));
}
/**
* Save columns mapping
* [Screenshot from design](http://prntscr.com/hy53jt)
*
* Response generated for [ 200 ] HTTP response code.
*/
saveColumnsMapping(
args: Exclude<APIClientInterface['saveColumnsMappingParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Table>;
saveColumnsMapping(
args: Exclude<APIClientInterface['saveColumnsMappingParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Table>>;
saveColumnsMapping(
args: Exclude<APIClientInterface['saveColumnsMappingParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Table>>;
saveColumnsMapping(
args: Exclude<APIClientInterface['saveColumnsMappingParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Table | HttpResponse<models.Table> | HttpEvent<models.Table>> {
return super.saveColumnsMapping(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isTable(res) || console.error(`TypeGuard for response 'models.Table' caught inconsistency.`, res)));
}
/**
* Get validation table
* [Screenshot from design](http://prntscr.com/hy5fct)
*
* Response generated for [ 200 ] HTTP response code.
*/
getValidationTable(
args: Exclude<APIClientInterface['getValidationTableParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ValidatedTable>;
getValidationTable(
args: Exclude<APIClientInterface['getValidationTableParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ValidatedTable>>;
getValidationTable(
args: Exclude<APIClientInterface['getValidationTableParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ValidatedTable>>;
getValidationTable(
args: Exclude<APIClientInterface['getValidationTableParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.ValidatedTable | HttpResponse<models.ValidatedTable> | HttpEvent<models.ValidatedTable>> {
return super.getValidationTable(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isValidatedTable(res) || console.error(`TypeGuard for response 'models.ValidatedTable' caught inconsistency.`, res)));
}
/**
* Download imported data
* [Screenshot from design](http://prntscr.com/hy55ga)
*
* Response generated for [ 200 ] HTTP response code.
*/
downloadImportedFile(
args: Exclude<APIClientInterface['downloadImportedFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<File>;
downloadImportedFile(
args: Exclude<APIClientInterface['downloadImportedFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<File>>;
downloadImportedFile(
args: Exclude<APIClientInterface['downloadImportedFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<File>>;
downloadImportedFile(
args: Exclude<APIClientInterface['downloadImportedFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<File | HttpResponse<File> | HttpEvent<File>> {
return super.downloadImportedFile(args, requestHttpOptions, observe)
.pipe(tap((res: any) => res instanceof File || console.error(`TypeGuard for response 'File' caught inconsistency.`, res)));
}
/**
* Confirm final import
* [Screenshot from design](http://prntscr.com/hy57nj)
*
* Response generated for [ 200 ] HTTP response code.
*/
importConfirmation(
args: Exclude<APIClientInterface['importConfirmationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.ImportResponse>;
importConfirmation(
args: Exclude<APIClientInterface['importConfirmationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.ImportResponse>>;
importConfirmation(
args: Exclude<APIClientInterface['importConfirmationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.ImportResponse>>;
importConfirmation(
args: Exclude<APIClientInterface['importConfirmationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.ImportResponse | HttpResponse<models.ImportResponse> | HttpEvent<models.ImportResponse>> {
return super.importConfirmation(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isImportResponse(res) || console.error(`TypeGuard for response 'models.ImportResponse' caught inconsistency.`, res)));
}
/**
* Download original file
* [Screenshot from design](http://prntscr.com/hy5a54)
*
* Response generated for [ 200 ] HTTP response code.
*/
downloadImportOriginalFile(
args: Exclude<APIClientInterface['downloadImportOriginalFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<File>;
downloadImportOriginalFile(
args: Exclude<APIClientInterface['downloadImportOriginalFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<File>>;
downloadImportOriginalFile(
args: Exclude<APIClientInterface['downloadImportOriginalFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<File>>;
downloadImportOriginalFile(
args: Exclude<APIClientInterface['downloadImportOriginalFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<File | HttpResponse<File> | HttpEvent<File>> {
return super.downloadImportOriginalFile(args, requestHttpOptions, observe)
.pipe(tap((res: any) => res instanceof File || console.error(`TypeGuard for response 'File' caught inconsistency.`, res)));
}
/**
* Download skipped rows file
* [Screenshot from design](http://prntscr.com/hy5ae7)
*
* Response generated for [ 200 ] HTTP response code.
*/
downloadImportSkippedFile(
args: Exclude<APIClientInterface['downloadImportSkippedFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<File>;
downloadImportSkippedFile(
args: Exclude<APIClientInterface['downloadImportSkippedFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<File>>;
downloadImportSkippedFile(
args: Exclude<APIClientInterface['downloadImportSkippedFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<File>>;
downloadImportSkippedFile(
args: Exclude<APIClientInterface['downloadImportSkippedFileParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<File | HttpResponse<File> | HttpEvent<File>> {
return super.downloadImportSkippedFile(args, requestHttpOptions, observe)
.pipe(tap((res: any) => res instanceof File || console.error(`TypeGuard for response 'File' caught inconsistency.`, res)));
}
/**
* Cancel current import
* [Screenshot from design](http://prntscr.com/hy5aqq)
*
* Response generated for [ 200 ] HTTP response code.
*/
cancelImport(
args: Exclude<APIClientInterface['cancelImportParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
cancelImport(
args: Exclude<APIClientInterface['cancelImportParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
cancelImport(
args: Exclude<APIClientInterface['cancelImportParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
cancelImport(
args: Exclude<APIClientInterface['cancelImportParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.cancelImport(args, requestHttpOptions, observe);
}
/**
* Request override data for import
* [Screenshot from design](http://prntscr.com/hy5bi6)
*
* Response generated for [ 200 ] HTTP response code.
*/
overrideImport(
args: Exclude<APIClientInterface['overrideImportParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
overrideImport(
args: Exclude<APIClientInterface['overrideImportParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
overrideImport(
args: Exclude<APIClientInterface['overrideImportParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
overrideImport(
args: Exclude<APIClientInterface['overrideImportParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.overrideImport(args, requestHttpOptions, observe);
}
/**
* Get import stats
* [Screenshot from design](http://prntscr.com/i4052r)
*
* Response generated for [ 200 ] HTTP response code.
*/
geImportStats(
args?: APIClientInterface['geImportStatsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.TotalImportStats>;
geImportStats(
args?: APIClientInterface['geImportStatsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.TotalImportStats>>;
geImportStats(
args?: APIClientInterface['geImportStatsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.TotalImportStats>>;
geImportStats(
args: APIClientInterface['geImportStatsParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.TotalImportStats | HttpResponse<models.TotalImportStats> | HttpEvent<models.TotalImportStats>> {
return super.geImportStats(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isTotalImportStats(res) || console.error(`TypeGuard for response 'models.TotalImportStats' caught inconsistency.`, res)));
}
/**
* Get issues list
* [Screenshot from design](http://prntscr.com/i40s18)
*
* Response generated for [ 200 ] HTTP response code.
*/
getIssuesList(
args: Exclude<APIClientInterface['getIssuesListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getIssuesList(
args: Exclude<APIClientInterface['getIssuesListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getIssuesList(
args: Exclude<APIClientInterface['getIssuesListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
getIssuesList(
args: Exclude<APIClientInterface['getIssuesListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.getIssuesList(args, requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Get import statuses list
* [Screenshot from design](http://prntscr.com/i4byyx)
*
* Response generated for [ 200 ] HTTP response code.
*/
getStatusesList(
args: Exclude<APIClientInterface['getStatusesListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getStatusesList(
args: Exclude<APIClientInterface['getStatusesListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getStatusesList(
args: Exclude<APIClientInterface['getStatusesListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
getStatusesList(
args: Exclude<APIClientInterface['getStatusesListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.getStatusesList(args, requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Get users list
* Response generated for [ 200 ] HTTP response code.
*/
getUsersList(
args: Exclude<APIClientInterface['getUsersListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getUsersList(
args: Exclude<APIClientInterface['getUsersListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getUsersList(
args: Exclude<APIClientInterface['getUsersListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
getUsersList(
args: Exclude<APIClientInterface['getUsersListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.getUsersList(args, requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Create user
* Response generated for [ 200 ] HTTP response code.
*/
createUser(
args: Exclude<APIClientInterface['createUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.UserDetails>;
createUser(
args: Exclude<APIClientInterface['createUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.UserDetails>>;
createUser(
args: Exclude<APIClientInterface['createUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.UserDetails>>;
createUser(
args: Exclude<APIClientInterface['createUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.UserDetails | HttpResponse<models.UserDetails> | HttpEvent<models.UserDetails>> {
return super.createUser(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isUserDetails(res) || console.error(`TypeGuard for response 'models.UserDetails' caught inconsistency.`, res)));
}
/**
* Get acl structure
* Response generated for [ 200 ] HTTP response code.
*/
getAclStructure(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.Acl[]>;
getAclStructure(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.Acl[]>>;
getAclStructure(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.Acl[]>>;
getAclStructure(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.Acl[] | HttpResponse<models.Acl[]> | HttpEvent<models.Acl[]>> {
return super.getAclStructure(requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isAcl(item)) ) || console.error(`TypeGuard for response 'models.Acl[]' caught inconsistency.`, res)));
}
/**
* getUserDetails
* Response generated for [ 200 ] HTTP response code.
*/
getUserDetails(
args: Exclude<APIClientInterface['getUserDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.UserDetails[]>;
getUserDetails(
args: Exclude<APIClientInterface['getUserDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.UserDetails[]>>;
getUserDetails(
args: Exclude<APIClientInterface['getUserDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.UserDetails[]>>;
getUserDetails(
args: Exclude<APIClientInterface['getUserDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.UserDetails[] | HttpResponse<models.UserDetails[]> | HttpEvent<models.UserDetails[]>> {
return super.getUserDetails(args, requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isUserDetails(item)) ) || console.error(`TypeGuard for response 'models.UserDetails[]' caught inconsistency.`, res)));
}
/**
* update user by id
* Response generated for [ 200 ] HTTP response code.
*/
updateUser(
args: Exclude<APIClientInterface['updateUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.UserDetails>;
updateUser(
args: Exclude<APIClientInterface['updateUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.UserDetails>>;
updateUser(
args: Exclude<APIClientInterface['updateUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.UserDetails>>;
updateUser(
args: Exclude<APIClientInterface['updateUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.UserDetails | HttpResponse<models.UserDetails> | HttpEvent<models.UserDetails>> {
return super.updateUser(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isUserDetails(res) || console.error(`TypeGuard for response 'models.UserDetails' caught inconsistency.`, res)));
}
/**
* delete user by id
* Response generated for [ 200 ] HTTP response code.
*/
deleteUser(
args: Exclude<APIClientInterface['deleteUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteUser(
args: Exclude<APIClientInterface['deleteUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteUser(
args: Exclude<APIClientInterface['deleteUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteUser(
args: Exclude<APIClientInterface['deleteUserParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.deleteUser(args, requestHttpOptions, observe);
}
/**
* Get roles list
* [Screenshot from design](http://prntscr.com/i93q0s)
*
* Response generated for [ 200 ] HTTP response code.
*/
getRolesList(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.RoleListItem[]>;
getRolesList(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.RoleListItem[]>>;
getRolesList(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.RoleListItem[]>>;
getRolesList(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.RoleListItem[] | HttpResponse<models.RoleListItem[]> | HttpEvent<models.RoleListItem[]>> {
return super.getRolesList(requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isRoleListItem(item)) ) || console.error(`TypeGuard for response 'models.RoleListItem[]' caught inconsistency.`, res)));
}
/**
* Create role
* Response generated for [ 200 ] HTTP response code.
*/
createRole(
args: Exclude<APIClientInterface['createRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.RoleDetailsItem>;
createRole(
args: Exclude<APIClientInterface['createRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.RoleDetailsItem>>;
createRole(
args: Exclude<APIClientInterface['createRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.RoleDetailsItem>>;
createRole(
args: Exclude<APIClientInterface['createRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.RoleDetailsItem | HttpResponse<models.RoleDetailsItem> | HttpEvent<models.RoleDetailsItem>> {
return super.createRole(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isRoleDetailsItem(res) || console.error(`TypeGuard for response 'models.RoleDetailsItem' caught inconsistency.`, res)));
}
/**
* Get privileges list
* [Screenshot from design](http://prntscr.com/i947a3)
*
* Response generated for [ 200 ] HTTP response code.
*/
getList(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PrivilegeTreeItem[]>;
getList(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PrivilegeTreeItem[]>>;
getList(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PrivilegeTreeItem[]>>;
getList(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.PrivilegeTreeItem[] | HttpResponse<models.PrivilegeTreeItem[]> | HttpEvent<models.PrivilegeTreeItem[]>> {
return super.getList(requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isPrivilegeTreeItem(item)) ) || console.error(`TypeGuard for response 'models.PrivilegeTreeItem[]' caught inconsistency.`, res)));
}
/**
* Get role details
* Response generated for [ 200 ] HTTP response code.
*/
getRoleDetails(
args: Exclude<APIClientInterface['getRoleDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.RoleDetailsItem[]>;
getRoleDetails(
args: Exclude<APIClientInterface['getRoleDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.RoleDetailsItem[]>>;
getRoleDetails(
args: Exclude<APIClientInterface['getRoleDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.RoleDetailsItem[]>>;
getRoleDetails(
args: Exclude<APIClientInterface['getRoleDetailsParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.RoleDetailsItem[] | HttpResponse<models.RoleDetailsItem[]> | HttpEvent<models.RoleDetailsItem[]>> {
return super.getRoleDetails(args, requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isRoleDetailsItem(item)) ) || console.error(`TypeGuard for response 'models.RoleDetailsItem[]' caught inconsistency.`, res)));
}
/**
* Update role by id
* Response generated for [ 200 ] HTTP response code.
*/
updateRole(
args: Exclude<APIClientInterface['updateRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.RoleDetailsItem>;
updateRole(
args: Exclude<APIClientInterface['updateRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.RoleDetailsItem>>;
updateRole(
args: Exclude<APIClientInterface['updateRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.RoleDetailsItem>>;
updateRole(
args: Exclude<APIClientInterface['updateRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.RoleDetailsItem | HttpResponse<models.RoleDetailsItem> | HttpEvent<models.RoleDetailsItem>> {
return super.updateRole(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isRoleDetailsItem(res) || console.error(`TypeGuard for response 'models.RoleDetailsItem' caught inconsistency.`, res)));
}
/**
* Ddelete role by id
* Response generated for [ 200 ] HTTP response code.
*/
deleteRole(
args: Exclude<APIClientInterface['deleteRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
deleteRole(
args: Exclude<APIClientInterface['deleteRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
deleteRole(
args: Exclude<APIClientInterface['deleteRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
deleteRole(
args: Exclude<APIClientInterface['deleteRoleParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.deleteRole(args, requestHttpOptions, observe);
}
/**
* Get unviewed notifications list
* [Screenshot from design](http://prntscr.com/iba7xr)
*
* Response generated for [ 200 ] HTTP response code.
*/
getNewNotificationsList(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.NotificationListItem[]>;
getNewNotificationsList(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.NotificationListItem[]>>;
getNewNotificationsList(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.NotificationListItem[]>>;
getNewNotificationsList(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.NotificationListItem[] | HttpResponse<models.NotificationListItem[]> | HttpEvent<models.NotificationListItem[]>> {
return super.getNewNotificationsList(requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isNotificationListItem(item)) ) || console.error(`TypeGuard for response 'models.NotificationListItem[]' caught inconsistency.`, res)));
}
/**
* Mark notifications as viewed
* Response generated for [ 200 ] HTTP response code.
*/
markViewedNotifications(
args?: APIClientInterface['markViewedNotificationsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
markViewedNotifications(
args?: APIClientInterface['markViewedNotificationsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
markViewedNotifications(
args?: APIClientInterface['markViewedNotificationsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
markViewedNotifications(
args: APIClientInterface['markViewedNotificationsParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.markViewedNotifications(args, requestHttpOptions, observe);
}
/**
* Get user's notifications list
* [Screenshot from design](http://prntscr.com/iba8tq)
*
* Response generated for [ 200 ] HTTP response code.
*/
getNotificationsList(
args: Exclude<APIClientInterface['getNotificationsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getNotificationsList(
args: Exclude<APIClientInterface['getNotificationsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getNotificationsList(
args: Exclude<APIClientInterface['getNotificationsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
getNotificationsList(
args: Exclude<APIClientInterface['getNotificationsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.getNotificationsList(args, requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Get modules list
* [Screenshot from design](http://prntscr.com/ibac47) |
* [Screenshot from design](http://prntscr.com/ibacgu)
*
* Response generated for [ 200 ] HTTP response code.
*/
getModulesList(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.NotificationModule[]>;
getModulesList(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.NotificationModule[]>>;
getModulesList(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.NotificationModule[]>>;
getModulesList(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.NotificationModule[] | HttpResponse<models.NotificationModule[]> | HttpEvent<models.NotificationModule[]>> {
return super.getModulesList(requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isNotificationModule(item)) ) || console.error(`TypeGuard for response 'models.NotificationModule[]' caught inconsistency.`, res)));
}
/**
* Get triggers list
* [Screenshot from design](http://prntscr.com/ibad9m)
*
* Response generated for [ 200 ] HTTP response code.
*/
getTriggersList(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.NotificationTrigger[]>;
getTriggersList(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.NotificationTrigger[]>>;
getTriggersList(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.NotificationTrigger[]>>;
getTriggersList(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.NotificationTrigger[] | HttpResponse<models.NotificationTrigger[]> | HttpEvent<models.NotificationTrigger[]>> {
return super.getTriggersList(requestHttpOptions, observe)
.pipe(tap((res: any) => ( Array.isArray(res) && res.every((item: any) => guards.isNotificationTrigger(item)) ) || console.error(`TypeGuard for response 'models.NotificationTrigger[]' caught inconsistency.`, res)));
}
/**
* Get module's notifications list
* [Screenshot from design](http://prntscr.com/iba8tq)
*
* Response generated for [ 200 ] HTTP response code.
*/
getModuleNotificationsList(
args: Exclude<APIClientInterface['getModuleNotificationsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<object>;
getModuleNotificationsList(
args: Exclude<APIClientInterface['getModuleNotificationsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<object>>;
getModuleNotificationsList(
args: Exclude<APIClientInterface['getModuleNotificationsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<object>>;
getModuleNotificationsList(
args: Exclude<APIClientInterface['getModuleNotificationsListParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<object | HttpResponse<object> | HttpEvent<object>> {
return super.getModuleNotificationsList(args, requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'object' || console.error(`TypeGuard for response 'object' caught inconsistency.`, res)));
}
/**
* Enable notification
* Response generated for [ 200 ] HTTP response code.
*/
enableNotification(
args: Exclude<APIClientInterface['enableNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
enableNotification(
args: Exclude<APIClientInterface['enableNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
enableNotification(
args: Exclude<APIClientInterface['enableNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
enableNotification(
args: Exclude<APIClientInterface['enableNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.enableNotification(args, requestHttpOptions, observe);
}
/**
* Disable notification
* Response generated for [ 200 ] HTTP response code.
*/
disableNotification(
args: Exclude<APIClientInterface['disableNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
disableNotification(
args: Exclude<APIClientInterface['disableNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
disableNotification(
args: Exclude<APIClientInterface['disableNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
disableNotification(
args: Exclude<APIClientInterface['disableNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.disableNotification(args, requestHttpOptions, observe);
}
/**
* Get notification details
* Response generated for [ 200 ] HTTP response code.
*/
getNotification(
args: Exclude<APIClientInterface['getNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.NotificationEditableListItem>;
getNotification(
args: Exclude<APIClientInterface['getNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.NotificationEditableListItem>>;
getNotification(
args: Exclude<APIClientInterface['getNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.NotificationEditableListItem>>;
getNotification(
args: Exclude<APIClientInterface['getNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.NotificationEditableListItem | HttpResponse<models.NotificationEditableListItem> | HttpEvent<models.NotificationEditableListItem>> {
return super.getNotification(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isNotificationEditableListItem(res) || console.error(`TypeGuard for response 'models.NotificationEditableListItem' caught inconsistency.`, res)));
}
/**
* Update notification
* Response generated for [ 200 ] HTTP response code.
*/
updateNotification(
args: Exclude<APIClientInterface['updateNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<void>;
updateNotification(
args: Exclude<APIClientInterface['updateNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<void>>;
updateNotification(
args: Exclude<APIClientInterface['updateNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<void>>;
updateNotification(
args: Exclude<APIClientInterface['updateNotificationParams'], undefined>,
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<void | HttpResponse<void> | HttpEvent<void>> {
return super.updateNotification(args, requestHttpOptions, observe);
}
/**
* Create notification
* Response generated for [ 200 ] HTTP response code.
*/
createNotification(
args?: APIClientInterface['createNotificationParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<number>;
createNotification(
args?: APIClientInterface['createNotificationParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<number>>;
createNotification(
args?: APIClientInterface['createNotificationParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<number>>;
createNotification(
args: APIClientInterface['createNotificationParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<number | HttpResponse<number> | HttpEvent<number>> {
return super.createNotification(args, requestHttpOptions, observe)
.pipe(tap((res: any) => typeof res === 'number' || console.error(`TypeGuard for response 'number' caught inconsistency.`, res)));
}
/**
* Get password verefication settings
* [Screenshot from design](http://prntscr.com/ijzt2b)
*
* Response generated for [ 200 ] HTTP response code.
*/
getPassVerificationPolicies(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PasswordVerificationPolicies>;
getPassVerificationPolicies(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PasswordVerificationPolicies>>;
getPassVerificationPolicies(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PasswordVerificationPolicies>>;
getPassVerificationPolicies(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.PasswordVerificationPolicies | HttpResponse<models.PasswordVerificationPolicies> | HttpEvent<models.PasswordVerificationPolicies>> {
return super.getPassVerificationPolicies(requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isPasswordVerificationPolicies(res) || console.error(`TypeGuard for response 'models.PasswordVerificationPolicies' caught inconsistency.`, res)));
}
/**
* Update password verefication settings
* [Screenshot from design](http://prntscr.com/ijzt2b)
*
* Response generated for [ 200 ] HTTP response code.
*/
udatePassVerificationPolicies(
args?: APIClientInterface['udatePassVerificationPoliciesParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PasswordVerificationPolicies>;
udatePassVerificationPolicies(
args?: APIClientInterface['udatePassVerificationPoliciesParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PasswordVerificationPolicies>>;
udatePassVerificationPolicies(
args?: APIClientInterface['udatePassVerificationPoliciesParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PasswordVerificationPolicies>>;
udatePassVerificationPolicies(
args: APIClientInterface['udatePassVerificationPoliciesParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.PasswordVerificationPolicies | HttpResponse<models.PasswordVerificationPolicies> | HttpEvent<models.PasswordVerificationPolicies>> {
return super.udatePassVerificationPolicies(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isPasswordVerificationPolicies(res) || console.error(`TypeGuard for response 'models.PasswordVerificationPolicies' caught inconsistency.`, res)));
}
/**
* Get password creation settings
* [Screenshot from design](http://prntscr.com/ijzuv3)
*
* Response generated for [ 200 ] HTTP response code.
*/
getPassCreationPolicies(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PasswordCreationPolicies>;
getPassCreationPolicies(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PasswordCreationPolicies>>;
getPassCreationPolicies(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PasswordCreationPolicies>>;
getPassCreationPolicies(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.PasswordCreationPolicies | HttpResponse<models.PasswordCreationPolicies> | HttpEvent<models.PasswordCreationPolicies>> {
return super.getPassCreationPolicies(requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isPasswordCreationPolicies(res) || console.error(`TypeGuard for response 'models.PasswordCreationPolicies' caught inconsistency.`, res)));
}
/**
* Update password creation settings
* [Screenshot from design](http://prntscr.com/ijzuv3)
*
* Response generated for [ 200 ] HTTP response code.
*/
udatePassCreationPolicies(
args?: APIClientInterface['udatePassCreationPoliciesParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.PasswordCreationPolicies>;
udatePassCreationPolicies(
args?: APIClientInterface['udatePassCreationPoliciesParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.PasswordCreationPolicies>>;
udatePassCreationPolicies(
args?: APIClientInterface['udatePassCreationPoliciesParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.PasswordCreationPolicies>>;
udatePassCreationPolicies(
args: APIClientInterface['udatePassCreationPoliciesParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.PasswordCreationPolicies | HttpResponse<models.PasswordCreationPolicies> | HttpEvent<models.PasswordCreationPolicies>> {
return super.udatePassCreationPolicies(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isPasswordCreationPolicies(res) || console.error(`TypeGuard for response 'models.PasswordCreationPolicies' caught inconsistency.`, res)));
}
/**
* Get other security settings settings
* [Screenshot from design](http://prntscr.com/ijzvo3)
*
* Response generated for [ 200 ] HTTP response code.
*/
getOtherSecuritySettings(
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.OtherSecuritySettings>;
getOtherSecuritySettings(
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.OtherSecuritySettings>>;
getOtherSecuritySettings(
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.OtherSecuritySettings>>;
getOtherSecuritySettings(
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.OtherSecuritySettings | HttpResponse<models.OtherSecuritySettings> | HttpEvent<models.OtherSecuritySettings>> {
return super.getOtherSecuritySettings(requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isOtherSecuritySettings(res) || console.error(`TypeGuard for response 'models.OtherSecuritySettings' caught inconsistency.`, res)));
}
/**
* Update other security settings settings
* [Screenshot from design](http://prntscr.com/ijzvo3)
*
* Response generated for [ 200 ] HTTP response code.
*/
udateOtherSecuritySettings(
args?: APIClientInterface['udateOtherSecuritySettingsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'body',
): Observable<models.OtherSecuritySettings>;
udateOtherSecuritySettings(
args?: APIClientInterface['udateOtherSecuritySettingsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'response',
): Observable<HttpResponse<models.OtherSecuritySettings>>;
udateOtherSecuritySettings(
args?: APIClientInterface['udateOtherSecuritySettingsParams'],
requestHttpOptions?: HttpOptions,
observe?: 'events',
): Observable<HttpEvent<models.OtherSecuritySettings>>;
udateOtherSecuritySettings(
args: APIClientInterface['udateOtherSecuritySettingsParams'] = {},
requestHttpOptions?: HttpOptions,
observe: any = 'body',
): Observable<models.OtherSecuritySettings | HttpResponse<models.OtherSecuritySettings> | HttpEvent<models.OtherSecuritySettings>> {
return super.udateOtherSecuritySettings(args, requestHttpOptions, observe)
.pipe(tap((res: any) => guards.isOtherSecuritySettings(res) || console.error(`TypeGuard for response 'models.OtherSecuritySettings' caught inconsistency.`, res)));
}
} | the_stack |
import { IInputs, IOutputs } from "./generated/ManifestTypes";
export class WebAPIControl implements ComponentFramework.StandardControl<IInputs, IOutputs>
{
// Reference to the control container HTMLDivElement
// This element contains all elements of our custom control example
private _container: HTMLDivElement;
// Reference to ComponentFramework Context object
private _context: ComponentFramework.Context<IInputs>;
// Name of entity to use for example Web API calls performed by this control
private static _entityName = "account";
// Required field on _entityName of type 'single line of text'
// Example Web API calls performed by example custom control will set this field for new record creation examples
private static _requiredAttributeName = "name";
// Value the _requiredAttributeName field will be set to for new created records
private static _requiredAttributeValue = "Web API Custom Control (Sample)";
// Name of currency field on _entityName to populate during record create
// Example Web API calls performed by example custom control will set and read this field
private static _currencyAttributeName = "revenue";
// Friendly name of currency field (only used for control UI - no functional impact)
private static _currencyAttributeNameFriendlyName = "annual revenue";
// Flag if control view has been rendered
private _controlViewRendered: boolean;
// References to button elements rendered by example custom control
private _createEntity1Button: HTMLButtonElement;
private _createEntity2Button: HTMLButtonElement;
private _createEntity3Button: HTMLButtonElement;
private _deleteRecordButton: HTMLButtonElement;
private _fetchXmlRefreshButton: HTMLButtonElement;
private _oDataRefreshButton: HTMLButtonElement;
// References to div elements rendered by the example custom control
private _odataStatusContainerDiv: HTMLDivElement;
private _resultContainerDiv: HTMLDivElement;
/**
* Used to initialize the control instance. Controls can kick off remote server calls and other initialization actions here.
* Data-set values are not initialized here, use updateView.
* @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to property names defined in the manifest, as well as utility functions.
* @param notifyOutputChanged A callback method to alert the framework that the control has new outputs ready to be retrieved asynchronously.
* @param state A piece of data that persists in one session for a single user. Can be set at any point in a controls life cycle by calling 'setControlState' in the Mode interface.
* @param container If a control is marked control-type='standard', it will receive an empty div element within which it can render its content.
*/
public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container: HTMLDivElement): void {
this._context = context;
this._controlViewRendered = false;
this._container = document.createElement("div");
this._container.classList.add("WebAPIControl_Container");
container.appendChild(this._container);
}
/**
* Called when any value in the property bag has changed. This includes field values, data-sets, global values such as container height and width, offline status, control metadata values such as label, visible, etc.
* @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to names defined in the manifest, as well as utility functions
*/
public updateView(context: ComponentFramework.Context<IInputs>): void {
this._context = context;
if (!this._controlViewRendered) {
this._controlViewRendered = true;
// Render Web API Examples
this.renderCreateExample();
this.renderDeleteExample();
this.renderFetchXmlRetrieveMultipleExample();
this.renderODataRetrieveMultipleExample();
// Render result div to display output of Web API calls
this.renderResultsDiv();
}
}
/**
* It is called by the framework prior to a control receiving new data.
* @returns an object based on nomenclature defined in manifest, expecting object[s] for property marked as "bound" or "output"
*/
public getOutputs(): IOutputs {
// no-op: method not leveraged by this example custom control
return {};
}
/**
* Called when the control is to be removed from the DOM tree. Controls should use this call for cleanup.
* i.e. cancelling any pending remote calls, removing listeners, etc.
*/
public destroy(): void {
// no-op: method not leveraged by this example custom control
}
/**
* Renders example use of CreateRecord Web API
*/
private renderCreateExample() {
// Create header label for Web API sample
const headerDiv: HTMLDivElement = this.createHTMLDivElement("create_container", true, `Click to create ${WebAPIControl._entityName} record`);
this._container.appendChild(headerDiv);
// Create button 1 to create record with revenue field set to 100
const value1 = "100";
this._createEntity1Button = this.createHTMLButtonElement(
this.getCreateRecordButtonLabel(value1),
this.getCreateButtonId(value1),
value1,
this.createButtonOnClickHandler.bind(this));
// Create button 2 to create record with revenue field set to 200
const value2 = "200";
this._createEntity2Button = this.createHTMLButtonElement(
this.getCreateRecordButtonLabel(value2),
this.getCreateButtonId(value2),
value2,
this.createButtonOnClickHandler.bind(this));
// Create button 3 to create record with revenue field set to 300
const value3 = "300";
this._createEntity3Button = this.createHTMLButtonElement(
this.getCreateRecordButtonLabel(value3),
this.getCreateButtonId(value3),
value3,
this.createButtonOnClickHandler.bind(this));
// Append all button HTML elements to custom control container div
this._container.appendChild(this._createEntity1Button);
this._container.appendChild(this._createEntity2Button);
this._container.appendChild(this._createEntity3Button);
}
/**
* Renders example use of DeleteRecord Web API
*/
private renderDeleteExample(): void {
// Create header label for Web API sample
const headerDiv: HTMLDivElement = this.createHTMLDivElement("delete_container", true, `Click to delete ${WebAPIControl._entityName} record`);
// Render button to invoke DeleteRecord Web API call
this._deleteRecordButton = this.createHTMLButtonElement(
"Select record to delete",
"delete_button",
null,
this.deleteButtonOnClickHandler.bind(this));
// Append elements to custom control container div
this._container.appendChild(headerDiv);
this._container.appendChild(this._deleteRecordButton);
}
/**
* Renders example use of RetrieveMultiple Web API with OData
*/
private renderODataRetrieveMultipleExample(): void {
const containerClassName = "odata_status_container";
// Create header label for Web API sample
const statusDivHeader: HTMLDivElement = this.createHTMLDivElement(containerClassName, true, "Click to refresh record count");
this._odataStatusContainerDiv = this.createHTMLDivElement(containerClassName, false, undefined);
// Create button to invoke OData RetrieveMultiple Example
this._fetchXmlRefreshButton = this.createHTMLButtonElement(
"Refresh record count",
"odata_refresh",
null,
this.refreshRecordCountButtonOnClickHandler.bind(this));
// Append HTML elements to custom control container div
this._container.appendChild(statusDivHeader);
this._container.appendChild(this._odataStatusContainerDiv);
this._container.appendChild(this._fetchXmlRefreshButton);
}
/**
* Renders example use of RetrieveMultiple Web API with Fetch XML
*/
private renderFetchXmlRetrieveMultipleExample(): void {
const containerName = "fetchxml_status_container";
// Create header label for Web API sample
const statusDivHeader: HTMLDivElement = this.createHTMLDivElement(containerName, true,
`Click to calculate average value of ${WebAPIControl._currencyAttributeNameFriendlyName}`);
const statusDiv: HTMLDivElement = this.createHTMLDivElement(containerName, false, undefined);
// Create button to invoke Fetch XML RetrieveMultiple Web API example
this._oDataRefreshButton = this.createHTMLButtonElement(
`Calculate average value of ${WebAPIControl._currencyAttributeNameFriendlyName}`,
"odata_refresh",
null,
this.calculateAverageButtonOnClickHandler.bind(this));
// Append HTML Elements to custom control container div
this._container.appendChild(statusDivHeader);
this._container.appendChild(statusDiv);
this._container.appendChild(this._oDataRefreshButton);
}
/**
* Renders a 'result container' div element to inject the status of the example Web API calls
*/
private renderResultsDiv() {
// Render header label for result container
const resultDivHeader: HTMLDivElement = this.createHTMLDivElement("result_container", true,
"Result of last action");
this._container.appendChild(resultDivHeader);
// Div elements to populate with the result text
this._resultContainerDiv = this.createHTMLDivElement("result_container", false, undefined);
this._container.appendChild(this._resultContainerDiv);
// Init the result container with a notification the control was loaded
this.updateResultContainerText("Web API sample custom control loaded");
}
/**
* Event Handler for onClick of create record button
* @param event : click event
*/
private createButtonOnClickHandler(event: Event): void {
// Retrieve the value to set the currency field to from the button's attribute
const currencyAttributeValue: number = parseInt(
(event.target as Element)?.attributes?.getNamedItem("buttonvalue")?.value ?? "0"
);
// Generate unique record name by appending timestamp to _requiredAttributeValue
const recordName = `${WebAPIControl._requiredAttributeValue}_${Date.now()}`;
// Set the values for the attributes we want to set on the new record
// If you want to set additional attributes on the new record, add to data dictionary as key/value pair
const data: ComponentFramework.WebApi.Entity = {};
data[WebAPIControl._requiredAttributeName] = recordName;
data[WebAPIControl._currencyAttributeName] = currencyAttributeValue;
// Invoke the Web API to creat the new record
this._context.webAPI.createRecord(WebAPIControl._entityName, data).then(
(response: ComponentFramework.LookupValue) => {
// Callback method for successful creation of new record
// Get the ID of the new record created
const id: string = response.id;
// Generate HTML to inject into the result div to showcase the fields and values of the new record created
let resultHtml = `Created new ${ WebAPIControl._entityName } record with below values:`;
resultHtml += "<br />";
resultHtml += "<br />";
resultHtml += `id: ${id}`;
resultHtml += "<br />";
resultHtml += "<br />";
resultHtml += `${WebAPIControl._requiredAttributeName}: ${recordName}`;
resultHtml += "<br />";
resultHtml += "<br />";
resultHtml += `${WebAPIControl._currencyAttributeName}: ${currencyAttributeValue}`;
this.updateResultContainerText(resultHtml);
},
(errorResponse) => {
// Error handling code here - record failed to be created
this.updateResultContainerTextWithErrorResponse(errorResponse);
}
);
}
/**
* Event Handler for onClick of delete record button
* @param event : click event
*/
private deleteButtonOnClickHandler(): void {
// Invoke a lookup dialog to allow the user to select an existing record of type _entityName to delete
const lookUpOptions: any =
{
entityTypes: [WebAPIControl._entityName]
};
const lookUpPromise = this._context.utils.lookupObjects(lookUpOptions);
lookUpPromise.then(
// Callback method - invoked after user has selected an item from the lookup dialog
// Data parameter is the item selected in the lookup dialog
(data: ComponentFramework.LookupValue[]) => {
if (data && data[0]) {
// Get the ID and entityType of the record selected by the lookup
const id: string = data[0].id;
const entityType: string = data[0].entityType;
// Invoke the deleteRecord method of the WebAPI to delete the selected record
this._context.webAPI.deleteRecord(entityType, id).then(
(response: ComponentFramework.LookupValue) => {
// Record was deleted successfully
const responseId: string = response.id;
const responseEntityType: string = response.entityType;
// Generate HTML to inject into the result div to showcase the deleted record
this.updateResultContainerText(`Deleted ${responseEntityType} record with ID: ${responseId}`);
},
(errorResponse) => {
// Error handling code here
this.updateResultContainerTextWithErrorResponse(errorResponse);
}
);
}
},
(error) => {
// Error handling code here
this.updateResultContainerTextWithErrorResponse(error);
}
);
}
/**
* Event Handler for onClick of calculate average value button
* @param event : click event
*/
private calculateAverageButtonOnClickHandler(): void {
// Build FetchXML to retrieve the average value of _currencyAttributeName field for all _entityName records
// Add a filter to only aggregate on records that have _currencyAttributeName not set to null
let fetchXML = "<fetch distinct='false' mapping='logical' aggregate='true'>";
fetchXML += `<entity name='${WebAPIControl._entityName}'>`;
fetchXML += `<attribute name='${WebAPIControl._currencyAttributeName}' aggregate='avg' alias='average_val' />`;
fetchXML += "<filter>";
fetchXML += `<condition attribute='${WebAPIControl._currencyAttributeName}' operator='not-null' />`;
fetchXML += "</filter>";
fetchXML += "</entity>";
fetchXML += "</fetch>";
// Invoke the Web API RetrieveMultipleRecords method to calculate the aggregate value
this._context.webAPI.retrieveMultipleRecords(WebAPIControl._entityName, `?fetchXml=${ fetchXML}`).then(
(response: ComponentFramework.WebApi.RetrieveMultipleResponse) => {
// Retrieve multiple completed successfully -- retrieve the averageValue
const averageVal: number = response.entities[0].average_val;
// Generate HTML to inject into the result div to showcase the result of the RetrieveMultiple Web API call
const resultHTML = `Average value of ${WebAPIControl._currencyAttributeNameFriendlyName} attribute for all ${WebAPIControl._entityName} records: ${averageVal}`;
this.updateResultContainerText(resultHTML);
},
(errorResponse) => {
// Error handling code here
this.updateResultContainerTextWithErrorResponse(errorResponse);
}
);
}
/**
* Event Handler for onClick of calculate record count button
* @param event : click event
*/
private refreshRecordCountButtonOnClickHandler(): void {
// Generate OData query string to retrieve the _currencyAttributeName field for all _entityName records
// Add a filter to only retrieve records with _requiredAttributeName field which contains _requiredAttributeValue
const queryString = `?$select=${WebAPIControl._currencyAttributeName }&$filter=contains(${WebAPIControl._requiredAttributeName},'${WebAPIControl._requiredAttributeValue}')`;
// Invoke the Web API Retrieve Multiple call
this._context.webAPI.retrieveMultipleRecords(WebAPIControl._entityName, queryString).then(
(response: ComponentFramework.WebApi.RetrieveMultipleResponse) => {
// Retrieve Multiple Web API call completed successfully
let count1 = 0;
let count2 = 0;
let count3 = 0;
// Loop through each returned record
for (const entity of response.entities) {
// Retrieve the value of _currencyAttributeName field
const value: number = entity[WebAPIControl._currencyAttributeName];
// Check the value of _currencyAttributeName field and increment the correct counter
if (value == 100) {
count1++;
}
else if (value == 200) {
count2++;
}
else if (value == 300) {
count3++;
}
}
// Generate HTML to inject into the fetch xml status div to showcase the results of the OData retrieve example
let innerHtml = "Use above buttons to create or delete a record to see count update";
innerHtml += "<br />";
innerHtml += "<br />";
innerHtml += `Count of ${WebAPIControl._entityName} records with ${WebAPIControl._currencyAttributeName} of 100: ${count1}`;
innerHtml += "<br />";
innerHtml += `Count of ${WebAPIControl._entityName} records with ${WebAPIControl._currencyAttributeName} of 200: ${count2}`;
innerHtml += "<br />";
innerHtml += `Count of ${WebAPIControl._entityName} records with ${WebAPIControl._currencyAttributeName} of 300: ${count3}`;
// Inject the HTML into the fetch xml status div
if (this._odataStatusContainerDiv) {
this._odataStatusContainerDiv.innerHTML = innerHtml;
}
// Inject a success message into the result div
this.updateResultContainerText("Record count refreshed");
},
(errorResponse) => {
// Error handling code here
this.updateResultContainerTextWithErrorResponse(errorResponse);
}
);
}
/**
* Helper method to inject HTML into result container div
* @param statusHTML : HTML to inject into result container
*/
private updateResultContainerText(statusHTML: string): void {
if (this._resultContainerDiv) {
this._resultContainerDiv.innerHTML = statusHTML;
}
}
/**
* Helper method to inject error string into result container div after failed Web API call
* @param errorResponse : error object from rejected promise
*/
private updateResultContainerTextWithErrorResponse(errorResponse: any): void {
if (this._resultContainerDiv) {
// Retrieve the error message from the errorResponse and inject into the result div
let errorHTML = "Error with Web API call:";
errorHTML += "<br />";
errorHTML += errorResponse.message;
this._resultContainerDiv.innerHTML = errorHTML;
}
}
/**
* Helper method to generate Label for Create Buttons
* @param entityNumber : value to set _currencyAttributeNameFriendlyName field to for this button
*/
private getCreateRecordButtonLabel(entityNumber: string): string {
return `Create record with ${WebAPIControl._currencyAttributeNameFriendlyName} of ${entityNumber}`;
}
/**
* Helper method to generate ID for Create Button
* @param entityNumber : value to set _currencyAttributeNameFriendlyName field to for this button
*/
private getCreateButtonId(entityNumber: string): string {
return `create_button_${entityNumber}`;
}
/**
* Helper method to create HTML Button used for CreateRecord Web API Example
* @param buttonLabel : Label for button
* @param buttonId : ID for button
* @param buttonValue : value of button (attribute of button)
* @param onClickHandler : onClick event handler to invoke for the button
*/
private createHTMLButtonElement(buttonLabel: string, buttonId: string, buttonValue: string | null, onClickHandler: (event?: any) => void): HTMLButtonElement {
const button: HTMLButtonElement = document.createElement("button");
button.innerHTML = buttonLabel;
if (buttonValue) {
button.setAttribute("buttonvalue", buttonValue);
}
button.id = buttonId;
button.classList.add("SampleControl_WebAPIControl_ButtonClass");
button.addEventListener("click", onClickHandler);
return button;
}
/**
* Helper method to create HTML Div Element
* @param elementClassName : Class name of div element
* @param isHeader : True if 'header' div - adds extra class and post-fix to ID for header elements
* @param innerText : innerText of Div Element
*/
private createHTMLDivElement(elementClassName: string, isHeader: boolean, innerText?: string): HTMLDivElement {
const div: HTMLDivElement = document.createElement("div");
if (isHeader) {
div.classList.add("SampleControl_WebAPIControl_Header");
elementClassName += "_header";
}
if (innerText) {
div.innerText = innerText.toUpperCase();
}
div.classList.add(elementClassName);
return div;
}
} | the_stack |
import { update } from '../../src/spec/update/update';
import { RemoveChange } from '../../lib/utility/change';
import { Tree } from '@angular-devkit/schematics';
import { SchematicTestRunner } from '@angular-devkit/schematics/testing';
import { collectionPath } from './common';
describe('Update a spec', () => {
it('should return a remove list', async () => {
const result = update(
'./test',
`import { autoSpy } from 'autoSpy';
import { ExampleComponent } from './example.component';
describe('ExampleComponent', () => {
});
function setup() {
let dep:string;
const service = autoSpy(Object);
const builder = {
dep,
service,
default() {
return builder;
},
build() {
return new ExampleComponent(dep,service);
}
};
return builder;
}`,
[],
'ExampleComponent',
'remove',
[],
'a'
);
const removes = result.filter((r) => r instanceof RemoveChange);
// expecting 6 removes
expect(removes.length).toBe(6);
// order is the position of the remove
expect(removes[0].order).toBe(152); // let dep:string;
expect(removes[1].order).toBe(172); // const service = autoSpy(Object);
expect(removes[2].order).toBe(231); // dep in builder
expect(removes[3].order).toBe(244); // service in builder
expect(removes[4].order).toBe(379); // dep, in ExampleComponent(dep, service)
expect(removes[5].order).toBe(383); // service in ExampleComponent(dep, service)
});
describe('with pre-exising spec (UPDATE)', () => {
let treeWithASpec = Tree.empty();
beforeEach(() => {
treeWithASpec = Tree.empty();
// a class with anotherStr and anotherService as constructor parameters
treeWithASpec.create(
'to-update.ts',
`export class ToUpdate {
constructor(anotherStr: string, anotherService: Service) {}
}`
);
// create a .spec file next to to-update.ts with the anotherStr and anotherService as constructor parameters
treeWithASpec.create(
'to-update.spec.ts',
`import { ToUpdate } from "./to-update";
describe("ToUpdate", () => {});
function setup() {
let stringDependency: string;
const service = autoSpy(Object);
const builder = {
stringDependency,
service,
default() {
return builder;
},
build() {
return new ToUpdate(stringDependency, service);
}
};
return builder;
}`
);
});
it('removes the removed dependencies', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
// ToUpdate class has new deps - so we need to update the existing spec file
const result = await runner
.runSchematicAsync('spec', { name: 'to-update.ts', update: true }, treeWithASpec)
.toPromise();
// assert
const contents = result.readContent('to-update.spec.ts');
expect(contents.includes('ToUpdate(stringDependency, service)')).toBe(false);
});
it('adds the added dependencies', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
// ToUpdate class has new deps - so we need to update the existing spec file
const result = await runner
.runSchematicAsync('spec', { name: 'to-update.ts', update: true }, treeWithASpec)
.toPromise();
// assert
const contents = result.readContent('to-update.spec.ts');
expect(contents.includes('let anotherStr: string;')).toBe(true);
expect(contents.includes('const anotherService = autoSpy(Service);')).toBe(true);
});
it('adds the added dependencies to builder `exports`', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
// ToUpdate class has new deps - so we need to update the existing spec file
const result = await runner
.runSchematicAsync('spec', { name: 'to-update.ts', update: true }, treeWithASpec)
.toPromise();
// assert
const contents = result.readContent('to-update.spec.ts');
expect(contents.includes(' anotherStr,')).toBe(true);
expect(contents.includes(' anotherService,')).toBe(true);
});
it('adds the added dependencies to the class-under-test construction', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
// ToUpdate class has new deps - so we need to update the existing spec file
const result = await runner
.runSchematicAsync('spec', { name: 'to-update.ts', update: true }, treeWithASpec)
.toPromise();
// assert
const contents = result.readContent('to-update.spec.ts');
expect(contents).toMatch(/return new ToUpdate\(anotherStr,\s*anotherService\)/);
});
it('Errors if the update flag is not passed in', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
treeWithASpec.overwrite('to-update.spec.ts', `Some other content`);
// act
// assert
return runner
.runSchematicAsync('spec', { name: 'to-update.ts' }, treeWithASpec)
.toPromise()
.then(() => fail('should throw'))
.catch((e) => expect(e).toBeDefined());
});
});
describe('with pre-existing spec (UPDATE Methods)', () => {
let treeWithASpec = Tree.empty();
beforeEach(() => {
treeWithASpec = Tree.empty();
// a class with anotherStr and anotherService as constructor parameters
treeWithASpec.create(
'to-update.ts',
`export class ToUpdate {
constructor() {}
oldMethod() {}
newMethod() {}
}`
);
// create a .spec file next to to-update.ts with the anotherStr and anotherService as constructor parameters
// it already has
treeWithASpec.create(
'to-update.spec.ts',
`import { ToUpdate } from "./to-update";
describe('ToUpdate', () => {
it('when oldMethod is called it should', () => {
c.oldMethod();
});
});
function setup() {
const builder = {
default() {
return builder;
},
build() {
return new ToUpdate(stringDependency, service);
}
};
return builder;
}`
);
});
it('adds the missing public method tests', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
// ToUpdate class has new deps - so we need to update the existing spec file
const result = await runner
.runSchematicAsync('spec', { name: 'to-update.ts', update: true }, treeWithASpec)
.toPromise();
// assert
const contents = result.readContent('to-update.spec.ts');
expect(contents.includes('when newMethod is called it should')).toBe(true);
});
it('does not add (would duplicate) the existing public method tests', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
// ToUpdate class has new deps - so we need to update the existing spec file
const result = await runner
.runSchematicAsync('spec', { name: 'to-update.ts', update: true }, treeWithASpec)
.toPromise();
// assert
const contents = result.readContent('to-update.spec.ts');
// splitting by the expected it description - if there is one such it -
// then we'll get 2 results otherwise - 1, 3 or more
expect(contents.split('when oldMethod is called it should').length).toBe(
2
//"We expect to see 2 results because when splitting by the expected it description - if there is one such it method - then we'll get 2 results otherwise - 1, 3 or more"
);
});
it('adds the it at the correct location after the last it', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
// ToUpdate class has new deps - so we need to update the existing spec file
const result = await runner
.runSchematicAsync('spec', { name: 'to-update.ts', update: true }, treeWithASpec)
.toPromise();
// assert
const contents = result.readContent('to-update.spec.ts');
expect(contents).toMatch(
/it\('when oldMethod is called it should', \(\) => \{(\r\n|\n\r|\n)\s*c\.oldMethod\(\);(\r\n|\n\r|\n)\s*\}\);(\r\n|\n\r|\n)\s*it\('when newMethod is called it should/
);
});
describe('with no it methods', () => {
let treeWithASpecAndOnlyDescribe: Tree;
beforeEach(() => {
treeWithASpecAndOnlyDescribe = Tree.empty();
// a class with anotherStr and anotherService as constructor parameters
treeWithASpecAndOnlyDescribe.create(
'to-update.ts',
`
export class ToUpdate {
constructor() {}
method() {}
}`
);
treeWithASpecAndOnlyDescribe.create(
'to-update.spec.ts',
`
import { ToUpdate } from "./to-update";
describe('ToUpdate', () => {
});
function setup() {
const builder = {
default() {
return builder;
},
build() {
return new ToUpdate(stringDependency, service);
}
};
return builder;
}`
);
});
it('adds the it at the correct location after the last describe', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
// ToUpdate class has new deps - so we need to update the existing spec file
const result = await runner
.runSchematicAsync(
'spec',
{ name: 'to-update.ts', update: true },
treeWithASpecAndOnlyDescribe
)
.toPromise();
// assert
const contents = result.readContent('to-update.spec.ts');
// splitting by the expected it description - if there is one such it -
// then we'll get 2 results otherwise - 1, 3 or more
expect(contents).toMatch(
/describe\('ToUpdate', \(\) => \{(\r\n|\n\r|\n)\s*it\('when method is called it should/
);
});
it('uses the correct shorthand (ToUpdate shorthand t)', async () => {
// arrange
const runner = new SchematicTestRunner('schematics', collectionPath);
// act
// ToUpdate class has new deps - so we need to update the existing spec file
const result = await runner
.runSchematicAsync(
'spec',
{ name: 'to-update.ts', update: true },
treeWithASpecAndOnlyDescribe
)
.toPromise();
// assert
const contents = result.readContent('to-update.spec.ts');
// splitting by the expected it description - if there is one such it -
// then we'll get 2 results otherwise - 1, 3 or more
expect(contents).toMatch('t.method();');
expect(contents).toMatch('expect(t).toEqual');
});
});
describe('when there are existing deps in the class-under-test constructor', () => {
let treeForComma = Tree.empty();
beforeEach(() => {
treeForComma = Tree.empty();
treeForComma.create(
't.ts',
`
export class T {
constructor(a: string, b:string) {}
}`
);
treeForComma.create(
't.spec.ts',
`
describe('existing spec', () => {
});
function setup() {
let a: string;
const builder = {
a,
build() {
return new T(a);
}
}
}
`
);
});
it('should add a comma at the start of the deps list', async () => {
// arrange
let runner = new SchematicTestRunner('schematics', collectionPath);
// act
const result = await runner
.runSchematicAsync('spec', { name: 't.ts', update: true }, treeForComma)
.toPromise();
// assert
const content = result.readContent('t.spec.ts');
expect(content).toMatch(/return new T\(a, b\);/);
});
});
});
}); | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Provides a hosted connection on the specified interconnect or a link aggregation group (LAG) of interconnects. Intended for use by AWS Direct Connect Partners only.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const hosted = new aws.directconnect.HostedConnection("hosted", {
* bandwidth: "100Mbps",
* connectionId: "dxcon-ffabc123",
* ownerAccountId: "123456789012",
* vlan: 1,
* });
* ```
*/
export class HostedConnection extends pulumi.CustomResource {
/**
* Get an existing HostedConnection 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?: HostedConnectionState, opts?: pulumi.CustomResourceOptions): HostedConnection {
return new HostedConnection(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:directconnect/hostedConnection:HostedConnection';
/**
* Returns true if the given object is an instance of HostedConnection. 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 HostedConnection {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === HostedConnection.__pulumiType;
}
/**
* The Direct Connect endpoint on which the physical connection terminates.
*/
public /*out*/ readonly awsDevice!: pulumi.Output<string>;
/**
* The bandwidth of the connection. Valid values for dedicated connections: 1Gbps, 10Gbps. Valid values for hosted connections: 50Mbps, 100Mbps, 200Mbps, 300Mbps, 400Mbps, 500Mbps, 1Gbps, 2Gbps, 5Gbps and 10Gbps. Case sensitive.
*/
public readonly bandwidth!: pulumi.Output<string>;
/**
* The ID of the interconnect or LAG.
*/
public readonly connectionId!: pulumi.Output<string>;
/**
* Indicates whether the connection supports a secondary BGP peer in the same address family (IPv4/IPv6).
*/
public /*out*/ readonly hasLogicalRedundancy!: pulumi.Output<string>;
/**
* Boolean value representing if jumbo frames have been enabled for this connection.
*/
public /*out*/ readonly jumboFrameCapable!: pulumi.Output<boolean>;
/**
* The ID of the LAG.
*/
public /*out*/ readonly lagId!: pulumi.Output<string>;
/**
* The time of the most recent call to [DescribeLoa](https://docs.aws.amazon.com/directconnect/latest/APIReference/API_DescribeLoa.html) for this connection.
*/
public /*out*/ readonly loaIssueTime!: pulumi.Output<string>;
/**
* The location of the connection.
*/
public /*out*/ readonly location!: pulumi.Output<string>;
/**
* The name of the connection.
*/
public readonly name!: pulumi.Output<string>;
/**
* The ID of the AWS account of the customer for the connection.
*/
public readonly ownerAccountId!: pulumi.Output<string>;
/**
* The name of the AWS Direct Connect service provider associated with the connection.
*/
public /*out*/ readonly partnerName!: pulumi.Output<string>;
/**
* The name of the service provider associated with the connection.
*/
public /*out*/ readonly providerName!: pulumi.Output<string>;
/**
* The AWS Region where the connection is located.
*/
public /*out*/ readonly region!: pulumi.Output<string>;
/**
* The state of the connection. Possible values include: ordering, requested, pending, available, down, deleting, deleted, rejected, unknown. See [AllocateHostedConnection](https://docs.aws.amazon.com/directconnect/latest/APIReference/API_AllocateHostedConnection.html) for a description of each connection state.
*/
public /*out*/ readonly state!: pulumi.Output<string>;
/**
* The dedicated VLAN provisioned to the hosted connection.
*/
public readonly vlan!: pulumi.Output<number>;
/**
* Create a HostedConnection 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: HostedConnectionArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: HostedConnectionArgs | HostedConnectionState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as HostedConnectionState | undefined;
inputs["awsDevice"] = state ? state.awsDevice : undefined;
inputs["bandwidth"] = state ? state.bandwidth : undefined;
inputs["connectionId"] = state ? state.connectionId : undefined;
inputs["hasLogicalRedundancy"] = state ? state.hasLogicalRedundancy : undefined;
inputs["jumboFrameCapable"] = state ? state.jumboFrameCapable : undefined;
inputs["lagId"] = state ? state.lagId : undefined;
inputs["loaIssueTime"] = state ? state.loaIssueTime : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["ownerAccountId"] = state ? state.ownerAccountId : undefined;
inputs["partnerName"] = state ? state.partnerName : undefined;
inputs["providerName"] = state ? state.providerName : undefined;
inputs["region"] = state ? state.region : undefined;
inputs["state"] = state ? state.state : undefined;
inputs["vlan"] = state ? state.vlan : undefined;
} else {
const args = argsOrState as HostedConnectionArgs | undefined;
if ((!args || args.bandwidth === undefined) && !opts.urn) {
throw new Error("Missing required property 'bandwidth'");
}
if ((!args || args.connectionId === undefined) && !opts.urn) {
throw new Error("Missing required property 'connectionId'");
}
if ((!args || args.ownerAccountId === undefined) && !opts.urn) {
throw new Error("Missing required property 'ownerAccountId'");
}
if ((!args || args.vlan === undefined) && !opts.urn) {
throw new Error("Missing required property 'vlan'");
}
inputs["bandwidth"] = args ? args.bandwidth : undefined;
inputs["connectionId"] = args ? args.connectionId : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["ownerAccountId"] = args ? args.ownerAccountId : undefined;
inputs["vlan"] = args ? args.vlan : undefined;
inputs["awsDevice"] = undefined /*out*/;
inputs["hasLogicalRedundancy"] = undefined /*out*/;
inputs["jumboFrameCapable"] = undefined /*out*/;
inputs["lagId"] = undefined /*out*/;
inputs["loaIssueTime"] = undefined /*out*/;
inputs["location"] = undefined /*out*/;
inputs["partnerName"] = undefined /*out*/;
inputs["providerName"] = undefined /*out*/;
inputs["region"] = undefined /*out*/;
inputs["state"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(HostedConnection.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering HostedConnection resources.
*/
export interface HostedConnectionState {
/**
* The Direct Connect endpoint on which the physical connection terminates.
*/
awsDevice?: pulumi.Input<string>;
/**
* The bandwidth of the connection. Valid values for dedicated connections: 1Gbps, 10Gbps. Valid values for hosted connections: 50Mbps, 100Mbps, 200Mbps, 300Mbps, 400Mbps, 500Mbps, 1Gbps, 2Gbps, 5Gbps and 10Gbps. Case sensitive.
*/
bandwidth?: pulumi.Input<string>;
/**
* The ID of the interconnect or LAG.
*/
connectionId?: pulumi.Input<string>;
/**
* Indicates whether the connection supports a secondary BGP peer in the same address family (IPv4/IPv6).
*/
hasLogicalRedundancy?: pulumi.Input<string>;
/**
* Boolean value representing if jumbo frames have been enabled for this connection.
*/
jumboFrameCapable?: pulumi.Input<boolean>;
/**
* The ID of the LAG.
*/
lagId?: pulumi.Input<string>;
/**
* The time of the most recent call to [DescribeLoa](https://docs.aws.amazon.com/directconnect/latest/APIReference/API_DescribeLoa.html) for this connection.
*/
loaIssueTime?: pulumi.Input<string>;
/**
* The location of the connection.
*/
location?: pulumi.Input<string>;
/**
* The name of the connection.
*/
name?: pulumi.Input<string>;
/**
* The ID of the AWS account of the customer for the connection.
*/
ownerAccountId?: pulumi.Input<string>;
/**
* The name of the AWS Direct Connect service provider associated with the connection.
*/
partnerName?: pulumi.Input<string>;
/**
* The name of the service provider associated with the connection.
*/
providerName?: pulumi.Input<string>;
/**
* The AWS Region where the connection is located.
*/
region?: pulumi.Input<string>;
/**
* The state of the connection. Possible values include: ordering, requested, pending, available, down, deleting, deleted, rejected, unknown. See [AllocateHostedConnection](https://docs.aws.amazon.com/directconnect/latest/APIReference/API_AllocateHostedConnection.html) for a description of each connection state.
*/
state?: pulumi.Input<string>;
/**
* The dedicated VLAN provisioned to the hosted connection.
*/
vlan?: pulumi.Input<number>;
}
/**
* The set of arguments for constructing a HostedConnection resource.
*/
export interface HostedConnectionArgs {
/**
* The bandwidth of the connection. Valid values for dedicated connections: 1Gbps, 10Gbps. Valid values for hosted connections: 50Mbps, 100Mbps, 200Mbps, 300Mbps, 400Mbps, 500Mbps, 1Gbps, 2Gbps, 5Gbps and 10Gbps. Case sensitive.
*/
bandwidth: pulumi.Input<string>;
/**
* The ID of the interconnect or LAG.
*/
connectionId: pulumi.Input<string>;
/**
* The name of the connection.
*/
name?: pulumi.Input<string>;
/**
* The ID of the AWS account of the customer for the connection.
*/
ownerAccountId: pulumi.Input<string>;
/**
* The dedicated VLAN provisioned to the hosted connection.
*/
vlan: pulumi.Input<number>;
} | the_stack |
import expect = require("expect");
import StorageManager from "@worldbrain/storex";
import { DexieStorageBackend } from '@worldbrain/storex-backend-dexie'
import { ChangeWatchMiddleware } from '@worldbrain/storex-middleware-change-watcher';
import inMemory from '@worldbrain/storex-backend-dexie/lib/in-memory'
import { createMultiApiTestSuite, TestSetup, MultiApiOptions } from "./index.tests";
import * as api from "../../public-api";
import { ClientEvent } from '../../public-api';
export default createMultiApiTestSuite('Remote apps', ({ it }) => {
it('should proxy operations into a remote app', async ({ createSession: api }) => {
const operations: any[] = []
const { api: memex } = await api({
type: 'websocket',
callbacks: {
handleRemoteOperation: async (options) => {
operations.push(options)
return { status: 'success', result: ['foo', 'bla'] }
}
}
})
await memex.registerApp({ name: 'memex', identify: true, remote: true })
const { api: backupApp } = await api({ type: 'http' })
await backupApp.registerApp({ name: 'backup', identify: true })
const response = await backupApp.executeRemoteOperation({
app: 'memex',
operation: ['findObjects', 'pages', { url: 'foo.com/bar' }]
})
expect(operations).toEqual([{
sourceApp: 'backup',
operation: ['findObjects', 'pages', { url: 'foo.com/bar' }]
}])
expect(response).toEqual({
status: 'success',
result: ['foo', 'bla']
})
})
async function setupChangeEventTest(createSession: TestSetup<MultiApiOptions, true>['createSession'], testOptions?: {
testSynchronous?: boolean
}) {
const collectionsToWatch = new Set<string>()
const backend = new DexieStorageBackend({ dbName: 'memex', idbImplementation: inMemory() })
const memexStorageManager = new StorageManager({ backend })
memexStorageManager.registry.registerCollections({
tags: {
version: new Date(),
fields: {
name: { type: 'string' },
url: { type: 'string' }
},
indices: [
{ field: ['name', 'url'], pk: true }
],
}
})
let subscriptionCount = 0
let memexSubscriptions: { [id: string]: api.RemoteStorageChangeSubscriptionRequest_v0 } = {}
const { api: memex } = await createSession({
type: 'websocket',
callbacks: {
handleSubscription: async ({ request }) => {
const subscriptionId = (subscriptionCount++).toString()
memexSubscriptions[subscriptionId] = request
if (request.type === 'storage-change') {
for (const collection of request.collections || []) {
collectionsToWatch.add(collection)
}
}
return { status: 'success', subscriptionId }
},
handleUnsubscription: async ({ subscriptionId }) => {
delete memexSubscriptions[subscriptionId]
return { status: 'success' }
}
}
})
await memex.registerApp({ name: 'memex', identify: true, remote: true })
const changeWatchMiddleware = new ChangeWatchMiddleware({
storageManager: memexStorageManager,
shouldWatchCollection: collection => collectionsToWatch.has(collection),
postprocessOperation: async context => {
await memex.emitEvent({
event: { type: 'storage-change', info: context.info },
synchronous: testOptions?.testSynchronous
})
}
})
await memexStorageManager.finishInitialization()
memexStorageManager.setMiddleware([
changeWatchMiddleware
])
const events: api.ClientEvent[] = []
const { api: backupApp } = await createSession({
type: 'websocket',
callbacks: {
handleEvent: (options) => {
const push = () => { events.push(options.event) }
if (testOptions?.testSynchronous) {
return new Promise(resolve => {
setTimeout(() => {
push()
resolve()
}, 20)
})
} else {
return Promise.resolve(push())
}
}
}
})
await backupApp.registerApp({ name: 'backup', identify: true })
const subscriptionResult = await backupApp.subscribeToEvent({
request: {
type: 'storage-change',
app: 'memex',
collections: ['tags'],
}
})
if (subscriptionResult.status !== 'success') {
throw new Error('Subscription was not successful')
}
expect(memexSubscriptions).toEqual({
'0': {
type: 'storage-change',
app: 'memex',
collections: ['tags'],
}
})
return { memexStorageManager, memexSubscriptions, events, subscriptionResult, backupApp }
}
it('should let remote apps signal changes to their local storage', async ({ createSession }) => {
const { memexStorageManager, events } = await setupChangeEventTest(createSession)
await memexStorageManager.collection('tags').createObject({
url: 'foo.com/test',
name: 'bla'
})
const expectedEvents: ClientEvent[] = [
{
type: 'storage-change',
app: 'memex',
info: {
changes: [
{
type: "create",
collection: "tags",
pk: ['bla', 'foo.com/test'],
values: {},
},
],
},
},
];
expect(events).toEqual(expectedEvents)
})
// it('should let remote apps signal changes to their local storage and wait for all handlers to resolve', async ({ createSession }) => {
// const { memexStorageManager, events } = await setupChangeEventTest(createSession, {
// testSynchronous: true
// })
// await memexStorageManager.collection('tags').createObject({
// url: 'foo.com/test',
// name: 'bla'
// })
// const expectedEvents: ClientEvent[] = [
// {
// type: 'storage-change',
// app: 'memex',
// info: {
// changes: [
// {
// type: "create",
// collection: "tags",
// pk: ['bla', 'foo.com/test'],
// values: {},
// },
// ],
// },
// },
// ]
// expect(events).toEqual(expectedEvents)
// })
it('should let remote apps signal changes to their local storage and unsubscribe from events', async ({ createSession }) => {
const { memexStorageManager, memexSubscriptions, events, backupApp, subscriptionResult } = await setupChangeEventTest(createSession)
await memexStorageManager.collection('tags').createObject({
url: 'foo.com/test',
name: 'bla'
})
await backupApp.unsubscribeFromEvent({ subscriptionId: subscriptionResult.subscriptionId })
expect(memexSubscriptions).toEqual({})
await memexStorageManager.collection('tags').createObject({
url: 'foo.com/test',
name: 'blub'
})
expect(events).toEqual([
{
type: "storage-change",
app: 'memex',
info: {
changes: [
{
type: "create",
collection: "tags",
pk: ['bla', 'foo.com/test'],
values: {},
},
],
},
}
])
})
it('should detect when a remote app becomes available and goes down', async ({ createSession }) => {
const receivedEvents: ClientEvent[] = []
const { api: backupApp } = await createSession({
type: 'websocket',
callbacks: {
async handleEvent({ event }) {
receivedEvents.push(event)
}
}
})
await backupApp.registerApp({ name: 'backup', identify: true })
await backupApp.subscribeToEvent({
request: { type: 'app-availability-changed' }
})
const { api: memexApp } = await createSession({ type: 'websocket', })
await memexApp.registerApp({ name: 'memex', identify: true, remote: true })
expect(receivedEvents).toEqual([
{ type: 'app-availability-changed', app: 'memex', availability: true }
])
receivedEvents.splice(0)
await memexApp.destroySession()
expect(receivedEvents).toEqual([
{ type: 'app-availability-changed', app: 'memex', availability: false }
])
})
it('should dispatch remote calls', async ({ createSession }) => {
const handledCalls: Array<any> = []
const { api: memex } = await createSession({
type: 'websocket',
callbacks: {
handleRemoteCall: async (options) => {
const result = 'foo'
handledCalls.push({ options, result })
return { status: 'success', result }
}
}
})
await memex.registerApp({ name: 'memex', identify: true, remote: true })
const { api: pocket } = await createSession({
type: 'websocket',
})
await pocket.registerApp({ name: 'pocket', identify: true })
const callOptions = {
call: 'savePage',
args: {
url: 'https://www.test.com',
bookmark: true,
}
}
const callResult = await pocket.executeRemoteCall({
app: 'memex',
...callOptions,
})
expect(handledCalls).toEqual([
{ options: callOptions, result: 'foo' }
])
expect(callResult).toEqual({
status: 'success',
result: 'foo',
})
})
it('should return remote call errors', async ({ createSession }) => {
const error = { status: 'internal-error' as 'internal-error', errorStatus: 'something-memex-y', errorText: 'Could not something' }
const { api: memex } = await createSession({
type: 'websocket',
callbacks: {
handleRemoteCall: async (options) => {
return error
}
}
})
await memex.registerApp({ name: 'memex', identify: true, remote: true })
const { api: pocket } = await createSession({
type: 'websocket',
})
await pocket.registerApp({ name: 'pocket', identify: true })
const callOptions = {
call: 'savePage',
args: {
url: 'https://www.test.com',
bookmark: true,
}
}
const callResult = await pocket.executeRemoteCall({
app: 'memex',
...callOptions,
})
expect(callResult).toEqual(error)
})
it('should return remote call errors', async ({ createSession }) => {
const error = { status: 'internal-error' as 'internal-error', errorStatus: 'something-memex-y', errorText: 'Could not something' }
const { api: memex } = await createSession({
type: 'websocket',
callbacks: {
handleRemoteCall: async (options) => {
return error
}
}
})
await memex.registerApp({ name: 'memex', identify: true, remote: true })
const { api: pocket } = await createSession({
type: 'websocket',
})
await pocket.registerApp({ name: 'pocket', identify: true })
const callOptions = {
call: 'savePage',
args: {
url: 'https://www.test.com',
bookmark: true,
}
}
const callResult = await pocket.executeRemoteCall({
app: 'memex',
...callOptions,
})
expect(callResult).toEqual(error)
})
it('should detect remote call to non-existing apps', async ({ createSession }) => {
const { api: pocket } = await createSession({
type: 'websocket',
})
await pocket.registerApp({ name: 'pocket', identify: true })
const callOptions = {
call: 'savePage',
args: {
url: 'https://www.test.com',
bookmark: true,
}
}
const callResult = await pocket.executeRemoteCall({
app: 'memex',
...callOptions,
})
expect(callResult).toEqual({ status: 'app-not-found' })
})
}) | the_stack |
* @title: Leaderboards
* @description:
* An example of how to set and view scores from the leaderboards.
*/
/*{{ javascript("jslib/observer.js") }}*/
/*{{ javascript("jslib/requesthandler.js") }}*/
/*{{ javascript("jslib/utilities.js") }}*/
/*{{ javascript("jslib/services/turbulenzservices.js") }}*/
/*{{ javascript("jslib/services/turbulenzbridge.js") }}*/
/*{{ javascript("jslib/services/leaderboardmanager.js") }}*/
/*{{ javascript("jslib/services/gameprofilemanager.js") }}*/
/*{{ javascript("jslib/services/gamesession.js") }}*/
/*{{ javascript("jslib/services/mappingtable.js") }}*/
/*{{ javascript("jslib/shadermanager.js") }}*/
/*{{ javascript("jslib/draw2d.js") }}*/
/*{{ javascript("jslib/fontmanager.js") }}*/
/*{{ javascript("jslib/assetcache.js") }}*/
/*{{ javascript("scripts/htmlcontrols.js") }}*/
/*global TurbulenzEngine: true */
/*global TurbulenzServices: false */
/*global GameProfileManager: false */
/*global RequestHandler: false */
/*global Draw2D: false */
/*global FontManager: false */
/*global ShaderManager: false */
/*global HTMLControls: false */
/*global AssetCache: false */
TurbulenzEngine.onload = function onloadFn()
{
//==========================================================================
// Turbulenz Initialization
//==========================================================================
var graphicsDevice = TurbulenzEngine.createGraphicsDevice({});
var mathDevice = TurbulenzEngine.createMathDevice({});
var inputDevice = TurbulenzEngine.createInputDevice({});
var requestHandler = RequestHandler.create({});
var fontManager = FontManager.create(graphicsDevice, requestHandler);
var shaderManager = ShaderManager.create(graphicsDevice, requestHandler);
var font, fontShader;
// Not Power Of 2 shader (needed for rendering user avatars)
var npot2DShader;
var upTexture, downTexture;
var leaderboardManager;
var gameProfileManager;
var userProfile;
var gameSession;
var assetsToLoad = 5;
function mappingTableReceived(mappingTable)
{
var urlMapping = mappingTable.urlMapping;
var assetPrefix = mappingTable.assetPrefix;
fontManager.setPathRemapping(urlMapping, assetPrefix);
fontManager.load('fonts/hero.fnt', function (fontObject)
{
font = fontObject;
assetsToLoad -= 1;
});
shaderManager.setPathRemapping(urlMapping, assetPrefix);
shaderManager.load('shaders/font.cgfx', function (shaderObject)
{
fontShader = shaderObject;
assetsToLoad -= 1;
});
shaderManager.load('shaders/npot2D.cgfx', function (shaderObject)
{
npot2DShader = shaderObject;
assetsToLoad -= 1;
});
graphicsDevice.createTexture({
src: mappingTable.getURL('textures/up.png'),
mipmaps: true,
onload: function onLoadedTextureFn(texture)
{
upTexture = texture;
assetsToLoad -= 1;
}
});
graphicsDevice.createTexture({
src: mappingTable.getURL('textures/down.png'),
mipmaps: true,
onload: function onLoadedTextureFn(texture)
{
downTexture = texture;
assetsToLoad -= 1;
}
});
}
function sessionCreated()
{
TurbulenzServices.createMappingTable(
requestHandler,
gameSession,
mappingTableReceived
);
leaderboardManager =
TurbulenzServices.createLeaderboardManager(requestHandler,
gameSession);
gameProfileManager =
GameProfileManager.create(requestHandler, gameSession);
userProfile = TurbulenzServices.createUserProfile(requestHandler);
}
gameSession = TurbulenzServices.createGameSession(requestHandler, sessionCreated);
var draw2D;
var status = [];
function setStatus(msg)
{
status.push(msg);
}
function clearStatus(delay?)
{
TurbulenzEngine.setTimeout(function () {
status.shift();
}, delay || 500);
}
var clearColor = mathDevice.v4Build(0.3, 0.3, 0.3, 1.0);
var fontTechnique, fontTechniqueParameters;
var npot2DTechniqueParameters;
var avatarCache = AssetCache.create({
size: 64,
onLoad: function loadTextureFn(key, params, loadedCallback)
{
graphicsDevice.createTexture({
src: key,
// since the avatar image might not be a power of 2 we cannot enable mipmaps
mipmaps: false,
onload: loadedCallback
});
},
onDestroy: function destroyTextureFn(key, texture)
{
if (texture)
{
texture.destroy();
}
}
});
var titleScale = 1.2;
var normalScale = 0.75;
var statusScale = 0.6;
var currentLeaderboardResult;
var defaultColor = mathDevice.v4Build(1, 1, 1, 1);
var playerColor = mathDevice.v4Build(1, 0, 0, 1);
var gameProfiles = {};
var xp = 0;
var rocketsLaunched = 0;
function mainLoop()
{
if (!graphicsDevice.beginFrame())
{
return;
}
graphicsDevice.clear(clearColor);
var clipSpace = mathDevice.v4Build(2 / graphicsDevice.width, -2 / graphicsDevice.height, -1, 1, clipSpace);
npot2DTechniqueParameters.clipSpace = clipSpace;
fontTechniqueParameters.clipSpace = clipSpace;
fontTechniqueParameters.color = defaultColor;
var xOffset = 2;
var yOffset = 0;
function newColumn()
{
xOffset += 10;
yOffset = 0;
}
function writeFont(text, scale, color?)
{
if (color === undefined)
{
color = defaultColor;
}
graphicsDevice.setTechnique(fontTechnique);
fontTechniqueParameters.color = color;
graphicsDevice.setTechniqueParameters(fontTechniqueParameters);
if (text)
{
var topLeft = draw2D.viewportUnmap(xOffset, yOffset);
var bottomRight = draw2D.viewportUnmap(xOffset + 10, yOffset + 1);
font.drawTextRect(text, {
rect : [topLeft[0], topLeft[1], bottomRight[0] - topLeft[0], bottomRight[1] - topLeft[1]],
scale : scale,
spacing : 0,
alignment : 0
});
}
yOffset += 2;
}
function drawAvatar(url)
{
var texture = avatarCache.get(url);
if (texture)
{
draw2D.draw({
texture : texture,
destinationRectangle : [xOffset, yOffset, xOffset + 1, yOffset + 1]
});
}
else if (!avatarCache.isLoading(url))
{
avatarCache.request(url);
}
yOffset += 2;
}
if (currentLeaderboardResult)
{
var view = currentLeaderboardResult.getView();
var getColor = function getColorFn(playerIndex)
{
return (playerIndex === view.playerIndex) ? playerColor : defaultColor;
};
var ranking = view.ranking;
var rankingLength = ranking.length;
var i;
writeFont("Rank", titleScale);
for (i = 0; i < rankingLength; i += 1)
{
writeFont(ranking[i].rank.toString(), normalScale, getColor(i));
}
newColumn();
writeFont("Avatar", titleScale);
// we use the NPOT 2D shader as the avatar images might not be a power of 2
if (draw2D.begin('npot2D'))
{
for (i = 0; i < rankingLength; i += 1)
{
drawAvatar(ranking[i].user.avatar);
}
draw2D.end();
}
newColumn();
writeFont("User", titleScale);
for (i = 0; i < rankingLength; i += 1)
{
writeFont(ranking[i].user.username, normalScale, getColor(i));
}
newColumn();
writeFont("Score", titleScale);
for (i = 0; i < rankingLength; i += 1)
{
writeFont(ranking[i].score.toString(), normalScale, getColor(i));
}
newColumn();
writeFont("XP", titleScale);
for (i = 0; i < rankingLength; i += 1)
{
if (gameProfiles[ranking[i].user.username])
{
writeFont(gameProfiles[ranking[i].user.username].xp.toString(), normalScale, getColor(i));
}
else
{
// skip over users which have unloaded game profiles
yOffset += 2;
}
}
if (draw2D.begin('additive'))
{
if (!view.top)
{
draw2D.draw({
texture : upTexture,
destinationRectangle : [0, 2, 1, 3]
});
}
if (!view.bottom)
{
draw2D.draw({
texture : downTexture,
destinationRectangle : [0, 28, 1, 29]
});
}
draw2D.end();
}
xOffset = 0;
if (status.length > 0)
{
writeFont('Status: ' + status[0], statusScale);
}
else
{
writeFont('Status:', statusScale);
}
writeFont('Rockets launched: ' + rocketsLaunched.toString(), statusScale);
}
graphicsDevice.endFrame();
}
var intervalID = 0;
var leaderboardSize = 14;
var leaderboardKeys = ['rockets', 'completedTime'];
var currentLeaderboardIndex = 0;
var showingNear = false;
function disableMoving(disable)
{
var view = currentLeaderboardResult.getView();
try
{
document.getElementById('button-topscores').disabled = disable || view.top;
document.getElementById('button-myscore').disabled = disable || showingNear;
}
catch (e) {}
}
function retrieveGameProfiles()
{
// request profiles for the entire sliding window (all of the results from the current response)
// as this is more efficient (only 1 game profile request per leaderboard request)
var slidingWindow = currentLeaderboardResult.getSlidingWindow();
var ranking = slidingWindow.ranking;
var numScores = ranking.length;
// only get the users which we don't already have
var users = [];
var i;
for (i = 0; i < numScores; i += 1)
{
var username = ranking[i].user.username;
if (!gameProfiles.hasOwnProperty(username))
{
users.push(username);
}
}
var onGameProfileList = function onGameProfileListFn(newGameProfiles)
{
var u;
for (u in newGameProfiles)
{
if (newGameProfiles.hasOwnProperty(u))
{
gameProfiles[u] = JSON.parse(newGameProfiles[u].value);
}
}
if (userProfile.username && gameProfiles[userProfile.username])
{
try
{
(<HTMLInputElement>(document.getElementById('text-xpinput'))).value = gameProfiles[userProfile.username].xp;
}
catch (e) {}
}
};
// check that some users are in the list before making a request
if (users.length > 0)
{
gameProfileManager.getList(users, onGameProfileList);
}
}
function gotLeaderboard(key, leaderboardResult)
{
currentLeaderboardResult = leaderboardResult;
// retrieve the game profiles each time the leaderboards sliding window
// is updated
retrieveGameProfiles();
leaderboardResult.onSlidingWindowUpdate = retrieveGameProfiles;
var slidingWindow = leaderboardResult.getSlidingWindow();
try
{
(<HTMLInputElement>(document.getElementById('text-scoreinput'))).value = slidingWindow.player && slidingWindow.player.score || 0;
}
catch (e) {}
disableMoving(false);
}
function leaderboardMoved()
{
disableMoving(false);
}
function loadingLoop()
{
if (assetsToLoad === 0 && leaderboardManager && leaderboardManager.ready)
{
fontTechnique = fontShader.getTechnique('font');
fontTechniqueParameters = graphicsDevice.createTechniqueParameters({
clipSpace : mathDevice.v4BuildZero(),
alphaRef : 0.01,
color : mathDevice.v4BuildOne()
});
var npot2DTechnique = npot2DShader.getTechnique('textured2D');
npot2DTechniqueParameters = graphicsDevice.createTechniqueParameters({
clipSpace : mathDevice.v4BuildZero(),
alphaRef : 0.01
});
draw2D = Draw2D.create({
graphicsDevice : graphicsDevice,
blendModes: {
"npot2D": npot2DTechnique
}
});
draw2D.configure({
viewportRectangle : [0, 0, 52, 35],
scaleMode : 'scale'
});
TurbulenzEngine.clearInterval(intervalID);
intervalID = TurbulenzEngine.setInterval(mainLoop, 1000 / 60);
leaderboardManager.get(leaderboardKeys[currentLeaderboardIndex], {'type': 'top', 'size': leaderboardSize}, gotLeaderboard);
}
}
intervalID = TurbulenzEngine.setInterval(loadingLoop, 100);
// Controls
var htmlControls = HTMLControls.create();
function changeLeaderboard(index)
{
currentLeaderboardIndex = index;
showingNear = false;
leaderboardManager.get(leaderboardKeys[index], {'type': 'top', 'size': leaderboardSize}, gotLeaderboard);
disableMoving(true);
htmlControls.setSelectedRadio("leaderboardIndex", index);
}
function addRadioControl(index)
{
htmlControls.addRadioControl({
id: "radio" + index,
groupName: "leaderboardIndex",
radioIndex: index,
value: leaderboardKeys[index],
fn: function ()
{
changeLeaderboard(index);
},
isDefault: index === currentLeaderboardIndex
});
}
addRadioControl(0);
addRadioControl(1);
function scoresSetFn()
{
clearStatus();
try
{
document.getElementById('button-setscore').disabled = false;
}
catch (e) {}
currentLeaderboardResult.refresh(gotLeaderboard);
disableMoving(true);
}
function scoresSetErrorFn()
{
scoresSetFn();
setStatus("Error setting score");
TurbulenzEngine.setTimeout(function () { clearStatus(); }, 1000);
}
htmlControls.addButtonControl({
id: "button-setscore",
value: "Set score",
fn: function ()
{
var elt = <HTMLInputElement>document.getElementById('text-scoreinput');
var score = parseInt(elt.value, 10);
if (typeof(score) !== 'number' || isNaN(score))
{
setStatus('Score must be a number');
clearStatus(1000);
return;
}
setStatus('Setting score');
leaderboardManager.set(leaderboardKeys[currentLeaderboardIndex], score, scoresSetFn, scoresSetErrorFn);
try
{
document.getElementById('button-setscore').disabled = true;
}
catch (e) {}
}
});
function setXP(newXp: number, updateFn)
{
xp = newXp;
var gameProfile = {'xp': xp};
gameProfileManager.set(JSON.stringify(gameProfile), updateFn);
if (userProfile.username)
{
gameProfiles[userProfile.username] = gameProfile;
}
try
{
(<HTMLInputElement>(document.getElementById('text-xpinput'))).value = xp.toString();
}
catch (e) {}
}
htmlControls.addButtonControl({
id: "button-setxp",
value: "Set XP",
fn: function ()
{
var elt = <HTMLInputElement>(document.getElementById('text-xpinput'));
setStatus('Setting XP');
setXP(parseInt(elt.value, 10), clearStatus);
}
});
htmlControls.addButtonControl({
id: "button-topscores",
value: "Go",
fn: function ()
{
leaderboardManager.get(leaderboardKeys[currentLeaderboardIndex], {'type': 'top', 'size': leaderboardSize}, gotLeaderboard);
showingNear = false;
disableMoving(true);
}
});
htmlControls.addButtonControl({
id: "button-myscore",
value: "Go",
fn: function ()
{
leaderboardManager.get(leaderboardKeys[currentLeaderboardIndex], {'type': 'near', 'size': leaderboardSize}, gotLeaderboard);
showingNear = true;
disableMoving(true);
}
});
function resetScoreFn()
{
setStatus('Resetting leaderboards');
gameProfileManager.remove();
if (userProfile.username)
{
delete gameProfiles[userProfile.username];
}
// ONLY available on Local and the Hub (will fail on the Gamesite)
leaderboardManager.reset(function leaderboardsResetFn()
{
rocketsLaunched = 0;
setXP(0, null);
clearStatus();
currentLeaderboardResult.refresh(gotLeaderboard);
disableMoving(true);
});
}
htmlControls.addButtonControl({
id: "button-reset",
value: "Reset",
fn: resetScoreFn
});
htmlControls.register();
function moveFn(functionName)
{
if (currentLeaderboardResult)
{
if (currentLeaderboardResult[functionName](leaderboardMoved))
{
showingNear = false;
disableMoving(true);
}
}
}
var keyCodes = inputDevice.keyCodes;
var keyUp = function keyUpFn(key)
{
if (key === keyCodes.UP)
{
moveFn('pageUp');
}
else if (key === keyCodes.DOWN)
{
moveFn('pageDown');
}
else if (key === keyCodes.LEFT)
{
changeLeaderboard(0);
}
else if (key === keyCodes.RIGHT)
{
changeLeaderboard(1);
}
else if (key === keyCodes.R)
{
resetScoreFn();
}
else if (key === keyCodes.SPACE)
{
var leftToSet = 2;
var setComplete = function completeFn()
{
leftToSet -= 1;
if (leftToSet === 0)
{
clearStatus();
currentLeaderboardResult.refresh(gotLeaderboard);
disableMoving(true);
try
{
document.getElementById('button-setscore').disabled = false;
(<HTMLInputElement>(document.getElementById('text-xpinput'))).value = xp.toString();
}
catch (e) {}
}
};
rocketsLaunched += 1;
setStatus('Setting score');
leaderboardManager.set('rockets', rocketsLaunched, setComplete);
try
{
document.getElementById('button-setscore').disabled = true;
}
catch (e) {}
setXP(xp + 10, setComplete);
}
};
var onMouseWheel = function onMouseWheelFn(delta)
{
if (delta > 0)
{
moveFn('scrollUp');
}
else
{
moveFn('scrollDown');
}
};
var scoreOnClick = 71;
var onMouseUp = function onMouseUpFn(button, x, y)
{
setStatus('Setting score');
leaderboardManager.set(leaderboardKeys[currentLeaderboardIndex],
scoreOnClick, scoresSetFn, scoresSetErrorFn);
scoreOnClick += 10;
};
inputDevice.addEventListener('mousewheel', onMouseWheel);
inputDevice.addEventListener("keyup", keyUp);
inputDevice.addEventListener('mouseup', onMouseUp);
// Create a scene destroy callback to run when the window is closed
TurbulenzEngine.onunload = function destroyScene()
{
if (intervalID)
{
TurbulenzEngine.clearInterval(intervalID);
}
if (gameSession)
{
gameSession.destroy();
gameSession = null;
}
};
}; | the_stack |
import { fetchAddr, fetchSize, isSize } from '../backend/backUtils';
import { Context, ContextSet } from '../backend/context';
import { absExpIndexByLen, simplifyNum } from '../backend/expUtils';
import { simplifyShape } from '../backend/expUtils';
import { CodeSource, ShValue, SVInt, SVObject, SVSize, SVType } from '../backend/sharpValues';
import { ExpNum, ExpShape } from '../backend/symExpressions';
import { LCImpl } from '.';
import { LCBase } from './libcall';
export namespace ShapeLCImpl {
// parse shape (args), copy it to new SVSize.
export function setShape(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length < 2) {
return ctx
.warnWithMsg(
`from 'LibCall.shape.setSize': got insufficient number of argument: ${params.length}`,
source
)
.toSet();
}
const heap = ctx.heap;
const [selfAddr, argsAddr] = params;
const self = fetchAddr(selfAddr, heap)! as SVObject;
const args = fetchAddr(argsAddr, heap);
if (args && args instanceof SVSize) {
const sizedSelf = SVSize.toSize(self, args.shape);
const newHeap = ctx.heap.setVal(self.addr, sizedSelf);
return ctx.setHeap(newHeap).toSetWith(self);
}
return ctx.parseSize(argsAddr, source).map((ctx) => {
let shape: ExpShape;
let newCtx: Context<any> = ctx;
if (typeof ctx.retVal === 'string') {
newCtx = ctx.warnWithMsg(ctx.retVal, source).genIntGte('tempRank', 0, source);
shape = ExpShape.fromSymbol(newCtx.genSymShape('tempShape', newCtx.retVal, source));
} else {
shape = ctx.retVal;
}
const sizedSelf = SVSize.toSize(self, shape);
const newHeap = newCtx.heap.setVal(self.addr, sizedSelf);
return newCtx.setHeap(newHeap).setRetVal(self);
});
}
// get (shape, axis, repeat_count). returns new shape repeated by repeat_count through axis.
export function repeat(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length !== 3) {
return ctx
.warnSizeWithMsg(
`from 'LibCall.shape.repeat': got insufficient number of argument: ${params.length}`,
source
)
.toSet();
}
const heap = ctx.heap;
const [sizeAddr, axisAddr, countAddr] = params;
const size = fetchAddr(sizeAddr, heap);
const axis = fetchAddr(axisAddr, heap);
const count = fetchAddr(countAddr, heap);
if (!isSize(size)) {
return ctx.warnSizeWithMsg(`from 'LibCall.shape.repeat: shape value is not a sized type`, source).toSet();
}
if (axis?.type !== SVType.Int) {
return ctx.warnSizeWithMsg(`from 'LibCall.shape.repeat: axis value is not an integer`, source).toSet();
} else if (count?.type !== SVType.Int) {
return ctx.warnSizeWithMsg(`from 'LibCall.shape.repeat: count value is not an integer`, source).toSet();
}
const shape = size.shape;
const rank = ExpShape.getRank(shape);
const axisVal = axis.value;
const countVal = count.value;
const absAxis = absExpIndexByLen(axisVal, rank, source, ctx.ctrSet);
return ctx.shRepeat(shape, absAxis, countVal, source).map((ctx) => {
const [newSize, heap] = size.clone(ctx.heap, source);
return ctx.setHeap(heap).setRetVal(SVSize.toSize(newSize, ctx.retVal));
});
}
// index from shape
export function index(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length !== 2) {
return ctx
.warnWithMsg(
`from 'LibCall.shape.index': got insufficient number of argument: ${params.length}`,
source
)
.toSet();
}
const heap = ctx.heap;
const [sizeAddr, axisAddr] = params;
const size = fetchAddr(sizeAddr, heap);
const axis = fetchAddr(axisAddr, heap);
if (!isSize(size)) {
return ctx.warnSizeWithMsg(`from 'LibCall.shape.repeat: shape value is not a sized type`, source).toSet();
}
if (axis?.type !== SVType.Int) {
return ctx.warnSizeWithMsg(`from 'LibCall.shape.repeat: axis value is not an integer`, source).toSet();
}
const shape = size.shape;
const rank = ExpShape.getRank(shape);
const axisVal = axis.value;
const absAxis = absExpIndexByLen(axisVal, rank, source, ctx.ctrSet);
const retVal = simplifyNum(ctx.ctrSet, ExpNum.index(shape, absAxis, source));
return ctx.toSetWith(SVInt.create(retVal, source));
}
// slice from shape
export function slice(ctx: Context<LCBase.ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length !== 3) {
return ctx
.warnSizeWithMsg(
`from 'LibCall.shape.slice': got insufficient number of argument: ${params.length}`,
source
)
.toSet();
}
const heap = ctx.heap;
const [sizeAddr, startAddr, endAddr] = params;
const size = fetchAddr(sizeAddr, heap);
const start = fetchAddr(startAddr, heap);
const end = fetchAddr(endAddr, heap);
if (!isSize(size)) {
return ctx.warnSizeWithMsg(`from 'LibCall.shape.slice: shape value is not a sized type`, source).toSet();
}
if (!(start?.type === SVType.Int || start?.type === SVType.None)) {
return ctx.warnSizeWithMsg(`from 'LibCall.shape.slice: start value is not an integer`, source).toSet();
}
if (!(end?.type === SVType.Int || end?.type === SVType.None)) {
return ctx.warnSizeWithMsg(`from 'LibCall.shape.slice: end value is not an integer`, source).toSet();
}
const shape = size.shape;
const rank = ExpShape.getRank(shape);
const startNum = start.type === SVType.Int ? start.value : 0;
const endNum = end.type === SVType.Int ? end.value : rank;
const startAbs = absExpIndexByLen(startNum, rank, source, ctx.ctrSet);
const endAbs = absExpIndexByLen(endNum, rank, source, ctx.ctrSet);
let finalShape: ExpShape = ExpShape.slice(shape, startAbs, endAbs, source);
finalShape = simplifyShape(ctx.ctrSet, finalShape);
const [newSize, newHeap] = size.clone(heap, source);
return ctx.setHeap(newHeap).toSetWith(SVSize.toSize(newSize, finalShape));
}
// extract shape from list of list of ... list of integer/tensor/ndarray
//
// TODO: we look only the first items of list to infer a shape.
// consistency of each item's shape is not checked for now.
export function extractShape(
ctx: Context<LCBase.ExplicitParams>,
source: CodeSource | undefined
): ContextSet<ShValue> {
const params = ctx.retVal.params;
if (params.length !== 1) {
return _randSize(
ctx,
`from 'LibCall.shape.extractShape': got insufficient number of argument: ${params.length}`,
source
);
}
const valueAddr = params[0];
const value = fetchAddr(valueAddr, ctx.heap);
if (value?.type === SVType.Object) {
if (value instanceof SVSize) {
return ctx.toSetWith(value);
}
const shape = fetchAddr(value.getAttr('shape'), ctx.heap);
if (shape?.type === SVType.Object && shape instanceof SVSize) {
return ctx.toSetWith(shape);
}
}
return buildShape(ctx, valueAddr, source).map((ctx) => SVSize.createSize(ctx, ctx.retVal, source));
}
export function buildShape(
ctx: Context<unknown>,
maySized: ShValue,
source: CodeSource | undefined
): ContextSet<ExpShape> {
const value = fetchAddr(maySized, ctx.heap);
if (!value) {
return _randShape(ctx, `from 'LibCall.shape.extractShape': got undefined value`, source);
}
switch (value.type) {
case SVType.Bool:
case SVType.Int:
case SVType.Float:
return ctx.toSetWith(ExpShape.fromConst(0, [], source));
case SVType.Object: {
// already has size
const size = fetchSize(value, ctx.heap);
if (typeof size === 'object') {
return ctx.toSetWith(size.shape);
}
// has length
const length = value.getAttr('$length');
if (length?.type === SVType.Int) {
return ctx.getIndiceDeep(value, 0, source).flatMap((ctx) => {
const inner = ctx.retVal;
return buildShape(ctx, inner, source).map((ctx) => {
const shape = simplifyShape(
ctx.ctrSet,
ExpShape.concat(ExpShape.fromConst(1, [length.value], source), ctx.retVal, source)
);
return ctx.setRetVal(shape);
});
});
}
// fall back to unknown
return _randShape(
ctx,
`from 'LibCall.shape.extractShape': failed to infer size. return temp shape.`,
source
);
}
default:
return _randShape(
ctx,
`from 'LibCall.shape.extractShape': extract shape from invalid type. return temp shape.`,
source
);
}
}
function _randSize(ctx: Context<unknown>, message: string, source: CodeSource | undefined): ContextSet<ShValue> {
return _randShape(ctx, message, source).map((ctx) => SVSize.createSize(ctx, ctx.retVal, source));
}
function _randShape(ctx: Context<unknown>, msg: string, source: CodeSource | undefined): ContextSet<ExpShape> {
const rank = ctx.genSymInt('WarnTempRank', source);
const sym = ctx.genSymShape('WarnTempShape', ExpNum.fromSymbol(rank), source);
const shape = ExpShape.fromSymbol(sym);
return ctx.warnWithMsg(msg, source).toSetWith(shape);
}
export function randShape(
ctx: Context<LCBase.ExplicitParams>,
source: CodeSource | undefined
): ContextSet<ShValue> {
const rank = ctx.genSymInt('WarnTempRank', source);
const sym = ctx.genSymShape('WarnTempShape', ExpNum.fromSymbol(rank), source);
const shape = ExpShape.fromSymbol(sym);
return SVSize.createSize(ctx, shape, source).toSet();
}
export const libCallImpls: { [key: string]: LCImpl } = {
setShape,
repeat,
index,
slice,
extractShape,
randShape,
};
}
export const libCallMap: Map<string, LCImpl> = new Map([...Object.entries(ShapeLCImpl.libCallImpls)]); | the_stack |
'use strict';
import { uuid_to_string as rheaUuidToString, string_to_uuid as rheaStringToUuid, types as rheaTypes, message as rheaMessage } from 'rhea';
import { Message } from 'azure-iot-common';
/* tslint:disable:variable-name */
/* tslint:enable:variable-name: [true, "check-format", allow-leading-underscore", "ban-keywords", "allow-snake-case"]*/
function encodeUuid(uuidString: string): any {
const uuidRegEx = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
let uuid;
if (typeof uuidString === 'string' && uuidString.match(uuidRegEx)) {
//
// The rhea library will only serialize the the uuid with an encoding of 0x98 if the uuid property is actually
// a 16 byte buffer.
//
uuid = rheaStringToUuid(uuidString);
} else {
uuid = uuidString;
}
return uuid;
}
/**
* @private
* @class module:azure-iot-amqp-base.AmqpMessage
* @classdesc AMQP-specific message class used to prepare a [azure-iot-common.Message]{@link module:azure-iot-common.Message}
* before it's sent over the wire using the AMQP protocol.
*/
export class AmqpMessage {
to?: string;
absolute_expiry_time?: Date;
message_id?: string;
correlation_id?: string;
reply_to?: string;
content_type?: undefined | 'application/json';
content_encoding?: undefined | 'utf-8' | 'utf-16' | 'utf-32';
body: any;
application_properties: {
[key: string]: any
};
message_annotations: {
[key: string]: any
};
/**
* @method module:azure-iot-amqp-base.AmqpMessage.fromMessage
* @description Takes a azure-iot-common.Message{@link module:azure-iot-common.Message} object and creates an AMQP message from it.
*
* @param {module:azure-iot-common.Message} message The {@linkcode Message} object from which to create an AMQP message.
*/
static fromMessage (message: Message): AmqpMessage {
if (!message) throw new ReferenceError('message is \'' + message + '\'');
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_05_001: [The fromMessage method shall create a new instance of AmqpMessage.]*/
let amqpMessage = new AmqpMessage();
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_05_003: [If the message argument has a to property, the AmqpMessage object shall have a property named to with the same value.]*/
if (message.to) {
amqpMessage.to = message.to;
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_05_004: [If the message argument has an expiryTimeUtc property, the AmqpMessage object shall have a property named absolute_expiry_time with the same value.]*/
if (message.expiryTimeUtc) {
amqpMessage.absolute_expiry_time = message.expiryTimeUtc;
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_05_007: [If the message argument has a messageId property, the AmqpMessage object shall have a property named messageId with the same value.]*/
if (message.messageId) {
amqpMessage.message_id = encodeUuid(message.messageId);
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_010: [If the `message` argument has a `correlationId` property, the `AmqpMessage` object shall have a property named `correlation_id` with the same value.]*/
if (message.correlationId) {
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_012: [If the `Message.correlationId` property is a UUID, the AMQP type of the `AmqpMessage.correlation_id` property shall be forced to Buffer[16].]*/
amqpMessage.correlation_id = encodeUuid(message.correlationId);
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_014: [If the `message` argument has a `contentEncoding` property, the `AmqpMessage` object shall have a property named `content_encoding` with the same value.]*/
if (message.contentEncoding) {
amqpMessage.content_encoding = message.contentEncoding;
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_015: [If the `message` argument has a `contentType` property, the `AmqpMessage` object shall have a property named `content_type` with the same value.]*/
if (message.contentType) {
amqpMessage.content_type = message.contentType;
}
if (message.interfaceId) {
if (!amqpMessage.message_annotations) {
amqpMessage.message_annotations = {
'iothub-interface-id': message.interfaceId
};
} else {
amqpMessage.message_annotations['iothub-interface-id'] = message.interfaceId;
}
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_05_008: [If needed, the created AmqpMessage object shall have a property of type Object named application_properties.]*/
function ensureApplicationPropertiesCreated(): void {
if (!amqpMessage.application_properties) {
amqpMessage.application_properties = {};
}
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_05_009: [If the message argument has an ack property, the application_properties property of the AmqpMessage object shall have a property named iothub-ack with the same value.]*/
if (message.ack) {
ensureApplicationPropertiesCreated();
amqpMessage.application_properties['iothub-ack'] = message.ack;
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_13_001: [ If message.properties is truthy, then all the properties in it shall be copied to the application_properties property of the AmqpMessage object. ]*/
if (message.properties) {
const props = message.properties;
const propsCount = props.count();
if (propsCount > 0) {
if (!amqpMessage.application_properties) {
ensureApplicationPropertiesCreated();
}
for (let index = 0; index < propsCount; index++) {
const item = props.getItem(index);
if (!!item) {
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_013: [If one of the property key is `IoThub-status`, this property is reserved and shall be forced to an `int` `rhea` type.]*/
const val = (item.key === 'IoThub-status') ? rheaTypes.wrap_int(parseInt(item.value)) : item.value;
amqpMessage.application_properties[item.key] = val;
}
}
}
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_05_005: [If message.getData() is truthy, the AmqpMessage object shall have a property named body with the value returned from message.getData().]*/
const body = message.getData();
if (body !== undefined) {
amqpMessage.body = rheaMessage.data_section(message.getBytes());
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_05_006: [The generated AmqpMessage object shall be returned to the caller.]*/
return amqpMessage;
}
/**
* @method module:azure-iot-amqp-base.AmqpMessage.toMessage
* @description Creates a transport-agnostic azure-iot-common.Message{@link module:azure-iot-common.Message} object from transport-specific AMQP message.
*
* @param {AmqpMessage} message The {@linkcode AmqpMessage} object from which to create an Message.
*/
static toMessage(amqpMessage: AmqpMessage): Message {
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_001: [The `toMessage` method shall throw if the `amqpMessage` argument is falsy.]*/
if (!amqpMessage) {
throw new ReferenceError('amqpMessage cannot be \'' + amqpMessage + '\'');
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_009: [The `toMessage` method shall set the `Message.data` of the message to the content of the `AmqpMessage.body.content` property.]*/
let msg: Message = ( amqpMessage.body ) ? ( new Message(amqpMessage.body.content) ) : ( new Message(undefined) );
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_005: [The `toMessage` method shall set the `Message.to` property to the `AmqpMessage.to` value if it is present.]*/
if (amqpMessage.to) {
msg.to = amqpMessage.to;
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_006: [The `toMessage` method shall set the `Message.expiryTimeUtc` property to the `AmqpMessage.absolute_expiry_time` value if it is present.]*/
if (amqpMessage.absolute_expiry_time) {
msg.expiryTimeUtc = amqpMessage.absolute_expiry_time;
}
//
// The rhea library will de-serialize an encoded uuid (0x98) as a 16 byte buffer.
// Since common messages should only have type string it is safe to decode
// these as strings.
//
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_004: [The `toMessage` method shall set the `Message.messageId` property to the `AmqpMessage.message_id` value if it is present.]*/
if (amqpMessage.message_id) {
if (((amqpMessage.message_id as any) instanceof Buffer) && (amqpMessage.message_id.length === 16)) {
msg.messageId = rheaUuidToString(amqpMessage.message_id as any);
} else {
msg.messageId = amqpMessage.message_id;
}
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_003: [The `toMessage` method shall set the `Message.correlationId` property to the `AmqpMessage.correlation_id` value if it is present.]*/
if (amqpMessage.correlation_id) {
if (((amqpMessage.correlation_id as any) instanceof Buffer) && (amqpMessage.correlation_id.length === 16)) {
msg.correlationId = rheaUuidToString(amqpMessage.correlation_id as any);
} else {
msg.correlationId = amqpMessage.correlation_id;
}
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_016: [The `toMessage` method shall set the `Message.contentType` property to the `AmqpMessage.content_type` value if it is present. ]*/
if (amqpMessage.content_type) {
msg.contentType = amqpMessage.content_type;
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_017: [The `toMessage` method shall set the `Message.contentEncoding` property to the `AmqpMessage.content_encoding` value if it is present. ]*/
if (amqpMessage.content_encoding) {
msg.contentEncoding = amqpMessage.content_encoding;
}
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_007: [The `toMessage` method shall convert the user-defined `AmqpMessage.applicationProperties` to a `Properties` collection stored in `Message.properties`.]*/
if (amqpMessage.application_properties) {
const appProps = amqpMessage.application_properties;
for (let key in appProps) {
if (appProps.hasOwnProperty(key)) {
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_008: [The `toMessage` method shall set the `Message.ack` property to the `AmqpMessage.application_properties['iothub-ack']` value if it is present.]*/
if (key === 'iothub-ack') {
msg.ack = appProps[key];
} else {
msg.properties.add(key, appProps[key]);
}
}
}
}
msg.transportObj = amqpMessage;
/*Codes_SRS_NODE_IOTHUB_AMQPMSG_16_002: [The `toMessage` method shall return a `Message` object.]*/
return msg;
}
} | 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 resource to manage a VPC's default network ACL. This resource can manage the default network ACL of the default or a non-default VPC.
*
* > **NOTE:** This is an advanced resource with special caveats. Please read this document in its entirety before using this resource. The `aws.ec2.DefaultNetworkAcl` behaves differently from normal resources. This provider does not _create_ this resource but instead attempts to "adopt" it into management.
*
* Every VPC has a default network ACL that can be managed but not destroyed. When the provider first adopts the Default Network ACL, it **immediately removes all rules in the ACL**. It then proceeds to create any rules specified in the configuration. This step is required so that only the rules specified in the configuration are created.
*
* This resource treats its inline rules as absolute; only the rules defined inline are created, and any additions/removals external to this resource will result in diffs being shown. For these reasons, this resource is incompatible with the `aws.ec2.NetworkAclRule` resource.
*
* For more information about Network ACLs, see the AWS Documentation on [Network ACLs][aws-network-acls].
*
* ## Example Usage
* ### Basic Example
*
* The following config gives the Default Network ACL the same rules that AWS includes but pulls the resource under management by this provider. This means that any ACL rules added or changed will be detected as drift.
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const mainvpc = new aws.ec2.Vpc("mainvpc", {cidrBlock: "10.1.0.0/16"});
* const _default = new aws.ec2.DefaultNetworkAcl("default", {
* defaultNetworkAclId: mainvpc.defaultNetworkAclId,
* ingress: [{
* protocol: -1,
* ruleNo: 100,
* action: "allow",
* cidrBlock: mainvpc.cidrBlock,
* fromPort: 0,
* toPort: 0,
* }],
* egress: [{
* protocol: -1,
* ruleNo: 100,
* action: "allow",
* cidrBlock: "0.0.0.0/0",
* fromPort: 0,
* toPort: 0,
* }],
* });
* ```
* ### Example: Deny All Egress Traffic, Allow Ingress
*
* The following denies all Egress traffic by omitting any `egress` rules, while including the default `ingress` rule to allow all traffic.
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const mainvpc = new aws.ec2.Vpc("mainvpc", {cidrBlock: "10.1.0.0/16"});
* const _default = new aws.ec2.DefaultNetworkAcl("default", {
* defaultNetworkAclId: mainvpc.defaultNetworkAclId,
* ingress: [{
* protocol: -1,
* ruleNo: 100,
* action: "allow",
* cidrBlock: aws_default_vpc.mainvpc.cidr_block,
* fromPort: 0,
* toPort: 0,
* }],
* });
* ```
* ### Example: Deny All Traffic To Any Subnet In The Default Network ACL
*
* This config denies all traffic in the Default ACL. This can be useful if you want to lock down the VPC to force all resources to assign a non-default ACL.
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const mainvpc = new aws.ec2.Vpc("mainvpc", {cidrBlock: "10.1.0.0/16"});
* const _default = new aws.ec2.DefaultNetworkAcl("default", {defaultNetworkAclId: mainvpc.defaultNetworkAclId});
* // no rules defined, deny all traffic in this ACL
* ```
* ### Managing Subnets In A Default Network ACL
*
* Within a VPC, all Subnets must be associated with a Network ACL. In order to "delete" the association between a Subnet and a non-default Network ACL, the association is destroyed by replacing it with an association between the Subnet and the Default ACL instead.
*
* When managing the Default Network ACL, you cannot "remove" Subnets. Instead, they must be reassigned to another Network ACL, or the Subnet itself must be destroyed. Because of these requirements, removing the `subnetIds` attribute from the configuration of a `aws.ec2.DefaultNetworkAcl` resource may result in a reoccurring plan, until the Subnets are reassigned to another Network ACL or are destroyed.
*
* Because Subnets are by default associated with the Default Network ACL, any non-explicit association will show up as a plan to remove the Subnet. For example: if you have a custom `aws.ec2.NetworkAcl` with two subnets attached, and you remove the `aws.ec2.NetworkAcl` resource, after successfully destroying this resource future plans will show a diff on the managed `aws.ec2.DefaultNetworkAcl`, as those two Subnets have been orphaned by the now destroyed network acl and thus adopted by the Default Network ACL. In order to avoid a reoccurring plan, they will need to be reassigned, destroyed, or added to the `subnetIds` attribute of the `aws.ec2.DefaultNetworkAcl` entry.
*
* As an alternative to the above, you can also specify the following lifecycle configuration in your `aws.ec2.DefaultNetworkAcl` resource:
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* // ... other configuration ...
* const _default = new aws.ec2.DefaultNetworkAcl("default", {});
* ```
* ### Removing `aws.ec2.DefaultNetworkAcl` From Your Configuration
*
* Each AWS VPC comes with a Default Network ACL that cannot be deleted. The `aws.ec2.DefaultNetworkAcl` allows you to manage this Network ACL, but the provider cannot destroy it. Removing this resource from your configuration will remove it from your statefile and management, **but will not destroy the Network ACL.** All Subnets associations and ingress or egress rules will be left as they are at the time of removal. You can resume managing them via the AWS Console.
*
* ## Import
*
* Default Network ACLs can be imported using the `id`, e.g.
*
* ```sh
* $ pulumi import aws:ec2/defaultNetworkAcl:DefaultNetworkAcl sample acl-7aaabd18
* ```
*/
export class DefaultNetworkAcl extends pulumi.CustomResource {
/**
* Get an existing DefaultNetworkAcl 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?: DefaultNetworkAclState, opts?: pulumi.CustomResourceOptions): DefaultNetworkAcl {
return new DefaultNetworkAcl(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:ec2/defaultNetworkAcl:DefaultNetworkAcl';
/**
* Returns true if the given object is an instance of DefaultNetworkAcl. 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 DefaultNetworkAcl {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === DefaultNetworkAcl.__pulumiType;
}
/**
* ARN of the Default Network ACL
*/
public /*out*/ readonly arn!: pulumi.Output<string>;
/**
* Network ACL ID to manage. This attribute is exported from `aws.ec2.Vpc`, or manually found via the AWS Console.
*/
public readonly defaultNetworkAclId!: pulumi.Output<string>;
/**
* Configuration block for an egress rule. Detailed below.
*/
public readonly egress!: pulumi.Output<outputs.ec2.DefaultNetworkAclEgress[] | undefined>;
/**
* Configuration block for an ingress rule. Detailed below.
*/
public readonly ingress!: pulumi.Output<outputs.ec2.DefaultNetworkAclIngress[] | undefined>;
/**
* ID of the AWS account that owns the Default Network ACL
*/
public /*out*/ readonly ownerId!: pulumi.Output<string>;
/**
* List of Subnet IDs to apply the ACL to. See the notes below on managing Subnets in the Default Network ACL
*/
public readonly subnetIds!: pulumi.Output<string[] | undefined>;
/**
* Map of tags to assign to the resource. .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}>;
/**
* ID of the associated VPC
*/
public /*out*/ readonly vpcId!: pulumi.Output<string>;
/**
* Create a DefaultNetworkAcl 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: DefaultNetworkAclArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: DefaultNetworkAclArgs | DefaultNetworkAclState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as DefaultNetworkAclState | undefined;
inputs["arn"] = state ? state.arn : undefined;
inputs["defaultNetworkAclId"] = state ? state.defaultNetworkAclId : undefined;
inputs["egress"] = state ? state.egress : undefined;
inputs["ingress"] = state ? state.ingress : undefined;
inputs["ownerId"] = state ? state.ownerId : undefined;
inputs["subnetIds"] = state ? state.subnetIds : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["tagsAll"] = state ? state.tagsAll : undefined;
inputs["vpcId"] = state ? state.vpcId : undefined;
} else {
const args = argsOrState as DefaultNetworkAclArgs | undefined;
if ((!args || args.defaultNetworkAclId === undefined) && !opts.urn) {
throw new Error("Missing required property 'defaultNetworkAclId'");
}
inputs["defaultNetworkAclId"] = args ? args.defaultNetworkAclId : undefined;
inputs["egress"] = args ? args.egress : undefined;
inputs["ingress"] = args ? args.ingress : undefined;
inputs["subnetIds"] = args ? args.subnetIds : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["arn"] = undefined /*out*/;
inputs["ownerId"] = undefined /*out*/;
inputs["tagsAll"] = undefined /*out*/;
inputs["vpcId"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(DefaultNetworkAcl.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering DefaultNetworkAcl resources.
*/
export interface DefaultNetworkAclState {
/**
* ARN of the Default Network ACL
*/
arn?: pulumi.Input<string>;
/**
* Network ACL ID to manage. This attribute is exported from `aws.ec2.Vpc`, or manually found via the AWS Console.
*/
defaultNetworkAclId?: pulumi.Input<string>;
/**
* Configuration block for an egress rule. Detailed below.
*/
egress?: pulumi.Input<pulumi.Input<inputs.ec2.DefaultNetworkAclEgress>[]>;
/**
* Configuration block for an ingress rule. Detailed below.
*/
ingress?: pulumi.Input<pulumi.Input<inputs.ec2.DefaultNetworkAclIngress>[]>;
/**
* ID of the AWS account that owns the Default Network ACL
*/
ownerId?: pulumi.Input<string>;
/**
* List of Subnet IDs to apply the ACL to. See the notes below on managing Subnets in the Default Network ACL
*/
subnetIds?: pulumi.Input<pulumi.Input<string>[]>;
/**
* Map of tags to assign to the resource. .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>}>;
/**
* ID of the associated VPC
*/
vpcId?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a DefaultNetworkAcl resource.
*/
export interface DefaultNetworkAclArgs {
/**
* Network ACL ID to manage. This attribute is exported from `aws.ec2.Vpc`, or manually found via the AWS Console.
*/
defaultNetworkAclId: pulumi.Input<string>;
/**
* Configuration block for an egress rule. Detailed below.
*/
egress?: pulumi.Input<pulumi.Input<inputs.ec2.DefaultNetworkAclEgress>[]>;
/**
* Configuration block for an ingress rule. Detailed below.
*/
ingress?: pulumi.Input<pulumi.Input<inputs.ec2.DefaultNetworkAclIngress>[]>;
/**
* List of Subnet IDs to apply the ACL to. See the notes below on managing Subnets in the Default Network ACL
*/
subnetIds?: pulumi.Input<pulumi.Input<string>[]>;
/**
* Map of tags to assign to the resource. .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>}>;
} | the_stack |
import * as assert from "assert";
import { testContext, disposeTestDocumentStore } from "../../Utils/TestUtil";
import {
AttachmentName,
IDocumentStore,
DeleteAttachmentOperation,
DeleteCommandData
} from "../../../src";
import * as stream from "readable-stream";
import { User } from "../../Assets/Entities";
import { CONSTANTS } from "../../../src/Constants";
import * as StreamUtil from "../../../src/Utility/StreamUtil";
describe("Attachments Session", function () {
let store: IDocumentStore;
beforeEach(async function () {
store = await testContext.getDocumentStore();
});
afterEach(async () =>
await disposeTestDocumentStore(store));
it("can put attachments", async () => {
const attachmentsInfo = [
{ name: "profile.png", contentType: "image/png" },
{ name: "background-photo.jpg", contentType: "ImGge/jPeg" },
{ name: "fileNAME_#$1^%_בעברית.txt", contentType: undefined }
];
const profileStream = Buffer.from([1, 2, 3]);
const backgroundStream = Buffer.from([10, 20, 30, 40, 50]);
const fileStream = new stream.Readable();
[1, 2, 3, 4, 5].forEach(x => fileStream.push(Buffer.from(x.toString())));
fileStream.push(null);
{
const session = store.openSession();
const user = new User();
user.name = "Fitzchak";
await session.store(user, "users/1");
session.advanced.attachments.store(
"users/1", attachmentsInfo[0].name, profileStream, attachmentsInfo[0].contentType);
session.advanced.attachments.store(
user, attachmentsInfo[1].name, backgroundStream, attachmentsInfo[1].contentType);
session.advanced.attachments.store(
user, attachmentsInfo[2].name, fileStream);
await session.saveChanges();
}
{
const session = store.openSession();
const user = await session.load<User>("users/1");
const metadata = session.advanced.getMetadataFor(user);
assert.strictEqual(metadata[CONSTANTS.Documents.Metadata.FLAGS], "HasAttachments");
const attachments = metadata[CONSTANTS.Documents.Metadata.ATTACHMENTS] as AttachmentName[];
assert.strictEqual(attachments.length, 3);
const orderedNames = [...attachments];
orderedNames.sort((a, b) => a.name > b.name ? 1 : -1);
for (let i = 0; i < attachmentsInfo.length; i++) {
const { name, contentType } = orderedNames[i];
const attachment = attachments[i];
assert.strictEqual(name, attachment.name);
assert.strictEqual(contentType, attachment.contentType);
assert.strictEqual(typeof attachment.size, "number");
assert.ok(attachment.hash);
}
}
});
it("throws if stream is used twice", async () => {
const session = store.openSession();
const stream = Buffer.from([1, 2, 3]);
const user = new User();
user.name = "Fitzchak";
await session.store(user, "users/1");
session.advanced.attachments.store(user, "profile", stream, "image/png");
session.advanced.attachments.store(user, "other", stream);
try {
await session.saveChanges();
assert.fail("it should have thrown");
} catch (err) {
assert.strictEqual(err.name, "InvalidOperationException");
}
});
it("throws when two attachments with the same name in session", async () => {
const session = store.openSession();
const stream = Buffer.from([1, 2, 3]);
const stream2 = Buffer.from([1, 2, 3, 4, 5]);
const user = new User();
user.name = "Fitzchak";
await session.store(user, "users/1");
session.advanced.attachments.store(user, "profile", stream, "image/png");
try {
session.advanced.attachments.store(user, "profile", stream2);
assert.fail("it should have thrown");
} catch (err) {
assert.strictEqual(err.name, "InvalidOperationException");
}
});
it("should throw when deleting attachment after put document and attachment", async () => {
const session = store.openSession();
const stream = Buffer.from([1, 2, 3]);
const user = new User();
user.name = "Fitzchak";
await session.store(user, "users/1");
session.advanced.attachments.store(user, "profile", stream, "image/png");
await session.delete(user);
try {
await session.saveChanges();
assert.fail("it should have thrown");
} catch (err) {
assert.strictEqual(err.name, "InvalidOperationException");
}
});
it("can get & delete attachments", async () => {
const stream1 = Buffer.from([1, 2, 3]);
const stream2 = Buffer.from([1, 2, 3, 4, 5, 6]);
const stream3 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const stream4 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
{
const session = store.openSession();
const user = new User();
user.name = "Fitzchak";
await session.store(user, "users/1");
session.advanced.attachments.store(user, "file1", stream1, "image/png");
session.advanced.attachments.store(user, "file2", stream2, "image/png");
session.advanced.attachments.store(user, "file3", stream3, "image/png");
session.advanced.attachments.store(user, "file4", stream4, "image/png");
await session.saveChanges();
}
{
const session = store.openSession();
const user = await session.load<User>("users/1");
// test get attachment by its name
{
const attachmentResult = await session.advanced.attachments.get("users/1", "file2");
assert.strictEqual(attachmentResult.details.name, "file2");
attachmentResult.dispose();
}
session.advanced.attachments.delete("users/1", "file2");
session.advanced.attachments.delete(user, "file4");
await session.saveChanges();
}
{
const session = store.openSession();
const user = await session.load<User>("users/1");
const metadata = session.advanced.getMetadataFor(user);
assert.strictEqual(metadata[CONSTANTS.Documents.Metadata.FLAGS], "HasAttachments");
const attachments = metadata[CONSTANTS.Documents.Metadata.ATTACHMENTS] as AttachmentName[];
assert.strictEqual(attachments.length, 2);
const result = await session.advanced.attachments.get("users/1", "file1");
assert.strictEqual(result.details.name, "file1");
assert.ok(result.details.hash);
assert.ok(result.details.changeVector);
assert.ok(result.details.size);
assert.ok(result.data);
assert.strictEqual(result.data.listenerCount("data"), 0);
assert.ok(result.data.readableLength);
assert.ok(result.data.isPaused());
// AttachmentResult data stream is paused until you resume() or pipe() it
// result.data.resume();
let bufResult = Buffer.from([]);
result.data.pipe(new stream.Writable({
write(chunk, enc, cb) {
bufResult = Buffer.concat([bufResult, chunk]);
cb();
}
}));
await StreamUtil.finishedAsync(result.data);
result.dispose();
assert.ok(Buffer.compare(bufResult, stream1) === 0);
}
});
it("can delete attachment using command", async () => {
{
const session = store.openSession();
const user = new User();
user.name = "Fitzchak";
await session.store(user, "users/1");
const stream1 = Buffer.from([1, 2, 3]);
const stream2 = Buffer.from([1, 2, 3, 4, 5, 6]);
session.advanced.attachments.store(user, "file1", stream1, "image/png");
session.advanced.attachments.store(user, "file2", stream2, "image/png");
await session.saveChanges();
}
await store.operations.send(new DeleteAttachmentOperation("users/1", "file2"));
{
const session = store.openSession();
const user = await session.load<User>("users/1");
const metadata = session.advanced.getMetadataFor(user);
assert.ok(metadata["@flags"].includes("HasAttachments"));
const attachments = metadata["@attachments"];
assert.strictEqual(attachments.length, 1);
const result = await session.advanced.attachments.get("users/1", "file1");
try {
assert.strictEqual(result.data.readableLength, 3);
} finally {
result.dispose();
}
}
});
it("delete document and then its attachments. This is no op but should be supported.", async () => {
{
const session = store.openSession();
const user = new User();
user.name = "Fitzchak";
await session.store(user, "users/1");
const stream = Buffer.from([1, 2, 3]);
session.advanced.attachments.store(user, "file", stream, "image/png");
await session.saveChanges();
}
{
const session = store.openSession();
const user = await session.load<User>("users/1");
await session.delete(user);
session.advanced.attachments.delete(user, "file");
session.advanced.attachments.delete(user, "file"); // this should be no-op
await session.saveChanges();
}
});
it("delete document by command and then its attachments. This is no op but should be supported.", async () => {
{
const session = store.openSession();
const user = new User();
user.name = "Fitzchak";
await session.store(user, "users/1");
const stream = Buffer.from([1, 2, 3]);
session.advanced.attachments.store(user, "file", stream, "image/png");
await session.saveChanges();
}
{
const session = store.openSession();
session.advanced.defer(new DeleteCommandData("users/1", null));
session.advanced.attachments.delete("users/1", "file");
session.advanced.attachments.delete("users/1", "file");
await session.saveChanges();
}
});
it("get attachment names", async () => {
const names = ["profile.png"];
{
const session = store.openSession();
const user = new User();
user.name = "Fitzchak";
await session.store(user, "users/1");
const stream = Buffer.from([1, 2, 3]);
session.advanced.attachments.store(user, names[0], stream, "image/png");
await session.saveChanges();
}
{
const session = store.openSession();
const user = await session.load<User>("users/1");
const attachments = session.advanced.attachments.getNames(user);
assert.strictEqual(attachments.length, 1);
const attachment = attachments[0];
assert.strictEqual(attachment.contentType, "image/png");
assert.strictEqual(attachment.name, names[0]);
assert.strictEqual(attachment.size, 3);
}
});
it("attachment exists", async () => {
{
const session = store.openSession();
const user = new User();
user.name = "Fitzchak";
await session.store(user, "users/1");
const attachmentStream = Buffer.from([1, 2, 3]);
session.advanced.attachments.store(user, "profile", attachmentStream, "image/png");
await session.saveChanges();
}
{
const session = store.openSession();
assert.ok(await session.advanced.attachments.exists("users/1", "profile"));
assert.ok(!(await session.advanced.attachments.exists("users/1", "background-photo")));
assert.ok(!(await session.advanced.attachments.exists("users/2", "profile")));
}
});
}); | the_stack |
import type { Client } from '../client';
import type { FilteredStreamRuleResolvable } from './Types';
import type { ClientEvents, Collection } from '../util';
import type { Tweet, RequestData, MatchingRule } from '../structures';
import type { TweetResolvable, UserResolvable, SpaceResolvable } from './Types';
import type {
Granularity,
MediaFieldsParameter,
PlaceFieldsParameter,
PollFieldsParameter,
Snowflake,
SpaceExpansionsParameter,
SpaceFieldsParameter,
TweetExpansionsParameter,
TweetFieldsParameter,
TweetTypeExcludesRequestParameter,
UserExpansionsParameter,
UserFieldsParameter,
} from 'twitter-types';
/**
* The options for the API in use
*/
export interface ApiOptions {
/**
* Current default version of the API
*/
version: number;
/**
* The base URL of the API
*/
baseURL: string;
}
/**
* The common optional options to provide while fetching a content
*/
export interface BaseFetchOptions {
/**
* Whether to skip cache check for the requested content and fetch from the API directly
*/
skipCacheCheck?: boolean;
/**
* Whether to store the fetched content in cache for later use
*/
cacheAfterFetching?: boolean;
}
export interface ClientCredentialsInterface {
consumerKey: string;
consumerSecret: string;
accessToken: string;
accessTokenSecret: string;
username: string;
bearerToken: string;
}
export interface ClientEventsMapping {
filteredTweetCreate: [tweet: Tweet, matchingRules: Collection<Snowflake, MatchingRule>];
keepAliveSignal: [stream: 'sampled' | 'filtered'];
partialError: [partialError: Record<string, unknown>];
ready: [client: Client];
sampledTweetCreate: [tweet: Tweet];
}
/**
* The options which the client gets initialized with
*/
export interface ClientOptions {
/**
* The options provided for the API
*/
api?: ApiOptions;
/**
* The options provided for query of an API request
*/
queryParameters?: QueryParameters;
/**
* The options for selecting what events should be fired
*/
events: Array<keyof typeof ClientEvents>;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type ErrorMessageBuilder = (...args: Array<any>) => string;
export interface ExtendedRequestData<Q, B> extends RequestData<Q, B> {
route: string;
}
/**
* Options used to fetch a single user by its username
*/
export interface FetchUserByUsernameOptions extends BaseFetchOptions {
/**
* The username of the user to fetch
*/
username: string;
}
/**
* Options used to fetch multiple users by their usernames
*/
export interface FetchUsersByUsernamesOptions extends Omit<BaseFetchOptions, 'skipCacheCheck'> {
/**
* The usernames of the users to fetch
*/
usernames: Array<string>;
}
/**
* Options used to fetch a single user
*/
export interface FetchUserOptions extends BaseFetchOptions {
/**
* The user to fetch
*/
user: UserResolvable;
}
/**
* Options used to fetch multiple users
*/
export interface FetchUsersOptions extends Omit<BaseFetchOptions, 'skipCacheCheck'> {
/**
* The users to fetch
*/
users: Array<UserResolvable>;
}
/**
* Options used to feth a single tweet
*/
export interface FetchTweetOptions extends BaseFetchOptions {
/**
* The tweet to fetch
*/
tweet: TweetResolvable;
}
/**
* Options used to feth multiple tweets
*/
export interface FetchTweetsOptions extends Omit<BaseFetchOptions, 'skipCacheCheck'> {
/**
* The tweets to fetch
*/
tweets: Array<TweetResolvable>;
}
/**
* Options used to fetch a single space
*/
export interface FetchSpaceOptions extends BaseFetchOptions {
/**
* The space to fetch
*/
space: SpaceResolvable;
}
/**
* Options used to fetch multiple spaces
*/
export interface FetchSpacesOptions extends Omit<BaseFetchOptions, 'skipCacheCheck'> {
/**
* The spaces to fetch
*/
spaces: Array<SpaceResolvable>;
}
/**
* Options used to fetch spaces using creator ids
*/
export interface FetchSpacesByCreatorIdsOptions extends Omit<BaseFetchOptions, 'skipCacheCheck'> {
/**
* The creators whose spaces are to be fetched
*/
users: Array<UserResolvable>;
}
/**
* The options used to search spaces
*/
export interface SearchSpacesOptions extends Omit<BaseFetchOptions, 'skipCacheCheck'> {
/**
* The query to match with
*/
query: string;
/**
* The state of the spaces to match
*/
state: 'live' | 'scheduled';
/**
* The number of maximum spaces to fetch
*/
maxResults?: number;
}
export interface QueryParameters {
userFields?: Array<UserFieldsParameter>;
tweetFields?: Array<TweetFieldsParameter>;
spaceFields?: Array<SpaceFieldsParameter>;
mediaFields?: Array<MediaFieldsParameter>;
placeFields?: Array<PlaceFieldsParameter>;
pollFields?: Array<PollFieldsParameter>;
tweetExpansions?: Array<TweetExpansionsParameter>;
userExpansions?: Array<UserExpansionsParameter>;
spaceExpansions?: Array<SpaceExpansionsParameter>;
}
export interface StructureConstructable<T> {
// eslint-disable-next-line
new(...args: any[]): T;
}
export interface TwitterjsErrorConstructor {
// eslint-disable-next-line
new(key: string, ...args: Array<unknown>): Error;
}
/**
* The options used to add a new filtered tweet stream rule
*/
export interface FilteredStreamRuleData {
/**
* The value of the rule
*/
value: string;
/**
* The label of the rule
*/
tag?: string;
}
export interface RequestDataOptions<Q, B> {
/**
* The query for the request
*/
query?: Q;
/**
* The body for the request
*/
body?: B;
/**
* Whether the request results in a persisent http connection
*/
isStreaming?: boolean;
/**
* Whether the request should be authorized with user context authorization
*/
isUserContext?: boolean;
}
/**
* The options used to fetch users blocked by the authorized user
*/
export interface FetchBlocksOptions {
/**
* The maximum number of users to fetch per page
*/
maxResultsPerPage?: number;
}
/**
* The options used to fetch users muted by the authorized user
*/
export interface FetchMutesOptions {
/**
* The maximum number of users to fetch per page
*/
maxResultsPerPage?: number;
}
export interface BookOptions {
/**
* The ID of the user to create the book for
*/
userId: Snowflake;
/**
* The maximum number of results to fetch per page
*/
maxResultsPerPage?: number;
}
/**
* The options used to fetch tweets composed by a twitter user
*/
export interface FetchComposedTweetsOptions {
/**
* Fetch tweets that were created after this point in time
*/
afterTime?: Date | number;
/**
* Fetch tweets that were created before this point in time
*/
beforeTime?: Date | number;
/**
* Fetch tweets that were created after this tweet
*/
afterTweet?: TweetResolvable;
/**
* Fetch tweets that were created before this tweet
*/
beforeTweet?: TweetResolvable;
/**
* The types of tweet to exclude from fetching
*/
exclude?: Array<TweetTypeExcludesRequestParameter>;
/**
* The maximum number of tweets to fetch per page
*/
maxResultsPerPage?: number;
}
/**
* The options used to create a {@link ComposedTweetsBook} object for a user
*/
export interface ComposedTweetsBookOptions extends BookOptions {
/**
* Return tweets that were created after this timestamp
*/
afterTimestamp?: number;
/**
* Return tweets that were created before this timestamp
*/
beforeTimestamp?: number;
/**
* The types of tweets to exclude
*/
exclude?: Array<TweetTypeExcludesRequestParameter>;
/**
* Return tweets that were created after this tweet ID
*/
afterTweetId?: Snowflake;
/**
* Return tweets that were created before this tweet ID
*/
beforeTweetId?: Snowflake;
}
/**
* The options used to create a {@link MentionsBook} object
*/
export interface MentionsBookOptions extends BookOptions {
/**
* Return tweets that were created after this timestamp
*/
afterTimestamp?: number;
/**
* Return tweets that were created before this timestamp
*/
beforeTimestamp?: number;
/**
* Return tweets that were created after this tweet ID
*/
afterTweetId?: Snowflake;
/**
* Return tweets that were created before this tweet ID
*/
beforeTweetId?: Snowflake;
}
/**
* The options used to fetch tweets that mention a given user
*/
export interface FetchMentionsOptions {
/**
* Fetch tweets that were created after this point in time
*/
afterTime?: Date | number;
/**
* Fetch tweets that were created before this point in time
*/
beforeTime?: Date | number;
/**
* Fetch tweets that were created after this tweet
*/
afterTweet?: TweetResolvable;
/**
* Fetch tweets that were created before this tweet
*/
beforeTweet?: TweetResolvable;
/**
* The maximum number of tweets to fetch per page
*/
maxResultsPerPage?: number;
}
/**
* The options used to create a {@link SearchTweetsBook} object
*/
export interface SearchTweetsBookOptions {
query: string;
/**
* Return tweets that were created after this timestamp
*/
afterTimestamp?: number;
/**
* Return tweets that were created before this timestamp
*/
beforeTimestamp?: number;
/**
* Return tweets that were created after this tweet ID
*/
afterTweetId?: Snowflake;
/**
* Return tweets that were created before this tweet ID
*/
beforeTweetId?: Snowflake;
/**
* The maximum number of results to fetch per page
*/
maxResultsPerPage?: number;
}
/**
* The options used to fetch tweets using query
*/
export interface SearchTweetsOptions {
/**
* Fetch tweets that were created after this point in time
*/
afterTime?: Date | number;
/**
* Fetch tweets that were created before this point in time
*/
beforeTime?: Date | number;
/**
* Fetch tweets that were created after this tweet
*/
afterTweet?: TweetResolvable;
/**
* Fetch tweets that were created before this tweet
*/
beforeTweet?: TweetResolvable;
/**
* The maximum number of tweets to fetch per page
*/
maxResultsPerPage?: number;
}
/**
* The options used to create a {@link TweetsCountBook} object
*/
export interface TweetsCountBookOptions {
/**
* The query for matching tweets
*/
query: string;
/**
* Match tweets that were created after this timestamp
*/
afterTimestamp?: number;
/**
* Match tweets that were created before this timestamp
*/
beforeTimestamp?: number;
/**
* The granularity of the {@link TweetCountBucket}
*/
granularity?: Granularity;
/**
* Match tweets that were created after this tweet ID
*/
afterTweetId?: Snowflake;
/**
* Match tweets that weere created before this tweet ID
*/
beforeTweetId?: Snowflake;
}
/**
* The options for fetching tweets count matching a query
*/
export interface CountTweetsOptions {
/**
* Match tweets that were created after this point in time
*/
afterTime?: Date | number;
/**
* Match tweets that were created before this point in time
*/
beforeTime?: Date | number;
/**
* Match tweets that were created after this tweet
*/
afterTweet?: TweetResolvable;
/**
* Match tweets that were created before this tweet
*/
beforeTweet?: TweetResolvable;
/**
* The granularity of the {@link TweetCountBucket}
*/
granularity?: Granularity;
}
/**
* The data to instantiate {@link BaseStructure} with
*/
export interface BaseStructureData {
id: Snowflake;
}
/**
* The options used for creating a new list
*/
export interface CreateListOptions {
/**
* The name of the list
*/
name: string;
/**
* The description of the list
*/
description?: string;
/**
* Whether the list should be private
*/
private?: boolean;
}
/**
* The options used to update a list
*/
export type UpdateListOptions = Partial<CreateListOptions>;
/**
* Options used to feth a single filtered stream rule
*/
export interface FetchFilteredStreamRuleOptions extends BaseFetchOptions {
/**
* The rule to fetch
*/
rule: FilteredStreamRuleResolvable;
}
/**
* Options used to feth multiple filtered stream rules
*/
export interface FetchFilteredStreamRulesOptions extends Omit<BaseFetchOptions, 'skipCacheCheck'> {
/**
* The rules to fetch, fetches all if not provided
*/
rules?: Array<FilteredStreamRuleResolvable>;
} | 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 CloudWatch Metric Stream resource.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* // https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-metric-streams-trustpolicy.html
* const metricStreamToFirehoseRole = new aws.iam.Role("metricStreamToFirehoseRole", {assumeRolePolicy: `{
* "Version": "2012-10-17",
* "Statement": [
* {
* "Action": "sts:AssumeRole",
* "Principal": {
* "Service": "streams.metrics.cloudwatch.amazonaws.com"
* },
* "Effect": "Allow",
* "Sid": ""
* }
* ]
* }
* `});
* const bucket = new aws.s3.Bucket("bucket", {acl: "private"});
* const firehoseToS3Role = new aws.iam.Role("firehoseToS3Role", {assumeRolePolicy: `{
* "Version": "2012-10-17",
* "Statement": [
* {
* "Action": "sts:AssumeRole",
* "Principal": {
* "Service": "firehose.amazonaws.com"
* },
* "Effect": "Allow",
* "Sid": ""
* }
* ]
* }
* `});
* const s3Stream = new aws.kinesis.FirehoseDeliveryStream("s3Stream", {
* destination: "s3",
* s3Configuration: {
* roleArn: firehoseToS3Role.arn,
* bucketArn: bucket.arn,
* },
* });
* const main = new aws.cloudwatch.MetricStream("main", {
* roleArn: metricStreamToFirehoseRole.arn,
* firehoseArn: s3Stream.arn,
* outputFormat: "json",
* includeFilters: [
* {
* namespace: "AWS/EC2",
* },
* {
* namespace: "AWS/EBS",
* },
* ],
* });
* // https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-metric-streams-trustpolicy.html
* const metricStreamToFirehoseRolePolicy = new aws.iam.RolePolicy("metricStreamToFirehoseRolePolicy", {
* role: metricStreamToFirehoseRole.id,
* policy: pulumi.interpolate`{
* "Version": "2012-10-17",
* "Statement": [
* {
* "Effect": "Allow",
* "Action": [
* "firehose:PutRecord",
* "firehose:PutRecordBatch"
* ],
* "Resource": "${s3Stream.arn}"
* }
* ]
* }
* `,
* });
* const firehoseToS3RolePolicy = new aws.iam.RolePolicy("firehoseToS3RolePolicy", {
* role: firehoseToS3Role.id,
* policy: pulumi.interpolate`{
* "Version": "2012-10-17",
* "Statement": [
* {
* "Effect": "Allow",
* "Action": [
* "s3:AbortMultipartUpload",
* "s3:GetBucketLocation",
* "s3:GetObject",
* "s3:ListBucket",
* "s3:ListBucketMultipartUploads",
* "s3:PutObject"
* ],
* "Resource": [
* "${bucket.arn}",
* "${bucket.arn}/*"
* ]
* }
* ]
* }
* `,
* });
* ```
*
* ## Import
*
* CloudWatch metric streams can be imported using the `name`, e.g.
*
* ```sh
* $ pulumi import aws:cloudwatch/metricStream:MetricStream sample <name>
* ```
*/
export class MetricStream extends pulumi.CustomResource {
/**
* Get an existing MetricStream 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?: MetricStreamState, opts?: pulumi.CustomResourceOptions): MetricStream {
return new MetricStream(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:cloudwatch/metricStream:MetricStream';
/**
* Returns true if the given object is an instance of MetricStream. 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 MetricStream {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === MetricStream.__pulumiType;
}
/**
* ARN of the metric stream.
*/
public /*out*/ readonly arn!: pulumi.Output<string>;
/**
* Date and time in [RFC3339 format](https://tools.ietf.org/html/rfc3339#section-5.8) that the metric stream was created.
*/
public /*out*/ readonly creationDate!: pulumi.Output<string>;
/**
* List of exclusive metric filters. If you specify this parameter, the stream sends metrics from all metric namespaces except for the namespaces that you specify here. Conflicts with `includeFilter`.
*/
public readonly excludeFilters!: pulumi.Output<outputs.cloudwatch.MetricStreamExcludeFilter[] | undefined>;
/**
* ARN of the Amazon Kinesis Firehose delivery stream to use for this metric stream.
*/
public readonly firehoseArn!: pulumi.Output<string>;
/**
* List of inclusive metric filters. If you specify this parameter, the stream sends only the metrics from the metric namespaces that you specify here. Conflicts with `excludeFilter`.
*/
public readonly includeFilters!: pulumi.Output<outputs.cloudwatch.MetricStreamIncludeFilter[] | undefined>;
/**
* Date and time in [RFC3339 format](https://tools.ietf.org/html/rfc3339#section-5.8) that the metric stream was last updated.
*/
public /*out*/ readonly lastUpdateDate!: pulumi.Output<string>;
public readonly name!: pulumi.Output<string>;
/**
* Creates a unique friendly name beginning with the specified prefix. Conflicts with `name`.
*/
public readonly namePrefix!: pulumi.Output<string>;
/**
* Output format for the stream. Possible values are `json` and `opentelemetry0.7`. For more information about output formats, see [Metric streams output formats](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-metric-streams-formats.html).
*/
public readonly outputFormat!: pulumi.Output<string>;
/**
* ARN of the IAM role that this metric stream will use to access Amazon Kinesis Firehose resources. For more information about role permissions, see [Trust between CloudWatch and Kinesis Data Firehose](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-metric-streams-trustpolicy.html).
*/
public readonly roleArn!: pulumi.Output<string>;
/**
* State of the metric stream. Possible values are `running` and `stopped`.
*/
public /*out*/ readonly state!: pulumi.Output<string>;
/**
* Map of tags to assign to the resource. 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 `defaultTags` configuration block.
*/
public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>;
/**
* Create a MetricStream 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: MetricStreamArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: MetricStreamArgs | MetricStreamState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as MetricStreamState | undefined;
inputs["arn"] = state ? state.arn : undefined;
inputs["creationDate"] = state ? state.creationDate : undefined;
inputs["excludeFilters"] = state ? state.excludeFilters : undefined;
inputs["firehoseArn"] = state ? state.firehoseArn : undefined;
inputs["includeFilters"] = state ? state.includeFilters : undefined;
inputs["lastUpdateDate"] = state ? state.lastUpdateDate : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["namePrefix"] = state ? state.namePrefix : undefined;
inputs["outputFormat"] = state ? state.outputFormat : undefined;
inputs["roleArn"] = state ? state.roleArn : undefined;
inputs["state"] = state ? state.state : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["tagsAll"] = state ? state.tagsAll : undefined;
} else {
const args = argsOrState as MetricStreamArgs | undefined;
if ((!args || args.firehoseArn === undefined) && !opts.urn) {
throw new Error("Missing required property 'firehoseArn'");
}
if ((!args || args.outputFormat === undefined) && !opts.urn) {
throw new Error("Missing required property 'outputFormat'");
}
if ((!args || args.roleArn === undefined) && !opts.urn) {
throw new Error("Missing required property 'roleArn'");
}
inputs["excludeFilters"] = args ? args.excludeFilters : undefined;
inputs["firehoseArn"] = args ? args.firehoseArn : undefined;
inputs["includeFilters"] = args ? args.includeFilters : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["namePrefix"] = args ? args.namePrefix : undefined;
inputs["outputFormat"] = args ? args.outputFormat : undefined;
inputs["roleArn"] = args ? args.roleArn : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["arn"] = undefined /*out*/;
inputs["creationDate"] = undefined /*out*/;
inputs["lastUpdateDate"] = undefined /*out*/;
inputs["state"] = undefined /*out*/;
inputs["tagsAll"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(MetricStream.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering MetricStream resources.
*/
export interface MetricStreamState {
/**
* ARN of the metric stream.
*/
arn?: pulumi.Input<string>;
/**
* Date and time in [RFC3339 format](https://tools.ietf.org/html/rfc3339#section-5.8) that the metric stream was created.
*/
creationDate?: pulumi.Input<string>;
/**
* List of exclusive metric filters. If you specify this parameter, the stream sends metrics from all metric namespaces except for the namespaces that you specify here. Conflicts with `includeFilter`.
*/
excludeFilters?: pulumi.Input<pulumi.Input<inputs.cloudwatch.MetricStreamExcludeFilter>[]>;
/**
* ARN of the Amazon Kinesis Firehose delivery stream to use for this metric stream.
*/
firehoseArn?: pulumi.Input<string>;
/**
* List of inclusive metric filters. If you specify this parameter, the stream sends only the metrics from the metric namespaces that you specify here. Conflicts with `excludeFilter`.
*/
includeFilters?: pulumi.Input<pulumi.Input<inputs.cloudwatch.MetricStreamIncludeFilter>[]>;
/**
* Date and time in [RFC3339 format](https://tools.ietf.org/html/rfc3339#section-5.8) that the metric stream was last updated.
*/
lastUpdateDate?: pulumi.Input<string>;
name?: pulumi.Input<string>;
/**
* Creates a unique friendly name beginning with the specified prefix. Conflicts with `name`.
*/
namePrefix?: pulumi.Input<string>;
/**
* Output format for the stream. Possible values are `json` and `opentelemetry0.7`. For more information about output formats, see [Metric streams output formats](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-metric-streams-formats.html).
*/
outputFormat?: pulumi.Input<string>;
/**
* ARN of the IAM role that this metric stream will use to access Amazon Kinesis Firehose resources. For more information about role permissions, see [Trust between CloudWatch and Kinesis Data Firehose](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-metric-streams-trustpolicy.html).
*/
roleArn?: pulumi.Input<string>;
/**
* State of the metric stream. Possible values are `running` and `stopped`.
*/
state?: pulumi.Input<string>;
/**
* Map of tags to assign to the resource. 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 `defaultTags` configuration block.
*/
tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
}
/**
* The set of arguments for constructing a MetricStream resource.
*/
export interface MetricStreamArgs {
/**
* List of exclusive metric filters. If you specify this parameter, the stream sends metrics from all metric namespaces except for the namespaces that you specify here. Conflicts with `includeFilter`.
*/
excludeFilters?: pulumi.Input<pulumi.Input<inputs.cloudwatch.MetricStreamExcludeFilter>[]>;
/**
* ARN of the Amazon Kinesis Firehose delivery stream to use for this metric stream.
*/
firehoseArn: pulumi.Input<string>;
/**
* List of inclusive metric filters. If you specify this parameter, the stream sends only the metrics from the metric namespaces that you specify here. Conflicts with `excludeFilter`.
*/
includeFilters?: pulumi.Input<pulumi.Input<inputs.cloudwatch.MetricStreamIncludeFilter>[]>;
name?: pulumi.Input<string>;
/**
* Creates a unique friendly name beginning with the specified prefix. Conflicts with `name`.
*/
namePrefix?: pulumi.Input<string>;
/**
* Output format for the stream. Possible values are `json` and `opentelemetry0.7`. For more information about output formats, see [Metric streams output formats](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-metric-streams-formats.html).
*/
outputFormat: pulumi.Input<string>;
/**
* ARN of the IAM role that this metric stream will use to access Amazon Kinesis Firehose resources. For more information about role permissions, see [Trust between CloudWatch and Kinesis Data Firehose](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-metric-streams-trustpolicy.html).
*/
roleArn: pulumi.Input<string>;
/**
* Map of tags to assign to the resource. 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>}>;
} | the_stack |
import {
app, BrowserWindow, ipcMain, shell
} from 'electron';
import {
IService
} from './main';
import {
ElectronStateDB
} from './state';
import {
JSONObject, JSONValue
} from '@lumino/coreutils';
import log from 'electron-log';
import { AsyncRemote, asyncRemoteMain } from '../asyncremote';
import fetch from 'node-fetch';
import * as yaml from 'js-yaml';
import * as semver from 'semver';
export
interface IApplication {
/**
* Register as service with persistent state.
*
* @return promise fulfileld with the service's previous state.
*/
registerStatefulService: (service: IStatefulService) => Promise<JSONValue>;
registerClosingService: (service: IClosingService) => void;
/**
* Force the application service to write data to the disk.
*/
saveState: (service: IStatefulService, data: JSONValue) => Promise<void>;
}
/**
* A service that has data that needs to persist.
*/
export
interface IStatefulService {
/**
* The human-readable id for the service state. Must be unique
* to each service.
*/
id: string;
/**
* Called before the application quits. Qutting will
* be suspended until the returned promise is resolved with
* the service's state.
*
* @return promise that is fulfilled with the service's state.
*/
getStateBeforeQuit(): Promise<JSONValue>;
/**
* Called before state is passed to the service. Implementing
* services should scan the state for issues in this function.
* If the data is invalid, the function should return false.
*
* @return true if the data is valid, false otherwise.
*/
verifyState: (state: JSONValue) => boolean;
}
/**
* A service that has to complete some task on application exit
*/
export
interface IClosingService {
/**
* Called before the application exits and after the states are saved.
* Service resolves the promise upon a successful cleanup.
*
* @return promise that is fulfilled when the service is ready to quit
*/
finished(): Promise<void>;
}
export
namespace IAppRemoteInterface {
export
let checkForUpdates: AsyncRemote.IMethod<void, void> = {
id: 'JupyterLabDesktop-check-for-updates'
};
export
let openDevTools: AsyncRemote.IMethod<void, void> = {
id: 'JupyterLabDesktop-open-dev-tools'
};
}
export
class JupyterApplication implements IApplication, IStatefulService {
readonly id = 'JupyterLabDesktop';
/**
* Construct the Jupyter application
*/
constructor() {
this._registerListeners();
// Get application state from state db file.
this._appState = new Promise<JSONObject>((res, rej) => {
this._appStateDB.fetch(JupyterApplication.APP_STATE_NAMESPACE)
.then((state: JSONObject) => {
res(state);
})
.catch( (e) => {
log.error(e);
res({});
});
});
this._applicationState = {
checkForUpdatesAutomatically: true
};
this.registerStatefulService(this)
.then((state: JupyterApplication.IState) => {
if (state) {
this._applicationState = state;
}
if (this._applicationState.checkForUpdatesAutomatically) {
setTimeout(() => {
this._checkForUpdates('on-new-version');
}, 5000);
}
});
}
registerStatefulService(service: IStatefulService): Promise<JSONValue> {
this._services.push(service);
return new Promise<JSONValue>((res, rej) => {
this._appState
.then((state: JSONObject) => {
if (state[service.id] && service.verifyState(state[service.id])) {
res(state[service.id]);
}
res(null);
})
.catch(() => {res(null); });
});
}
registerClosingService(service: IClosingService): void {
this._closing.push(service);
}
saveState(service: IStatefulService, data: JSONValue): Promise<void> {
this._updateState(service.id, data);
return this._saveState();
}
getStateBeforeQuit(): Promise<JupyterApplication.IState> {
return Promise.resolve(this._applicationState);
}
verifyState(state: JupyterApplication.IState): boolean {
return true;
}
private _updateState(id: string, data: JSONValue): void {
let prevState = this._appState;
this._appState = new Promise<JSONObject>((res, rej) => {
prevState
.then((state: JSONObject) => {
state[id] = data;
res(state);
})
.catch((state: JSONObject) => res(state));
});
}
private _rewriteState(ids: string[], data: JSONValue[]): void {
let prevState = this._appState;
this._appState = new Promise<JSONObject>((res, rej) => {
prevState
.then(() => {
let state: JSONObject = {};
ids.forEach((id: string, idx: number) => {
state[id] = data[idx];
});
res(state);
})
.catch((state: JSONObject) => res(state));
});
}
private _saveState(): Promise<void> {
return new Promise<void>((res, rej) => {
this._appState
.then((state: JSONObject) => {
return this._appStateDB.save(JupyterApplication.APP_STATE_NAMESPACE, state);
})
.then(() => {
res();
})
.catch((e) => {
rej(e);
});
});
}
/**
* Register all application event listeners
*/
private _registerListeners(): void {
// On OS X it is common for applications and their menu bar to stay
// active until the user quits explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('will-quit', (event) => {
event.preventDefault();
// Collect data from services
let state: Promise<JSONValue>[] = this._services.map((s: IStatefulService) => {
return s.getStateBeforeQuit();
});
let ids: string[] = this._services.map((s: IStatefulService) => {
return s.id;
});
// Wait for all services to return state
Promise.all(state)
.then((data: JSONValue[]) => {
this._rewriteState(ids, data);
return this._saveState();
})
.then(() => {
this._quit();
})
.catch(() => {
log.error(new Error('JupyterLab did not save state successfully'));
this._quit();
});
});
app.on('browser-window-focus', (_event: Event, window: BrowserWindow) => {
this._window = window;
});
ipcMain.on('set-check-for-updates-automatically', (_event, autoUpdate) => {
this._applicationState.checkForUpdatesAutomatically = autoUpdate;
});
ipcMain.on('launch-installer-download-page', () => {
shell.openExternal('https://github.com/jupyterlab/jupyterlab-desktop/releases');
});
asyncRemoteMain.registerRemoteMethod(IAppRemoteInterface.checkForUpdates,
(): Promise<void> => {
this._checkForUpdates('always');
return Promise.resolve();
});
asyncRemoteMain.registerRemoteMethod(IAppRemoteInterface.openDevTools,
(): Promise<void> => {
this._window.webContents.openDevTools();
return Promise.resolve();
});
}
private _showUpdateDialog(type: 'updates-available' | 'error' | 'no-updates') {
const dialog = new BrowserWindow({
title: 'JupyterLab Update',
width: 400,
height: 150,
resizable: false,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false
}
});
dialog.setMenuBarVisibility(false);
const checkForUpdatesAutomatically = this._applicationState.checkForUpdatesAutomatically !== false;
const message =
type === 'error' ? 'Error occurred while checking for updates!' :
type === 'no-updates' ? 'There are no updates available.' :
`There is a new version available. Download the latest version from <a href="javascript:void(0)" onclick='handleReleasesLink(this);'>the Releases page</a>.`
const pageSource = `
<body style="background: rgba(238,238,238,1); font-size: 13px; font-family: Helvetica, Arial, sans-serif">
<div style="height: 100%; display: flex;flex-direction: column; justify-content: space-between;">
<div>
${message}
</div>
<div>
<label><input type='checkbox' ${checkForUpdatesAutomatically ? 'checked' : ''} onclick='handleAutoCheckForUpdates(this);'>Check for updates automatically</label>
</div>
</div>
<script>
const ipcRenderer = require('electron').ipcRenderer;
function handleAutoCheckForUpdates(el) {
ipcRenderer.send('set-check-for-updates-automatically', el.checked);
}
function handleReleasesLink(el) {
ipcRenderer.send('launch-installer-download-page');
}
</script>
</body>
`;
dialog.loadURL(`data:text/html;charset=utf-8,${pageSource}`);
}
private _checkForUpdates(showDialog: 'on-new-version' | 'always') {
fetch('https://github.com/jupyterlab/jupyterlab-desktop/releases/latest/download/latest.yml').then(async (response) => {
try {
const data = await response.text();
const latestReleaseData = yaml.load(data);
const latestVersion = (latestReleaseData as any).version;
const currentVersion = app.getVersion();
const newVersionAvailable = semver.compare(currentVersion, latestVersion) === -1;
if (showDialog === 'always' || newVersionAvailable) {
this._showUpdateDialog(newVersionAvailable ? 'updates-available' : 'no-updates');
}
} catch (error) {
if (showDialog === 'always') {
this._showUpdateDialog('error');
}
console.error('Failed to check for updates:', error);
}
}).catch((error) => {
if (showDialog === 'always') {
this._showUpdateDialog('error');
}
console.error('Failed to check for updates:', error);
});
}
private _quit(): void {
let closing: Promise<void>[] = this._closing.map((s: IClosingService) => {
return s.finished();
});
Promise.all(closing)
.then( () => {process.exit(); })
.catch( (err) => {
log.error(new Error('JupyterLab could not close successfully'));
process.exit();
});
}
private _appStateDB = new ElectronStateDB({namespace: 'jupyterlab-desktop-data'});
private _appState: Promise<JSONObject>;
private _applicationState: JupyterApplication.IState;
private _services: IStatefulService[] = [];
private _closing: IClosingService[] = [];
/**
* The most recently focused window
*/
private _window: Electron.BrowserWindow;
}
export
namespace JupyterApplication {
export
const APP_STATE_NAMESPACE = 'jupyterlab-desktop';
export
interface IState extends JSONObject {
checkForUpdatesAutomatically?: boolean;
}
}
let service: IService = {
requirements: [],
provides: 'IApplication',
activate: (): IApplication => {
return new JupyterApplication();
}
};
export default service; | the_stack |
import { peek, Disposer, reverse } from '@/lib/std';
import Vue from 'vue';
import { reactive } from '@vue/composition-api';
import { emitter } from '@/lib/events';
import { getLogger } from '@/lib/log';
const logger = getLogger('olyger');
// You can read more about this file in the following issue:
// https://github.com/dawg/dawg/issues/156
// This is from the composition API
// We should probably remove this but idk
const RefKey = 'vfa.key.refKey';
interface Command<T> {
id: number;
name: string;
execute: () => T;
emit: (o: T) => void;
undo: () => void;
subscriptions: Subscription[];
}
interface ExecutedCommand<T> extends Command<T> {
undoers: Array<ReturnType<Subscription['execute']>>;
}
export const genId = ((i) => () => i++)(0);
export interface ExecutedAction<T> {
id: number;
commands: Array<ExecutedCommand<T>>;
}
export interface Action<T> {
id: number;
commands: Array<Command<T>>;
}
interface Context {
reference?: Action<any>;
top?: Action<any>;
hasUnsavedChanged: boolean;
}
const undoHistory: Array<ExecutedAction<any>> = [];
const redoHistory: Array<Action<any>> = [];
const context: Context = {
reference: undefined,
top: undefined,
hasUnsavedChanged: false,
};
export const undoStack: Readonly<Array<ExecutedAction<any>>> = undoHistory;
export const redoStack: Readonly<Array<Action<any>>> = redoHistory;
export const undoRedoContext: Readonly<Context> = context;
type State = 'unsaved' | 'saved';
const stateChangeEvents = emitter<{ stateChange: [State] }>();
export const onDidStateChange = (cb: (state: State) => void) => {
return stateChangeEvents.on('stateChange', cb);
};
const setValue = (key: 'reference' | 'top', a: Action<any> | undefined) => {
context[key] = a;
const oldValue = context.hasUnsavedChanged;
const newValue = context.hasUnsavedChanged = context.reference !== context.top;
if (oldValue !== newValue) {
stateChangeEvents.emit('stateChange', newValue ? 'unsaved' : 'saved');
}
};
let action: ExecutedAction<any> | undefined;
// Beware we group ALL actions together even if they are different actions
// This works well for now but may not be desirable in future use cases
let group: { action: ExecutedAction<any> } | undefined;
const getOrCreateExecutionContext = () => {
let startOfExecution = false;
let startOfGroupedExecution = false;
if (!action) {
if (group) {
startOfGroupedExecution = true;
action = group.action;
} else {
startOfExecution = true;
action = { commands: [], id: genId() };
group = { action };
setTimeout(() => {
group = undefined;
}, 500);
}
}
// create a local copy which is not undefined
const local = action;
const execute = <T>(command: Command<T>) => {
const result = command.execute();
command.emit(result);
local.commands.push({
...command,
undoers: command.subscriptions.map((subscription) => subscription.execute()),
});
return result;
};
if (startOfGroupedExecution) {
return {
execute,
finish: () => {
action = undefined;
},
};
}
if (!startOfExecution) {
return {
execute,
finish: () => {
// do nothing
},
};
}
return {
execute,
finish: () => {
undoHistory.push(local);
setValue('top', local);
// Everything in the redo stack is going to be lost forever at this point
// If needed, subscriptions can have a dispose method for cleaning up after themselves
redoHistory.forEach((a) => {
a.commands.forEach((command) => {
command.subscriptions.forEach((subscription) => {
if (subscription.dispose) {
subscription.dispose();
}
});
});
});
redoHistory.splice(0, redoHistory.length);
action = undefined;
logger.debug(
`Executed -> ${local.commands.map((c) => c.name).join(', ')} [${undoHistory.length}, ${redoHistory.length}]`,
);
},
};
};
export const undo = (): 'empty' | 'performed' => {
const undoTop = undoHistory.pop();
if (!undoTop) {
return 'empty';
}
for (const command of reverse(undoTop.commands)) {
command.undo();
command.undoers.forEach((undoer) => undoer.undo());
}
redoHistory.push(undoTop);
setValue('top', peek(undoHistory));
context.hasUnsavedChanged = context.top !== context.reference;
logger.debug(
`Undid -> ${undoTop.commands.map((c) => c.name).join(', ')} [${undoHistory.length}, ${redoHistory.length}]`,
);
return 'performed';
};
export const redo = (): 'empty' | 'performed' => {
const redoTop = redoHistory.pop();
if (!redoTop) {
return 'empty';
}
for (const command of redoTop.commands) {
command.execute();
}
undoHistory.push({
id: redoTop.id,
commands: redoTop.commands.map((command) => {
return {
...command,
undoers: command.subscriptions.map((subscription) => subscription.execute()),
};
}),
});
setValue('top', redoTop);
logger.debug(
`Redid -> ${redoTop.commands.map((c) => c.name).join(', ')} [${undoHistory.length}, ${redoHistory.length}]`,
);
return 'performed';
};
export const freezeReference = () => {
setValue('reference', peek(undoHistory));
};
function proxy<T, V>(
target: V, { get, set }: GetSet<T>,
): V & { value: T } {
Object.defineProperty(target, 'value', {
enumerable: true,
configurable: true,
get,
set,
});
return target as V & { value: T };
}
interface GetSet<T> {
get(): T;
set(x: T): void;
}
interface Ref<T> {
value: T;
}
interface Subscription {
execute: () => { undo: () => void };
/**
* This is called for cleaning up purposes. At this point, we will never call the subscription again.
*/
dispose?: () => void;
}
type Undo = () => void;
type Execute = () => Undo | Disposer[] | Disposer;
interface ElementChangeContext<T> {
newValue: T;
oldValue: T;
onExecute: (cb: Execute) => void;
subscriptions: Subscription[];
}
interface ElementChaining<T> {
onDidChange: (cb: (o: ElementChangeContext<T>) => void) => Disposer;
}
const onExecuteHelper = (subscriptions: Subscription[]) => {
return (cb: Execute) => {
subscriptions.push({
execute: () => {
const result = cb();
if (typeof result === 'function') {
return {
undo: result,
};
}
if (Array.isArray(result)) {
return {
undo: () => {
result.forEach((disposer) => disposer.dispose());
},
};
}
return {
undo: () => {
result.dispose();
},
};
},
});
};
};
export type OlyRef<T> = Ref<T> & ElementChaining<T>;
export function olyRef<T>(raw: T, name?: string): Ref<T> & ElementChaining<T> {
const o = reactive({ [RefKey]: raw }) as { [RefKey]: T };
const id = genId();
const events = emitter<{ change: [ElementChangeContext<T>] }>();
const ref = proxy({}, {
get: () => o[RefKey],
set: (v) => {
const oldValue = o[RefKey];
const subscriptions: Subscription[] = [];
const onExecute = onExecuteHelper(subscriptions);
// This is important as it prevents a command being placed on the stack
if (oldValue === v) {
return;
}
const env = getOrCreateExecutionContext();
env.execute({
id,
name: `Set${name ? ` ${name}` : ''} to ${v}`,
subscriptions,
execute: () => {
o[RefKey] = v;
},
emit: () => {
events.emit('change', { newValue: v, oldValue, subscriptions, onExecute });
},
undo: () => {
o[RefKey] = oldValue;
},
});
env.finish();
},
});
const chaining: ElementChaining<T> = {
onDidChange: (cb) => events.on('change', cb),
};
return Object.assign(ref, chaining);
}
interface Items<T> {
items: T[];
startingIndex: number;
onExecute: (cb: Execute) => void;
subscriptions: Subscription[];
}
interface ArrayChaining<T> {
onDidAdd: (cb: (o: Items<T>) => void) => Disposer;
onDidRemove: (cb: (o: Items<T>) => void) => Disposer;
}
export type OlyArr<T> = T[] & ArrayChaining<T>;
export const olyArr = <T>(raw: T[], name: string): OlyArr<T> => {
// Explicitly make the array observable because we replace some of the methods
// We store local variables in this closure and these NEED to be the vue ones for reactivity
// Therefore, we make the following call
raw = Vue.observable(raw);
const events = emitter<{ add: [Items<T>], remove: [Items<T>] }>();
const push = raw.push.bind(raw);
const splice = raw.splice.bind(raw);
const pushId = genId();
const spliceId = genId();
raw.push = (...items) => {
const length = raw.length;
const subscriptions: Subscription[] = [];
const onExecute = onExecuteHelper(subscriptions);
const env = getOrCreateExecutionContext();
const commandName = items.length === 1 ?
`Added ${name}` :
`Added ${items.length} ${items.length}s`;
const addedLength = env.execute({
id: pushId,
name: commandName,
subscriptions,
execute: () => {
const result = push(...items);
return result;
},
emit: () => {
events.emit('add', { items, startingIndex: length, subscriptions, onExecute });
},
undo: () => {
splice(length, items.length);
},
});
env.finish();
return addedLength;
};
raw.splice = (start: number, deleteCount: number, ...items: T[]) => {
if (!deleteCount && items.length === 0) {
return [];
}
const subscriptions: Subscription[] = [];
const onExecute = onExecuteHelper(subscriptions);
const env = getOrCreateExecutionContext();
let commandName = '';
if (items.length === 1) {
commandName += `Added ${name}`;
} else if (items.length > 1) {
commandName += `Added ${items.length} ${name}s`;
}
if (deleteCount === 1) {
commandName += commandName ?
` and Deleted ${name}` :
`Deleted ${name}`;
} else if (deleteCount > 1) {
commandName += commandName ?
` and Deleted ${deleteCount} ${name}s` :
`Deleted ${deleteCount} ${name}s`;
}
const deleted: T[] = env.execute({
id: spliceId,
name: commandName,
subscriptions,
execute: () => {
const result = splice(start, deleteCount, ...items);
return result;
},
emit(result) {
events.emit('remove', { items: result, startingIndex: start, subscriptions, onExecute });
events.emit('add', { items, startingIndex: start, subscriptions, onExecute });
},
undo: () => {
splice(start, items.length, ...deleted);
},
});
env.finish();
return deleted;
};
const chaining: ArrayChaining<T> = {
onDidAdd: (f) => events.on('add', f),
onDidRemove: (f) => events.on('remove', f),
};
return Object.assign(
raw,
chaining,
);
}; | the_stack |
import graphlib from '../graphlib';
import util from '../util';
import { graphlib as IGraphLib } from '../../graphlib';
type IGraph = IGraphLib.Graph;
const Graph = (graphlib as any).Graph;
/*
* This module provides coordinate assignment based on Brandes and Köpf, "Fast
* and Simple Horizontal Coordinate Assignment."
*/
/*
* Marks all edges in the graph with a type-1 conflict with the "type1Conflict"
* property. A type-1 conflict is one where a non-inner segment crosses an
* inner segment. An inner segment is an edge with both incident nodes marked
* with the "dummy" property.
*
* This algorithm scans layer by layer, starting with the second, for type-1
* conflicts between the current layer and the previous layer. For each layer
* it scans the nodes from left to right until it reaches one that is incident
* on an inner segment. It then scans predecessors to determine if they have
* edges that cross that inner segment. At the end a final scan is done for all
* nodes on the current rank to see if they cross the last visited inner
* segment.
*
* This algorithm (safely) assumes that a dummy node will only be incident on a
* single node in the layers being scanned.
*/
const findType1Conflicts = (g: IGraph, layering?: any) => {
const conflicts = {};
const visitLayer = (prevLayer: any, layer: any) => {
// last visited node in the previous layer that is incident on an inner
// segment.
let k0 = 0;
// Tracks the last node in this layer scanned for crossings with a type-1
// segment.
let scanPos = 0;
const prevLayerLength = prevLayer.length;
const lastNode = layer[layer?.length - 1];
layer.forEach((v: string, i: number) => {
const w = findOtherInnerSegmentNode(g, v);
const k1 = w ? g.node(w).order : prevLayerLength;
if (w || v === lastNode) {
layer.slice(scanPos, i +1).forEach((scanNode: any) => {
g.predecessors(scanNode)?.forEach((u: any) => {
const uLabel = g.node(u);
const uPos = uLabel.order as number;
if ((uPos < k0 || k1 < uPos) &&
!(uLabel.dummy && g.node(scanNode).dummy)) {
addConflict(conflicts, u, scanNode);
}
});
});
scanPos = i + 1;
k0 = k1;
}
});
return layer;
};
if (layering?.length) {
layering.reduce(visitLayer);
}
return conflicts;
};
const findType2Conflicts = (g: IGraph, layering?: any) => {
const conflicts = {};
const scan = (south: string[], southPos: number, southEnd: number, prevNorthBorder: number, nextNorthBorder: number) => {
let v: any;
const range = [];
for (let i = southPos; i < southEnd; i++ ) {
range.push(i);
}
range.forEach((i) => {
v = south[i];
if (g.node(v).dummy) {
g.predecessors(v)?.forEach((u: any) => {
const uNode = g.node(u);
if (uNode.dummy &&
((uNode.order as number) < prevNorthBorder || (uNode.order as number) > nextNorthBorder)) {
addConflict(conflicts, u, v);
}
});
}
});
};
const visitLayer = (north: string[], south: string[]) => {
let prevNorthPos = -1;
let nextNorthPos: number;
let southPos = 0;
south.forEach((v: string, southLookahead: number) => {
if (g.node(v).dummy === "border") {
const predecessors = g.predecessors(v) || [];
if (predecessors.length) {
nextNorthPos = g.node(predecessors[0]).order as number;
scan(south, southPos, southLookahead, prevNorthPos, nextNorthPos);
southPos = southLookahead;
prevNorthPos = nextNorthPos;
}
}
scan(south, southPos, south.length, nextNorthPos, north.length);
});
return south;
};
if (layering?.length) {
layering.reduce(visitLayer);
}
return conflicts;
};
const findOtherInnerSegmentNode = (g: IGraph, v: string) => {
if (g.node(v).dummy) {
return g.predecessors(v)?.find((u) => g.node(u).dummy);
}
};
const addConflict = (conflicts: any, v: number, w: number) => {
let vv = v;
let ww = w;
if (vv > ww) {
const tmp = vv;
vv = ww;
ww = tmp;
}
let conflictsV = conflicts[vv];
if (!conflictsV) {
conflicts[vv] = conflictsV = {};
}
conflictsV[ww] = true;
};
const hasConflict = (conflicts: any, v: number, w: number) => {
let vv = v;
let ww = w;
if (vv > ww) {
const tmp = v;
vv = ww;
ww = tmp;
}
return conflicts[vv] && conflicts[vv].hasOwnProperty(ww);
};
/*
* Try to align nodes into vertical "blocks" where possible. This algorithm
* attempts to align a node with one of its median neighbors. If the edge
* connecting a neighbor is a type-1 conflict then we ignore that possibility.
* If a previous node has already formed a block with a node after the node
* we're trying to form a block with, we also ignore that possibility - our
* blocks would be split in that scenario.
*/
const verticalAlignment = (g: IGraph, layering: any, conflicts: any, neighborFn: (v: string) => unknown) => {
const root: any = {};
const align: any = {};
const pos: any = {};
// We cache the position here based on the layering because the graph and
// layering may be out of sync. The layering matrix is manipulated to
// generate different extreme alignments.
layering.forEach((layer: any) => {
layer.forEach((v: string, order: number) => {
root[v] = v;
align[v] = v;
pos[v] = order;
});
});
layering.forEach((layer: any) => {
let prevIdx = -1;
layer.forEach((v: any) => {
let ws = neighborFn(v) as any;
if (ws.length) {
ws = ws.sort((a: string, b: string) => pos[a] - pos[b]);
const mp = (ws.length - 1) / 2;
for (let i = Math.floor(mp), il = Math.ceil(mp); i <= il; ++i) {
const w = ws[i];
if (align[v] === v &&
prevIdx < pos[w] &&
!hasConflict(conflicts, v, w)) {
align[w] = v;
align[v] = root[v] = root[w];
prevIdx = pos[w];
}
}
}
});
});
return { root, align };
};
const horizontalCompaction = (g: IGraph, layering: any, root: string, align: string[], reverseSep: boolean) => {
// This portion of the algorithm differs from BK due to a number of problems.
// Instead of their algorithm we construct a new block graph and do two
// sweeps. The first sweep places blocks with the smallest possible
// coordinates. The second sweep removes unused space by moving blocks to the
// greatest coordinates without violating separation.
const xs: any = {};
const blockG = buildBlockGraph(g, layering, root, reverseSep);
const borderType = reverseSep ? "borderLeft" : "borderRight";
const iterate = (setXsFunc: (param: string) => unknown, nextNodesFunc: (param: string) => any) => {
let stack = blockG.nodes();
let elem = stack.pop();
const visited: any = {};
while (elem) {
if (visited[elem]) {
setXsFunc(elem);
} else {
visited[elem] = true;
stack.push(elem);
stack = stack.concat(nextNodesFunc(elem));
}
elem = stack.pop();
}
};
// First pass, assign smallest coordinates
const pass1 = (elem: string) => {
xs[elem] = (blockG.inEdges(elem) || []).reduce((acc: number, e: any) => {
return Math.max(acc, (xs[e.v] || 0) + blockG.edge(e));
}, 0);
};
// Second pass, assign greatest coordinates
const pass2 = (elem: string) => {
const min = (blockG.outEdges(elem) || []).reduce((acc: number, e: any) => {
return Math.min(acc, (xs[e.w] || 0) - blockG.edge(e));
}, Number.POSITIVE_INFINITY);
const node = g.node(elem);
if (min !== Number.POSITIVE_INFINITY && node.borderType !== borderType) {
xs[elem] = Math.max(xs[elem], min);
}
};
iterate(pass1, blockG.predecessors.bind(blockG));
iterate(pass2, blockG.successors.bind(blockG));
// Assign x coordinates to all nodes
// @ts-ignore
Object.values(align).forEach((v: any) => {
xs[v] = xs[root[v]];
});
return xs;
};
const buildBlockGraph = (g: IGraph, layering: any, root: string, reverseSep: boolean) => {
const blockGraph = new Graph();
const graphLabel = g.graph();
const sepFn = sep(graphLabel.nodesep as number, graphLabel.edgesep as number, reverseSep as boolean);
layering.forEach((layer: any) => {
let u: any;
layer.forEach((v: any) => {
const vRoot = root[v];
blockGraph.setNode(vRoot);
if (u) {
const uRoot = root[u];
const prevMax = blockGraph.edge(uRoot, vRoot);
blockGraph.setEdge(uRoot, vRoot, Math.max(sepFn(g, v, u), prevMax || 0));
}
u = v;
});
});
return blockGraph;
};
/*
* Returns the alignment that has the smallest width of the given alignments.
*/
const findSmallestWidthAlignment = (g: IGraph, xss: any) => {
// @ts-ignore
return util.minBy(Object.values(xss), (xs) => {
let max = Number.NEGATIVE_INFINITY;
let min = Number.POSITIVE_INFINITY;
Object.keys(xs).forEach((v: string) => {
const x = xs[v];
const halfWidth = width(g, v) / 2;
max = Math.max(x + halfWidth, max);
min = Math.min(x - halfWidth, min);
});
return max - min;
});
};
/*
* Align the coordinates of each of the layout alignments such that
* left-biased alignments have their minimum coordinate at the same point as
* the minimum coordinate of the smallest width alignment and right-biased
* alignments have their maximum coordinate at the same point as the maximum
* coordinate of the smallest width alignment.
*/
function alignCoordinates(xss: any, alignTo: any) {
// @ts-ignore
const alignToVals = Object.values(alignTo) as number[];
const alignToMin = Math.min(...alignToVals);
const alignToMax = Math.max(...alignToVals);
["u", "d"].forEach((vert) => {
["l", "r"].forEach((horiz) => {
const alignment = vert + horiz;
const xs = xss[alignment];
let delta: number;
if (xs === alignTo) return;
const xsVals = Object.values(xs) as number[];
delta = horiz === "l" ? alignToMin - Math.min(...xsVals) : alignToMax - Math.max(...xsVals);
if (delta) {
xss[alignment] = {};
Object.keys(xs).forEach((key) => {
xss[alignment][key] = xs[key] + delta;
});
}
});
});
}
const balance = (xss: any, align: string) => {
const result: any = {};
Object.keys(xss.ul).forEach((key) => {
if (align) {
result[key] = xss[align.toLowerCase()][key];
} else {
// @ts-ignore
const values = Object.values(xss).map((x: any) => x[key]);
const xs = values.sort((a: number, b: number) => (a - b));
result[key] = (xs[1] + xs[2]) / 2;
}
});
return result;
// return _.mapValues(xss.ul, function(ignore, v) {
// if (align) {
// return xss[align.toLowerCase()][v];
// } else {
// const xs = _.sortBy(_.map(xss, v));
// return (xs[1] + xs[2]) / 2;
// }
// });
};
const positionX = (g: IGraph) => {
const layering = util.buildLayerMatrix(g);
const conflicts = Object.assign(
findType1Conflicts(g, layering),
findType2Conflicts(g, layering)
);
const xss: any = {};
let adjustedLayering: any;
["u", "d"].forEach((vert) => {
// @ts-ignore
adjustedLayering = vert === "u" ? layering : Object.values(layering).reverse();
["l", "r"].forEach((horiz) => {
if (horiz === "r") {
// @ts-ignore
adjustedLayering = adjustedLayering.map((inner: any) => Object.values(inner).reverse());
}
const neighborFn = (vert === "u" ? g.predecessors : g.successors).bind(g);
const align = verticalAlignment(g, adjustedLayering, conflicts, neighborFn);
let xs = horizontalCompaction(g, adjustedLayering,
align.root, align.align, horiz === "r");
if (horiz === "r") {
// @ts-ignore
xs = Object.values(xs).map((x: number) => -x);
}
xss[vert + horiz] = xs;
});
});
const smallestWidth = findSmallestWidthAlignment(g, xss);
alignCoordinates(xss, smallestWidth);
return balance(xss, g.graph().align as string);
};
const sep = (nodeSep: number, edgeSep: number, reverseSep: boolean) => {
return (g: IGraph, v: string, w: string) => {
const vLabel = g.node(v);
const wLabel = g.node(w);
let sum = 0;
let delta;
sum += vLabel.width / 2;
if (vLabel.hasOwnProperty("labelpos")) {
switch ((vLabel.labelpos || '').toLowerCase()) {
case "l": delta = -vLabel.width / 2; break;
case "r": delta = vLabel.width / 2; break;
}
}
if (delta) {
sum += reverseSep ? delta : -delta;
}
delta = 0;
sum += (vLabel.dummy ? edgeSep : nodeSep) / 2;
sum += (wLabel.dummy ? edgeSep : nodeSep) / 2;
sum += wLabel.width / 2;
if (wLabel.hasOwnProperty("labelpos")) {
switch ((wLabel.labelpos || '').toLowerCase()) {
case "l": delta = wLabel.width / 2; break;
case "r": delta = -wLabel.width / 2; break;
}
}
if (delta) {
sum += reverseSep ? delta : -delta;
}
delta = 0;
return sum;
};
};
const width = (g: IGraph, v: string) => g.node(v)?.width || 0;
export {
positionX,
findType1Conflicts,
findType2Conflicts,
addConflict,
hasConflict,
verticalAlignment,
horizontalCompaction,
alignCoordinates,
findSmallestWidthAlignment,
balance
};
export default {
positionX,
findType1Conflicts,
findType2Conflicts,
addConflict,
hasConflict,
verticalAlignment,
horizontalCompaction,
alignCoordinates,
findSmallestWidthAlignment,
balance
}; | the_stack |
export class DbConnect {
private readonly httpClient: HttpClient
/**
* Creates a DbConnect instance with host and credentials.
*
* @param host required, hostname or url of your Argo Tunnel running in db-connect mode.
* @param clientId recommended, client id of the Access policy for your host.
* @param clientSecret recommended, client secret of the Access policy for your host.
*/
constructor(parameters: DbConnectInit | object) {
const init = new DbConnectInit(parameters)
const url = new URL(init.host)
const headers = new Headers()
if(init.clientId) {
headers.set('Cf-access-client-id', init.clientId)
headers.set('Cf-access-client-secret', init.clientSecret)
}
this.httpClient = new HttpClient(url, <RequestInit> {
headers: headers,
keepalive: true,
cf: {
cacheEverything: true
}
})
}
/**
* Ping tests the connection to the database.
*
* To reduce latency, pings will be served stale for up to 1 second.
*
* @example
* const db = new DbConnect({ ... })
*
* async function doPing() {
* const resp = await db.ping()
* if(resp.ok) {
* return true
* }
* throw new Error(await resp.text())
* }
*/
public async ping(): Promise<Response> {
return this.httpClient.fetch('ping', {method: 'GET'}, 0, 1)
}
/**
* Submit sends a Command to the database and fetches a Response.
*
* @example
* const db = new DbConnect({ ... })
*
* async function doSubmit() {
* const cmd = new Command({
* statement: 'SELECT * FROM users WHERE name = ? AND age > ?',
* arguments: ['matthew', 21] })
* const resp = await db.submit(cmd)
* if(resp.ok) {
* return await resp.json()
* }
* throw new Error(await resp.text())
* }
*
* @param command required, the command to submit.
*/
public async submit(command: Command | object): Promise<Response> {
if(!(command instanceof Command)) command = new Command(command)
const cmd = <Command> command
const init = {
method: 'POST',
body: JSON.stringify(cmd),
headers: {'Content-type': 'application/json'}
}
return this.httpClient.fetch('submit', init, cmd.cacheTtl, cmd.staleTtl)
}
}
/**
* Initializer for DbConnect with host and credentials.
*
* @see DbConnect
*/
class DbConnectInit {
host: string
clientId?: string
clientSecret?: string
constructor(parameters: object) {
Object.assign(this, parameters)
if(!this.host) throw new TypeError('host is a required argument')
if(!this.host.startsWith('http')) this.host = `https://${this.host}`
if(!this.clientId != !this.clientSecret) throw new TypeError('both clientId and clientSecret must be specified')
}
}
/**
* Command is a standard, non-vendor format for submitting database commands.
*/
export class Command {
readonly statement: string
readonly arguments: any
readonly mode: Mode
readonly isolation: Isolation
readonly timeout: number
readonly cacheTtl: number
readonly staleTtl: number
/**
* Creates a new database Command.
*
* @param statement required, statement of the command.
* @param args an array or map of arguments, defaults to an empty array.
* @param mode mode of the command, defaults to 'query'.
* @param isolation isolation of the command, defaults to 'default'.
* @param timeout timeout in seconds of the command, defaults to indefinite.
* @param cacheTtl number of seconds to cache responses, defaults to -1.
* @param staleTtl after cacheTtl expires, number of seconds to serve stale responses.
*/
constructor(parameters: CommandInit | object) {
const init = new CommandInit(parameters)
Object.assign(this, init)
}
}
/**
* Initializer for Command with statement and options.
*
* @see Command
*/
class CommandInit {
statement: string
arguments?: any
mode?: Mode
isolation?: Isolation
timeout?: number
cacheTtl?: number
staleTtl?: number
constructor(parameters: object) {
Object.assign(this, parameters)
if(!this.statement) throw new TypeError('statement is a required argument')
if(!this.arguments) this.arguments = []
if(!this.mode) this.mode = Mode.query
if(!this.timeout) this.timeout = 0
if(!this.isolation) this.isolation = Isolation.none
if(!this.cacheTtl) this.cacheTtl = -1
if(!this.staleTtl) this.staleTtl = this.cacheTtl
}
}
/**
* Mode is a kind of Command.
* * query, a request for a set of rows or objects.
* * exec, an execution that returns a single result.
*
* @link https://golang.org/pkg/database/sql/#DB.Exec
*/
export enum Mode {
query = "query",
exec = "exec"
}
/**
* Isolation is a transaction type when executing a Command.
*
* @link https://golang.org/pkg/database/sql/#IsolationLevel
*/
export enum Isolation {
none = "none",
default = "default",
readUncommitted = "read_uncommitted",
readCommitted = "read_committed",
writeCommitted = "write_committed",
repeatableRead = "repeatable_read",
snapshot = "snapshot",
serializable = "serializable",
linearizable = "linearizable"
}
/**
* HttpClient is a convience wrapper for doing common transforms,
* such as injecting authentication headers, to fetch requests.
*/
class HttpClient {
private readonly url: URL
private readonly init: RequestInit
private readonly cache: Cache
/**
* Creates a new HttpClient.
*
* @param url required, the base url of all requests.
* @param init initializer for requests, defaults to empty.
* @param cache cache storage for requests, defaults to global.
*/
constructor(url: URL, init?: RequestInit, cache?: Cache) {
if(!url) throw new TypeError('url is a required argument')
this.url = url
this.init = init || {}
if(!this.init.headers) this.init.headers = {}
this.cache = cache || (<any> caches).default
}
/**
* Fetch a path from the origin or cache.
*
* @param path required, the path to fetch, joined by the client url.
* @param init initializer for the request, recursively merges with client initializer.
* @param cacheTtl required, number of seconds to cache the response.
* @param staleTtl required, number of seconds to serve the response stale.
*/
public async fetch(path: string, init?: RequestInit, cacheTtl?: number, staleTtl?: number): Promise<Response> {
const key = await this.cacheKey(path, init)
if(cacheTtl < 0 && staleTtl < 0) {
return this.fetchOrigin(path, init)
}
var response = await this.cache.match(key, {ignoreMethod: true})
if(!response) {
response = await this.fetchOrigin(path, init)
response.headers.set('Cache-control', this.cacheHeader(cacheTtl, staleTtl))
await this.cache.put(key, response.clone())
}
return response
}
/**
* Fetch a path directly from the origin.
*
* @param path required, the path to fetch, joined by the client url.
* @param init initializer for the request, recursively merges with client initializer.
*/
private async fetchOrigin(path: string, init?: RequestInit): Promise<Response> {
path = new URL(path, this.url).toString()
init = this.initMerge(init)
var response = await fetch(path, init)
// FIXME: access sometimes redirects to a 200 login page when client credentials are invalid.
if(response.redirected && new URL(response.url).hostname.endsWith('cloudflareaccess.com')) {
return new Response('client credentials rejected by cloudflare access', response)
}
return new Response(response.body, response)
}
/**
* Creates a new RequestInit for requests.
*
* @param init the initializer to merge into the client initializer.
*/
private initMerge(init?: RequestInit): RequestInit {
init = Object.assign({headers: {}}, init || {})
for(var kv of Object.entries(this.init.headers)) {
init.headers[kv[0]] = [1]
}
return Object.assign(init, this.init)
}
/**
* Creates a cache key for a Request.
*
* @param path required, the resource path of the request.
* @param init the initializer for the request, defaults to empty.
*/
private async cacheKey(path: string, init?: RequestInit): Promise<Request> {
path = new URL(path, this.url).toString()
init = this.initMerge(init)
if(init.method != 'POST') return new Request(path, init)
const hash = await sha256(init.body)
return new Request(`${path}/_/${hash}`, {method: 'GET', headers: init.headers})
}
/**
* Creates a Cache-control header for a Response.
*
* @param cacheTtl required, number of seconds to cache the response.
* @param staleTtl required, number of seconds to serve the response stale.
*/
private cacheHeader(cacheTtl?: number, staleTtl?: number): string {
var cache = 'public'
if(cacheTtl < 0 && staleTtl < 0) cache = 'private no-store no-cache'
if(cacheTtl >= 0) cache += `, max-age=${cacheTtl}`
if(staleTtl >= 0) cache += `, stale-while-revalidate=${staleTtl}`
return cache
}
}
/**
* Generate a SHA-256 hash of any object.
*
* @param object the object to generate a hash.
*/
async function sha256(object: any): Promise<string> {
const buffer = new TextEncoder().encode(JSON.stringify(object))
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)
const hashArray = Array.from(new Uint8Array(hashBuffer))
return hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('')
} | the_stack |
import { readBin, getBinUseNull, getBinNumElements, writeBin, writeBinHeader, readDataAsType } from './io';
import { isPositiveInteger, typeOfTypedArray, isNonNegativeInteger, nullValForType, isArray, dataSizeForType } from './utils';
import { Vector3, Vector2 } from 'three';
import { Type, TypedArray } from './types';
import { closeSync, openSync } from 'fs';
const tempArray: number[] = [];
const GROW_INCREMENT = 1000000;
/**
* Typed array that can grow
*/
export default class MutableTypedArray {
private useNull: Readonly<boolean>;
private nullVal?: Readonly<number>;
numElementsPerIndex: Readonly<number>;
type: Readonly<Type>;
private data: TypedArray;
private length: number;
static initFromFile(path: string, filename: string) {
const file = openSync(`${path}${filename}.bin`, 'r');
const useNull = getBinUseNull(path, filename, file);
const numElementsPerIndex = getBinNumElements(path, filename, file);
const data = readBin(path, filename, file);
closeSync(file);
return new MutableTypedArray(data, useNull, numElementsPerIndex);
}
/**
* @constructor
* @param {TypedArray} data initial data.
* @param {boolean} useNull flag telling if this data contains nulls
* @param {number} numElementsPerIndex number of elements that should be grouped together
* @param {number} length number of indices in data (only used in clone() operations)
*/
constructor(data: TypedArray, useNull: boolean, numElementsPerIndex = 1, length = data.length / numElementsPerIndex) {
// Check input params.
if (!isPositiveInteger(numElementsPerIndex)) {
throw new Error('numElementsPerVox for MutableTypedArray must be a positive integer.');
}
// Store input params.
this.numElementsPerIndex = numElementsPerIndex;
this.type = typeOfTypedArray(data);
this.useNull = useNull;
this.data = data;//.slice(0, length * numElementsPerIndex);// Make copy of data.
// Init other params.
this.length = length;
if (!isNonNegativeInteger(this.length)) {
throw new Error('Input data length of MutableTypedArray is not integer multiple of numElementsPerIndex.');
}
if (this.useNull) {
this.nullVal = nullValForType(this.type);
}
}
/**
* Clears all data (to either 0 or null).
*/
clear() {
let clearVal = 0;
if (this.useNull) {
clearVal = this.nullVal!;
}
for (let i = 0; i < this.data.length; i++) {
this.data[i] = clearVal;
}
}
/**
* Returns 'length' of array.
* Note that each entry of a MutableTypedArray may contain multiple values.
* @returns {number} number of entries in MutableTypedArray
*/
getLength() {
return this.length;
}
/**
* Returns value(s) or null at index.
* @param {number} index lookup index
* @returns {number|array|null} value(s) stored at given index or null
*/
get(index: number): number | null;
get(index: number, array: number[]): number[] | null
get(index: number, array?: number[]) {
// Check input param.
if (index < 0 || index >= this.length) {
throw new Error(`Index out of bounds: ${index}`);
}
// Get first element stored at index.
const firstVal = this.data[this.numElementsPerIndex * index];
if (this.useNull && firstVal === this.nullVal) return null;
// If only one element per index, return a single number.
if (this.numElementsPerIndex === 1) {
return firstVal;
}
// Otherwise, return an array of values or null.
if (array === undefined) {
throw new Error('No array passed to MutableTypedArray.get().');
}
// Else, add vals to array until a null value or numElementsPerIndex is reached.
array.length = 0;
array.push(firstVal);
for (let i = 1; i < this.numElementsPerIndex; i++) {
const val = this.data[(this.numElementsPerIndex * index) + i];
if (this.useNull && val === this.nullVal) return array;
array.push(val);
}
return array;
}
/**
* Returns Vector3 at index.
* @param {number} index lookup index
* @returns {Vector3} Vector3 stored at given index or null
*/
getVector3(index: number, v: Vector3) {
// Check input param.
if (this.numElementsPerIndex !== 3) {
throw new Error('Cannot call getVector3() on MutableTypedArray with numElementsPerIndex != 3.');
}
// Call standard get function.
const data = this.get(index, tempArray);
if (data === null) return null;
// Return array as Vector3.
if (data.length !== 3) {
throw new Error(`Voxel at index ${index} contains less than three elements.`);
}
return v.set(data[0], data[1], data[2]);
// if (v) return v.set(data[0], data[1], data[2]);
// return new Vector3(data[0], data[1], data[2]);
}
/**
* Returns Vector2 at index.
* @param {number} index lookup index
* @returns {Vector2} Vector2 stored at given index or null
*/
getVector2(index: number, v: Vector2) {
// Check input param.
if (this.numElementsPerIndex !== 2) {
throw new Error('Cannot call getVector2() on MutableTypedArray with numElementsPerIndex != 2.');
}
// Call standard get function.
const data = this.get(index, tempArray);
if (data === null) return null;
// Return array as Vector2.
if (data.length !== 2) {
throw new Error(`Voxel at index ${index} contains less than two elements.`);
}
return v.set(data[0], data[1]);
// if (v) return v.set(data[0], data[1]);
// return new Vector2(data[0], data[1]);
}
/**
* Sets data at index.
* @param {number} index lookup index
* @param {number|array|null} val value(s) or null
*/
set(index: number, val: number | number[] | null) {
if (index < 0 || index >= this.length) {
throw new Error(`Index out of bounds: ${index}`);
}
if (val === null) {
if (this.useNull) {
for (let i = 0; i < this.numElementsPerIndex; i++) {
this.data[index * this.numElementsPerIndex + i] = this.nullVal as number;
}
} else {
throw new Error('Null value not valid for this MutableTypedArray.');
}
} else if (this.numElementsPerIndex === 1) {
if (isArray(val)){
throw new Error('MutableTypedArray.set() val must be number or null for numElementsPerIndex === 1.');
}
this.data[index] = val as number;
} else {
if (!isArray(val)){
throw new Error('MutableTypedArray.set() val must be array or null for numElementsPerIndex > 1.');
}
val = val as number[];
if (this.numElementsPerIndex !== val.length && !this.useNull) {
// If not using nulls, numElementsPerIndex must equal val.length.
throw new Error('MutableTypedArray.set() val param must be same length as numElementsPerIndex.');
}
if (this.numElementsPerIndex < val.length) {
throw new Error('MutableTypedArray.set() val param is too long.');
}
for (let i = 0; i < this.numElementsPerIndex; i++) {
// Fill this._data with val[i] or null.
this.data[this.numElementsPerIndex * index + i] = (i < val.length) ? val[i] : this.nullVal as number;
}
}
}
/**
* Sets Vector3 at index.
* @param {number} index lookup index
* @param {Vector3|null} val Vector3 or null
*/
setVector3(index: number, val: Vector3 | null) {
// Check input params.
if (this.numElementsPerIndex !== 3) {
throw new Error('Must be exactly three elements per index to call setVector3().');
}
if (index < 0 || index >= this.length) {
throw new Error(`Out of bound index ${index} for MutableTypedArray of length ${this.length}.`);
}
// Set data.
if (val === null) {
if (this.useNull) {
this.data[3 * index] = this.nullVal as number;
this.data[3 * index + 1] = this.nullVal as number;
this.data[3 * index + 2] = this.nullVal as number;
} else throw new Error('Null value not valid for this MutableTypedArray.');
} else {
this.data[3 * index] = val.x;
this.data[3 * index + 1] = val.y;
this.data[3 * index + 2] = val.z;
}
}
/**
* Sets Vector2 at index.
* @param {number} index lookup index
* @param {Vector2|null} val Vector3 or null
*/
setVector2(index: number, val: Vector2) {
// Check input params.
if (this.numElementsPerIndex !== 2) {
throw new Error('Must be exactly two elements per index to call setVector2().');
}
if (index < 0 || index >= this.length) {
throw new Error(`Out of bound index ${index} for MutableTypedArray of length ${this.length}.`);
}
// Set data.
if (val === null) {
if (this.useNull) {
this.data[2 * index] = this.nullVal as number;
this.data[2 * index + 1] = this.nullVal as number;
} else throw new Error('Null value not valid for this MutableTypedArray.');
} else {
this.data[2 * index] = val.x;
this.data[2 * index + 1] = val.y;
}
}
// /**
// * Sets large window of data at once.
// * @param {TypedArray} data new data
// * @param {number} [startIndex] starting index to set data
// * @param {number} [numIndices] number of indices to set
// */
// setData(data, startIndex, numIndices) {
// // Set default params.
// const start = startIndex || 0;
// const length = numIndices || data.length / this.numElementsPerIndex;
// // Check input params.
// if (length * this.numElementsPerIndex > data.length) {
// throw new Error('setData() error, data array is not long enough for numIndices.');
// }
// // Set data.
// // this._data.set(data, start * this.numElementsPerIndex);
// const num = length * this.numElementsPerIndex;
// for (let i = 0; i < num; i++) {
// this._data[(start * this.numElementsPerIndex) + i] = data[i];
// }
// }
private growDataArray() {
if (this.data.length === this.length * this.numElementsPerIndex) {
// Grow data array by adding a million extra entries.
const length = this.numElementsPerIndex * (this.length + GROW_INCREMENT);
// Check that we haven't exceed a max.
// TODO: handle these cases.
if (length * dataSizeForType(this.type) > (2 ** 31) - 1) {
throw new Error('Mutable typed array is too long.');
}
let newData;
switch (this.type) {
case 'uint8':
newData = new Uint8Array(length);
break;
case 'int16':
newData = new Int16Array(length);
break;
case 'uint16':
newData = new Uint16Array(length);
break;
case 'int32':
newData = new Int32Array(length);
break;
case 'uint32':
newData = new Uint32Array(length);
break;
case 'float32':
newData = new Float32Array(length);
break;
default:
throw new Error(`Unknown type ${this.type}.`);
}
// Populate new array with old data.
for (let i = 0, length = this.length * this.numElementsPerIndex; i < length; i++) {
newData[i] = this.data[i];
}
// Fill the rest will null, if needed.
if (this.useNull) {
for (let i = this.length * this.numElementsPerIndex, length = newData.length; i < length; i++) {
newData[i] = this.nullVal!;
}
}
// Set this._data.
this.data = newData;
}
}
/**
* Pushes data to end of array.
* @param {number|array|null} val value(s) or null to push.
*/
push(val: number[] | number | null) {
this.growDataArray();
// Get index.
const index = this.length;
// Increment length.
this.length += 1;
// Set value(s) or null with regular setter.
this.set(index, val);
}
/**
* Pushes Vector3 to end of array.
* @param {Vector3|null} vec Vector3 or null
*/
pushVector3(val: Vector3 | null) {
this.growDataArray();
// Get index.
const index = this.length;
// Increment length.
this.length += 1;
// Set value(s) or null with regular setter.
this.setVector3(index, val);
}
/**
* Pushes Vector2 to end of array.
* @param {Vector2|null} vec Vector3 or null
*/
pushVector2(val: Vector2) {
this.growDataArray();
// Get index.
const index = this.length;
// Increment length.
this.length += 1;
// Set value(s) or null with regular setter.
this.setVector2(index, val);
}
forEach(callback: (val: number | number[] | null, index: number) => void) {
for (let i = 0, length = this.length; i < length; i++) {
callback(this.get(i), i);
}
}
forEachVector3(callback: (val: Vector3 | null, index: number) => void) {
const v = new Vector3();
for (let i = 0, length = this.length; i < length; i++) {
callback(this.getVector3(i, v), i);
}
}
forEachVector2(callback: (val: Vector2 | null, index: number) => void) {
const v = new Vector2();
for (let i = 0, length = this.length; i < length; i++) {
callback(this.getVector2(i, v), i);
}
}
// /**
// * Returns a copy of a portion of the this._data array.
// * @param {number} [startIndex=0] starting index to copy from
// * @param {number} [endIndex=this.length] ending index to copy from
// */
// getData(startIndex, endIndex) {
// // Set default params, if necessary.
// const start = startIndex || 0;
// const end = endIndex || this.length;
// // Check params.
// if (!utils.isNonNegativeInteger(start)) {
// throw new Error(`Invalid startIndex: ${start}`);
// }
// if (start >= end) {
// throw new Error('startIndex must be strictly less than endIndex.');
// }
// if (!utils.isInteger(end) || end > this.length) {
// throw new Error(`Invalid endIndex: ${end}`);
// }
// return this._data.slice(start * this.numElementsPerIndex, end * this.numElementsPerIndex);
// }
/**
* Returns this.data, this is called externally to avoid unecessary copies.
*/
getData() {
return this.data;
}
/**
* Saves data as a .vol file.
* @param {string} path path for save
* @param {*} filename filename for save
*/
saveAsBin(path: string, filename: string) {
writeBin(path, filename, this.data, this.numElementsPerIndex, this.useNull, this.getLength() * this.numElementsPerIndex);
}
/**
* Opens a new file and saves header.
* @param {string} path path for save
* @param {*} filename filename for save
* @returns {integer} file pointer
*/
saveHeader(path: string, filename: string) {
return writeBinHeader(path, filename, this.data, this.numElementsPerIndex, this.useNull, this.getLength() * this.numElementsPerIndex);
}
/**
* Clears all memory for garbage collection.
*/
destroy() {
// Clear properties for garbage collection.
// delete this.data;
}
/**
* Returns a deep copy of current instance.
* @returns {MutableTypedArray} clone of current instance
*/
clone() {
return new MutableTypedArray(this.data, this.useNull, this.numElementsPerIndex, this.length);
}
// TODO: remove this.
convertToVector2() {
if (this.numElementsPerIndex !== 3 || this.type !== 'float32') {
throw new Error('bad Vector 3 array');
}
const data = new Float32Array(this.length * 2);
for (let i = 0; i < this.length; i++) {
data[2 * i] = this.data[3 * i];
data[2 * i + 1] = this.data[3 * i + 2];
}
return new MutableTypedArray(data, this.useNull, 2);
}
// TODO: remove this.
static initFromVol(path: string, filename: string, type: Type, useNull: boolean, numElementsPerIndex: number) {
const fullPath = `${path}${filename}.vol`;
const file = openSync(fullPath, 'r');
const data = readDataAsType(fullPath, type, 0, undefined, file);
closeSync(file);
return new MutableTypedArray(data, useNull, numElementsPerIndex);
}
} | the_stack |
/**
* @module annieUI
*/
namespace annieUI {
import Sprite=annie.Sprite;
import Shape=annie.Shape;
import Event=annie.Event;
import MouseEvent=annie.MouseEvent;
import Point=annie.Point;
/**
* 电子杂志组件
* @class annieUI.FlipBook
* @public
* @extends annie.Sprite
* @since 1.0.0
*/
export class FlipBook extends Sprite {
//Events
/**
* annieUI.FlipBook组件翻页开始事件
* @event annie.Event.ON_FLIP_START
* @since 1.1.0
*/
/**
* annieUI.FlipBook组件翻页结束事件
* @event annie.Event.ON_FLIP_STOP
* @since 1.1.0
*/
/**
* 电子杂志组件类
* @class annieUI.FlipBook
* @public
* @extends annie.Sprite
* @since 1.0.3
*/
//可设置或可调用接口,页数以单页数计算~
/**
* 总页数
* @property totalPage
* @type {number}
*/
public totalPage: number = 0;
/**
* 当前页数
* @property
* @type {number}
* @since 1.0.3
*/
public currPage: number = 0;
/**
* 翻页速度,0-1之间,值越小,速度越快
* @property
* @since 1.1.3
* @type {number}
*/
public speed:number=0.4;
private bW: number;
private bH: number;
private toPage: number;
private crossGap: number;
private layer1Arr: any;
private layer0Arr: any;
private state: String = "stop";
private timerArg0: number = 0;
private timerArg1: number = 0;
private px: number = 0;
private py: number = 0;
private toPosArr: any;
private myPosArr: any;
private rPage0: Sprite = new Sprite();
private rPage1: Sprite = new Sprite();
private pageMC: Sprite = new Sprite();
private leftPage: Sprite = null;
private rightPage: Sprite = null;
private rMask0: Shape = new Shape();
private rMask1: Shape = new Shape();
private shadow0: Shape = new Shape();
private shadow1: Shape = new Shape();
private sMask0: Shape = new Shape();
private sMask1: Shape = new Shape();
private p1: Point;
private p2: Point;
private p3: Point;
private p4: Point;
private limitP1: Point;
private limitP2: Point;
private pages: any = [];
private stageMP: Point = new Point();
private getPageCallback:Function;
/**
* 指定是否能够翻页动作
* @property canFlip
* @since 1.0.3
* @type {boolean}
*/
public canFlip:boolean=true;
/**
* 初始化电子杂志
* @method FlipBook
* @param {number} width 单页宽
* @param {number} height 单页高
* @param {number} pageCount 总页数,一般为偶数
* @param {Function} getPageCallBack,通过此回调获取指定页的内容的显示对象
* @since 1.0.3
*/
public constructor(width: number, height: number, pageCount: any,getPageCallBack:Function) {
super();
let s = this;
s._instanceType = "annieUI.FlipBook";
s.getPageCallback=getPageCallBack;
s.bW = width;
s.bH = height;
s.totalPage = pageCount;
s.currPage = s.toPage = 0;
s.crossGap = Math.sqrt(s.bW * s.bW + s.bH * s.bH);
s.p1 = new Point(0, 0);
s.p2 = new Point(0, s.bH);
s.p3 = new Point(s.bW + s.bW, 0);
s.p4 = new Point(s.bW + s.bW, s.bH);
s.limitP1 = new Point(s.bW, 0);
s.limitP2 = new Point(s.bW, s.bH);
s.toPosArr = [s.p3, s.p4, s.p1, s.p2];
s.myPosArr = [s.p1, s.p2, s.p3, s.p4];
s.rPage0.mouseEnable=false;
s.rPage1.mouseEnable=false;
s.shadow0.mouseEnable=false;
s.shadow1.mouseEnable=false;
s.setShadowMask(s.shadow0, s.bW * 1.5, s.bH * 3);
s.setShadowMask(s.shadow1, s.bW * 1.5, s.bH * 3);
s.rPage1.mask=s.rMask1;
s.shadow1.mask=s.rMask1;
s.shadow0.mask=s.rMask0;
s.rPage0.mask=s.rMask0;
s.shadow0.visible = false;
s.shadow1.visible = false;
s.addChild(s.pageMC);
s.addChild(s.rPage0);
s.addChild(s.shadow0);
s.addChild(s.rPage1);
s.addChild(s.shadow1);
s.addChild(s.rMask0);
s.addChild(s.rMask1);
s.setPage(s.currPage);
s.md=s.onMouseDown.bind(s);
s.mu=s.onMouseUp.bind(s);
s.mm=s.onMouseMove.bind(s);
let em=s.onEnterFrame.bind(s);
s.addEventListener(annie.Event.ADD_TO_STAGE,function(e:annie.Event){
s.stage.addEventListener(MouseEvent.MOUSE_DOWN, s.md);
s.stage.addEventListener(MouseEvent.MOUSE_UP, s.mu);
s.stage.addEventListener(MouseEvent.MOUSE_MOVE, s.mm);
s.addEventListener(Event.ENTER_FRAME, em);
});
s.addEventListener(annie.Event.REMOVE_TO_STAGE,function(e:annie.Event){
s.stage.removeEventListener(MouseEvent.MOUSE_DOWN, s.md);
s.stage.removeEventListener(MouseEvent.MOUSE_UP, s.mu);
s.stage.removeEventListener(MouseEvent.MOUSE_MOVE, s.mm);
s.removeEventListener(Event.ENTER_FRAME, em);
})
}
private md:Function;
private mu:Function;
private mm:Function;
private drawPage(num: number, movePoint: Point): void {
let s = this;
let actionPoint: Point;
let bArr: any;
if (num == 1) {
movePoint = s.checkLimit(movePoint, s.limitP1, s.bW);
movePoint = s.checkLimit(movePoint, s.limitP2, s.crossGap);
bArr = s.getBookArr(movePoint, s.p1, s.p2);
actionPoint = bArr[1];
s.getLayerArr(movePoint, actionPoint, s.p1, s.p2, s.limitP1, s.limitP2);
s.getShadow(s.shadow0,s.p1, movePoint, 0.5);
s.getShadow(s.shadow1,s.p1, movePoint, 0.45);
s.rPage1.rotation = s.angle(movePoint, actionPoint) + 90;
s.rPage1.x = bArr[3].x;
s.rPage1.y = bArr[3].y;
s.rPage0.x = s.p1.x;
s.rPage0.y = s.p1.y;
} else if (num == 2) {
movePoint = s.checkLimit(movePoint, s.limitP2, s.bW);
movePoint = s.checkLimit(movePoint, s.limitP1, s.crossGap);
bArr = s.getBookArr(movePoint, s.p2, s.p1);
actionPoint = bArr[1];
s.getLayerArr(movePoint, actionPoint, s.p2, s.p1, s.limitP2, s.limitP1);
s.getShadow(s.shadow0, s.p2, movePoint, 0.5);
s.getShadow(s.shadow1, s.p2, movePoint, 0.45);
s.rPage1.rotation = s.angle(movePoint, actionPoint) - 90;
s.rPage1.x = bArr[2].x;
s.rPage1.y = bArr[2].y;
s.rPage0.x = s.p1.x;
s.rPage0.y = s.p1.y;
} else if (num == 3){
movePoint = s.checkLimit(movePoint, s.limitP1, s.bW);
movePoint = s.checkLimit(movePoint, s.limitP2, s.crossGap);
bArr = s.getBookArr(movePoint, s.p3, s.p4);
actionPoint = bArr[1];
s.getLayerArr(movePoint, actionPoint, s.p3, s.p4, s.limitP1, s.limitP2);
s.getShadow(s.shadow0, s.p3, movePoint, 0.5);
s.getShadow(s.shadow1, s.p3, movePoint, 0.4);
s.rPage1.rotation = s.angle(movePoint, actionPoint) + 90;
s.rPage1.x = movePoint.x;
s.rPage1.y = movePoint.y;
s.rPage0.x = s.limitP1.x;
s.rPage0.y = s.limitP1.y;
} else {
movePoint = s.checkLimit(movePoint, s.limitP2, s.bW);
movePoint = s.checkLimit(movePoint, s.limitP1, s.crossGap);
bArr = s.getBookArr(movePoint, s.p4, s.p3);
actionPoint = bArr[1];
s.getLayerArr(movePoint, actionPoint, s.p4, s.p3, s.limitP2, s.limitP1);
s.getShadow(s.shadow0, s.p4, movePoint, 0.5);
s.getShadow(s.shadow1, s.p4, movePoint, 0.4);
s.rPage1.rotation = s.angle(movePoint, actionPoint) - 90;
s.rPage1.x = actionPoint.x;
s.rPage1.y = actionPoint.y;
s.rPage0.x = s.limitP1.x;
s.rPage0.y = s.limitP1.y;
}
s.getShape(s.rMask1, s.layer1Arr);
s.getShape(s.rMask0, s.layer0Arr);
}
private checkLimit(point: Point, limitPoint: Point, limitGap: number): Point {
let s = this;
let gap: number = Math.abs(s.pos(limitPoint, point));
let angle: number = s.angle(limitPoint, point);
if (gap > limitGap) {
let tmp1: number = limitGap * Math.sin((angle / 180) * Math.PI);
let tmp2: number = limitGap * Math.cos((angle / 180) * Math.PI);
point = new Point(limitPoint.x - tmp2, limitPoint.y - tmp1);
}
return point;
}
private getPage(index:number):any{
let s=this;
if(!s.pages[index-1]){
s.pages[index-1]=s.getPageCallback(index);
}
return s.pages[index-1];
}
private getBookArr(point: Point, actionPoint1: Point, actionPoint2: Point): any {
let s = this;
let bArr: any = [];
let gap1: number = Math.abs(s.pos(actionPoint1, point) * 0.5);
let angle1: number = s.angle(actionPoint1, point);
let tmp1_2: number = gap1 / Math.cos((angle1 / 180) * Math.PI);
let tmpPoint1: Point = new Point(actionPoint1.x - tmp1_2, actionPoint1.y);
let angle2: number = s.angle(point, tmpPoint1) - s.angle(point, actionPoint2);
let gap2: number = s.pos(point, actionPoint2);
let tmp2_1: number = gap2 * Math.sin((angle2 / 180) * Math.PI);
let tmp2_2: number = gap2 * Math.cos((angle2 / 180) * Math.PI);
let tmpPoint2: Point = new Point(actionPoint1.x + tmp2_2, actionPoint1.y + tmp2_1);
let angle3: number = s.angle(tmpPoint1, point);
let tmp3_1: number = s.bW * Math.sin((angle3 / 180) * Math.PI);
let tmp3_2: number = s.bW * Math.cos((angle3 / 180) * Math.PI);
let tmpPoint3: Point = new Point(tmpPoint2.x + tmp3_2, tmpPoint2.y + tmp3_1);
let tmpPoint4: Point = new Point(point.x + tmp3_2, point.y + tmp3_1);
bArr.push(point);
bArr.push(tmpPoint2);
bArr.push(tmpPoint3);
bArr.push(tmpPoint4);
return bArr;
}
private getLayerArr(point1: Point, point2: Point, actionPoint1: Point, actionPoint2: Point, limitPoint1: Point, limitPoint2: Point): void {
let s = this;
let arrLayer1: any = [];
let arrLayer2: any = [];
let gap1: number = Math.abs(s.pos(actionPoint1, point1) * 0.5);
let angle1: number = s.angle(actionPoint1, point1);
let tmp1_1: number = gap1 / Math.sin((angle1 / 180) * Math.PI);
let tmp1_2: number = gap1 / Math.cos((angle1 / 180) * Math.PI);
let tmpPoint1: Point = new Point(actionPoint1.x - tmp1_2, actionPoint1.y);
let tmpPoint2: Point = new Point(actionPoint1.x, actionPoint1.y - tmp1_1);
let tmpPoint3: Point = point2;
let gap2: number = Math.abs(s.pos(point1, actionPoint2));
if (gap2 > s.bH) {
arrLayer1.push(tmpPoint3);
let pos: number = Math.abs(s.pos(tmpPoint3, actionPoint2) * 0.5);
let tmp3: number = pos / Math.cos((angle1 / 180) * Math.PI);
tmpPoint2 = new Point(actionPoint2.x - tmp3, actionPoint2.y);
} else {
arrLayer2.push(actionPoint2);
}
arrLayer1.push(tmpPoint2);
arrLayer1.push(tmpPoint1);
arrLayer1.push(point1);
s.layer1Arr = arrLayer1;
arrLayer2.push(limitPoint2);
arrLayer2.push(limitPoint1);
arrLayer2.push(tmpPoint1);
arrLayer2.push(tmpPoint2);
s.layer0Arr = arrLayer2;
}
private getShape(shape: Shape, pointArr: any): void {
let num: number = pointArr.length;
shape.clear();
shape.beginFill("#000");
shape.moveTo(pointArr[0].x, pointArr[0].y);
for (let i: number = 1; i < num; i++) {
shape.lineTo(pointArr[i].x, pointArr[i].y);
}
shape.endFill();
}
private setShadowMask(shape:Shape,g_width: number, g_height: number):void{
shape.beginLinearGradientFill([-g_width * 0.5, 4, g_width * 0.5, 4],[[0,"#000000",0],[1,"#000000",0.6]]);
shape.drawRect(-g_width * 0.5, -g_height * 0.5, g_width * 0.5, g_height);
shape.endFill();
shape.beginLinearGradientFill( [-g_width * 0.5, 4, g_width * 0.5, 4],[[1,"#000000",0], [0,"#000000",0.6]]);
shape.drawRect(0, -g_height * 0.5, g_width * 0.5, g_height);
shape.endFill();
}
private getShadow(shape: Shape, point1: Point, point2: Point, arg: number): void {
let myScale: number;
let myAlpha: number;
let s = this;
shape.visible = true;
shape.x = point2.x + (point1.x - point2.x) * arg;
shape.y = point2.y + (point1.y - point2.y) * arg;
shape.rotation = s.angle(point1, point2);
myScale = Math.abs(point1.x - point2.x) * 0.5 / s.bW;
myAlpha = 1 - myScale * myScale;
shape.scaleX = myScale + 0.1;
shape.alpha = myAlpha + 0.1;
}
private setPage(pageNum: number): void {
let s = this;
if (pageNum >0 && pageNum <= s.totalPage) {
s.leftPage = s.getPage(pageNum);
s.leftPage.x = s.leftPage.y = 0;
s.pageMC.addChild(s.leftPage);
}
if((pageNum + 1) > 0 && (pageNum + 1) < s.totalPage) {
s.rightPage = s.getPage(pageNum+1);
s.rightPage.x = s.bW;
s.rightPage.y = 0;
s.pageMC.addChild(s.rightPage);
}
}
private onMouseDown(e: MouseEvent): void {
let s = this;
if (!s.canFlip||s.state != "stop") {
return;
}
s.stageMP.x = e.clientX;
s.stageMP.y = e.clientY;
let p: Point = s.globalToLocal(s.stageMP);
s.stageMP=p;
s.timerArg0 = s.checkArea(p);
s.timerArg0 = s.timerArg0 < 0 ? -s.timerArg0 : s.timerArg0;
if (s.timerArg0 > 0) {
if((s.timerArg0<3&&s.currPage>0)||(s.timerArg0>2&&s.currPage<=s.totalPage-2)){
s.state = "start";
s.flushPage();
s.dispatchEvent("onFlipStart");
}
}
}
private onMouseUp(e: MouseEvent): void {
let s = this;
if (s.state == "start") {
s.stageMP.x = e.clientX;
s.stageMP.y = e.clientY;
let p: Point = s.globalToLocal(s.stageMP);
s.timerArg1 = s.checkArea(p);
s.state = "auto";
s.stageMP=p;
}
}
private onMouseMove(e: MouseEvent): void {
let s = this;
if (s.state == "start") {
s.stageMP.x = e.clientX;
s.stageMP.y = e.clientY;
let p: Point = s.globalToLocal(s.stageMP);
s.stageMP=p;
}
}
private checkArea(point: Point): number {
let s = this;
let tmpN: number;
let minX: number = 0;
let maxX: number = s.bW + s.bW;
let minY: number = 0;
let maxY: number = s.bH;
let areaNum: number = 50;
if (point.x > minX && point.x <= maxX * 0.5) {
tmpN = (point.y > minY && point.y <= (maxY * 0.5)) ? 1 : (point.y > (maxY * 0.5) && point.y < maxY) ? 2 : 0;
if (point.x <= (minX + areaNum)) {
tmpN = (point.y > minY && point.y <= (minY + areaNum)) ? -1 : (point.y > (maxY - areaNum) && point.y < maxY) ? -2 : tmpN;
}
return tmpN;
} else if (point.x > (maxX * 0.5) && point.x < maxX) {
tmpN = (point.y > minY && point.y <= (maxY * 0.5)) ? 3 : (point.y > (maxY * 0.5) && point.y < maxY) ? 4 : 0;
if (point.x >= (maxX - areaNum)) {
tmpN = (point.y > minY && point.y <= (minY + areaNum)) ? -3 : (point.y > (maxY - areaNum) && point.y < maxY) ? -4 : tmpN;
}
return tmpN;
}
return 0;
}
/**
* 跳到指定的页数
* @method flipTo
* @param {number} index 跳到指定的页数
* @since 1.0.3
*/
public flipTo(index: number): void {
let n: number;
let s = this;
index = index % 2 == 1 ? index - 1 : index;
n = index - s.currPage;
if (s.state == "stop" && index >= 0 && index <= s.totalPage && n != 0) {
s.timerArg0 = n < 0 ? 1 : 3;
s.timerArg1 = -1;
s.toPage = index > s.totalPage ? s.totalPage : index;
s.state = "auto";
s.flushPage();
}
}
/**
* @method nextPage
* @public
* @since 1.1.1
*/
public nextPage():void{
this.flipTo(this.currPage+2);
}
/**
* @method prevPage
* @public
* @since 1.1.1
*/
public prevPage():void{
this.flipTo(this.currPage-1);
}
/**
* @method startPage
* @public
* @since 1.1.1
*/
public startPage():void{
this.flipTo(0);
}
/**
* @method endPage
* @public
* @since 1.1.1
*/
public endPage():void{
this.flipTo(this.totalPage);
}
private flushPage(): void {
let s = this;
let page0: number;
let page1: number;
let myPos: Point = s.myPosArr[s.timerArg0 - 1];
let p: Sprite = null;
if (s.timerArg0 == 1 || s.timerArg0 == 2) {
s.toPage = s.toPage == s.currPage ? s.currPage - 2 : s.toPage;
page0 = s.currPage;
page1 = s.toPage + 1;
this.pageMC.removeChild(s.leftPage);
if (s.toPage> 0) {
p = s.getPage(s.currPage - 2);
p.x = 0;
s.leftPage = p;
s.pageMC.addChild(p);
}
} else if (s.timerArg0 == 3 || s.timerArg0 == 4) {
s.toPage = s.toPage == s.currPage ? s.currPage + 2 : s.toPage;
page0 = s.currPage + 1;
page1 = s.toPage;
s.pageMC.removeChild(s.rightPage);
if (s.toPage+1 < s.totalPage) {
p = s.getPage(s.currPage +3);
p.x = s.bW;
s.rightPage = p;
s.pageMC.addChild(p);
}
}
s.px = myPos.x;
s.py = myPos.y;
if(page0>0&&page0<=s.totalPage) {
p=s.getPage(page0);
p.x = 0;
p.y = 0;
s.rPage0.addChild(p);
}
if(page1>0&&page1<=s.totalPage) {
p=s.getPage(page1);
p.x = 0;
p.y = 0;
s.rPage1.addChild(p);
}
}
private onEnterFrame(e: Event): void {
let s = this;
let toPos: Point = s.toPosArr[s.timerArg0 - 1];
let myPos: Point = s.myPosArr[s.timerArg0 - 1];
let tox: number;
let toy: number;
let toFlag: number;
let tmpX: number;
let tmpY: number;
let u: number;
if (s.state == "start") {
u = s.speed;
let p:Point =s.stageMP;
s.px += (p.x - s.px) * u >> 0;
s.py += (p.y - s.py) * u >> 0;
let np=new Point(s.px,s.py);
s.drawPage(s.timerArg0,np);
} else if (s.state == "auto") {
if (Math.abs(toPos.x - s.px) > s.bW * 1.5 && s.timerArg1 > 0) {
//不处于点翻区域并且翻页不过中线时
tox = myPos.x;
toy = myPos.y;
toFlag = 0;
} else {
tox = toPos.x;
toy = toPos.y;
toFlag = 1;
}
tmpX = (tox - s.px) >> 0;
tmpY = (toy - s.py) >> 0;
if (s.timerArg1 < 0) {
u = s.speed*0.7;
s.py = s.arc(s.bW, tmpX, toPos.y);
} else {
u = s.speed;
s.py = tmpY * u + s.py;
}
s.px = tmpX * u + s.px;
s.drawPage(s.timerArg0, new Point(s.px, s.py));
if(tmpX == 0 && tmpY == 0){
s.rPage0.removeAllChildren();
s.rPage1.removeAllChildren();
s.shadow0.visible = false;
s.shadow1.visible = false;
s.toPage = toFlag == 0 ? s.currPage : s.toPage;
s.currPage = s.toPage;
s.pageMC.removeAllChildren();
s.setPage(s.currPage);
s.state = "stop";
s.dispatchEvent("onFlipStop");
}
}
}
private arc(argR: number, argN1: number, argN2: number): number {
let arg: number = argR * 2;
let r: number = argR * argR + arg * arg;
let a: number = Math.abs(argN1) - argR;
return argN2 - (Math.sqrt(r - a * a) - arg);
}
private angle(target1: Point, target2: Point): number {
let tmpX: number = target1.x - target2.x;
let tmpY: number = target1.y - target2.y;
let tmp_angle: number = Math.atan2(tmpY, tmpX) * 180 / Math.PI;
return tmp_angle < 0 ? tmp_angle + 360 : tmp_angle;
}
private pos(target1: Point, target2: Point): number {
let tmpX: number = target1.x - target2.x;
let tmpY: number = target1.y - target2.y;
let tmpS: number = Math.sqrt(tmpX * tmpX + tmpY * tmpY);
return target1.x > target2.x ? tmpS : -tmpS;
}
public destroy(): void {
let s=this;
s.md=null;
s.mu=null;
s.mm=null;
s.layer0Arr=null;
s.layer1Arr=null;
s.toPosArr=null;
s.myPosArr=null;
s.rPage0=null;
s.rMask0=null;
s.rMask1=null;
s.sMask0=null;
s.sMask1=null;
s.leftPage=null;
s.rightPage=null;
s.pageMC=null;
s.rightPage=null;
s.shadow0=null;
s.shadow1=null;
s.p1=null;
s.p2 = null;
s.p3=null;
s.p4=null;
s.limitP1=null;
s.limitP2=null;
s.pages=null;
s.stageMP=null;
s.getPageCallback=null;
super.destroy();
}
}
} | the_stack |
import { ActiveWorkspace } from "../workspace/model/ActiveWorkspace";
import { decoder, useWorkspaces, WorkspaceFile } from "../workspace/WorkspacesContext";
import { useRoutes } from "../navigation/Hooks";
import * as React from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { join } from "path";
import { Dropdown } from "@patternfly/react-core/dist/js/components/Dropdown";
import { Link } from "react-router-dom";
import { Flex, FlexItem } from "@patternfly/react-core/dist/js/layouts/Flex";
import { FileLabel } from "../workspace/components/FileLabel";
import { Toggle } from "@patternfly/react-core/dist/js/components/Dropdown/Toggle";
import { Title } from "@patternfly/react-core/dist/js/components/Title";
import { Popover } from "@patternfly/react-core/dist/js/components/Popover";
import { Tooltip } from "@patternfly/react-core/dist/js/components/Tooltip";
import { Text, TextContent, TextVariants } from "@patternfly/react-core/dist/js/components/Text";
import { TextInput } from "@patternfly/react-core/dist/js/components/TextInput";
import { Divider } from "@patternfly/react-core/dist/js/components/Divider";
import {
DrilldownMenu,
Menu,
MenuContent,
MenuGroup,
MenuInput,
MenuItem,
MenuList,
} from "@patternfly/react-core/dist/js/components/Menu";
import { CaretDownIcon } from "@patternfly/react-icons/dist/js/icons/caret-down-icon";
import { FolderIcon } from "@patternfly/react-icons/dist/js/icons/folder-icon";
import { ImageIcon } from "@patternfly/react-icons/dist/js/icons/image-icon";
import { ThLargeIcon } from "@patternfly/react-icons/dist/js/icons/th-large-icon";
import { ListIcon } from "@patternfly/react-icons/dist/js/icons/list-icon";
import { useWorkspaceDescriptorsPromise } from "../workspace/hooks/WorkspacesHooks";
import { PromiseStateWrapper, useCombinedPromiseState, usePromiseState } from "../workspace/hooks/PromiseState";
import { Split, SplitItem } from "@patternfly/react-core/dist/js/layouts/Split";
import { Button } from "@patternfly/react-core/dist/js/components/Button";
import { WorkspaceDescriptor } from "../workspace/model/WorkspaceDescriptor";
import { useWorkspacesFilesPromise } from "../workspace/hooks/WorkspacesFiles";
import { Skeleton } from "@patternfly/react-core/dist/js/components/Skeleton";
import { Card, CardBody, CardHeader, CardHeaderMain, CardTitle } from "@patternfly/react-core/dist/js/components/Card";
import { Gallery } from "@patternfly/react-core/dist/js/layouts/Gallery";
import { useCancelableEffect } from "../reactExt/Hooks";
import { useHistory } from "react-router";
import { Bullseye } from "@patternfly/react-core/dist/js/layouts/Bullseye";
import { EmptyState, EmptyStateIcon } from "@patternfly/react-core/dist/js/components/EmptyState";
import { CubesIcon } from "@patternfly/react-icons/dist/js/icons/cubes-icon";
import { ArrowRightIcon } from "@patternfly/react-icons/dist/js/icons/arrow-right-icon";
import { ArrowLeftIcon } from "@patternfly/react-icons/dist/js/icons/arrow-left-icon";
import { WorkspaceLabel } from "../workspace/components/WorkspaceLabel";
import { useEditorEnvelopeLocator } from "../envelopeLocator/EditorEnvelopeLocatorContext";
const ROOT_MENU_ID = "rootMenu";
enum FilesDropdownMode {
LIST_MODELS,
LIST_MODELS_AND_OTHERS,
CAROUSEL,
}
const MIN_FILE_SWITCHER_PANEL_WIDTH_IN_PX = 400;
export function FileSwitcher(props: { workspace: ActiveWorkspace; workspaceFile: WorkspaceFile }) {
const workspaces = useWorkspaces();
const workspaceFileNameRef = useRef<HTMLInputElement>(null);
const [newFileNameValid, setNewFileNameValid] = useState<boolean>(true);
const [filesDropdownMode, setFilesDropdownMode] = useState(FilesDropdownMode.LIST_MODELS);
const resetWorkspaceFileName = useCallback(() => {
if (workspaceFileNameRef.current) {
workspaceFileNameRef.current.value = props.workspaceFile.nameWithoutExtension;
setNewFileNameValid(true);
}
}, [props.workspaceFile]);
const checkNewFileName = useCallback(
async (newFileNameWithoutExtension: string) => {
const trimmedNewFileNameWithoutExtension = newFileNameWithoutExtension.trim();
if (trimmedNewFileNameWithoutExtension === props.workspaceFile.nameWithoutExtension) {
setNewFileNameValid(true);
return;
}
const newRelativePath = join(
props.workspaceFile.relativeDirPath,
`${trimmedNewFileNameWithoutExtension}.${props.workspaceFile.extension}`
);
const hasConflictingFileName = await workspaces.existsFile({
fs: await workspaces.fsService.getWorkspaceFs(props.workspaceFile.workspaceId),
workspaceId: props.workspaceFile.workspaceId,
relativePath: newRelativePath,
});
const hasForbiddenCharacters = !/^[\w\d_.\-()\s]+$/gi.test(newFileNameWithoutExtension);
setNewFileNameValid(!hasConflictingFileName && !hasForbiddenCharacters);
},
[props.workspaceFile, workspaces]
);
const renameWorkspaceFile = useCallback(
async (newFileName: string | undefined) => {
const trimmedNewFileName = newFileName?.trim();
if (!trimmedNewFileName || !newFileNameValid) {
resetWorkspaceFileName();
return;
}
if (trimmedNewFileName === props.workspaceFile.nameWithoutExtension) {
resetWorkspaceFileName();
return;
}
await workspaces.renameFile({
fs: await workspaces.fsService.getWorkspaceFs(props.workspaceFile.workspaceId),
file: props.workspaceFile,
newFileNameWithoutExtension: trimmedNewFileName.trim(),
});
},
[props.workspaceFile, workspaces, resetWorkspaceFileName, newFileNameValid]
);
const handleWorkspaceFileNameKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
e.stopPropagation();
if (newFileNameValid && e.keyCode === 13 /* Enter */) {
e.currentTarget.blur();
setPopoverVisible(false);
} else if (e.keyCode === 27 /* ESC */) {
resetWorkspaceFileName();
e.currentTarget.blur();
setPopoverVisible(false);
}
},
[newFileNameValid, resetWorkspaceFileName]
);
useEffect(resetWorkspaceFileName, [resetWorkspaceFileName]);
const [isFilesDropdownOpen, setFilesDropdownOpen] = useState(false);
const [isPopoverVisible, setPopoverVisible] = useState(false);
const [menuDrilledIn, setMenuDrilledIn] = useState<string[]>([]);
const [drilldownPath, setDrilldownPath] = useState<string[]>([]);
const [menuHeights, setMenuHeights] = useState<{ [key: string]: number }>({});
const [activeMenu, setActiveMenu] = useState(ROOT_MENU_ID);
useEffect(() => {
setMenuHeights({});
}, [props.workspace, filesDropdownMode, activeMenu]);
useEffect(() => {
setFilesDropdownMode((prev) =>
prev === FilesDropdownMode.LIST_MODELS_AND_OTHERS ? FilesDropdownMode.LIST_MODELS : prev
);
}, [activeMenu]);
useEffect(() => {
if (isFilesDropdownOpen) {
return;
}
setMenuDrilledIn([ROOT_MENU_ID]);
setDrilldownPath([props.workspace.descriptor.workspaceId]);
setActiveMenu(`dd${props.workspace.descriptor.workspaceId}`);
}, [isFilesDropdownOpen, props.workspace.descriptor.workspaceId]);
const drillIn = useCallback((fromMenuId, toMenuId, pathId) => {
setMenuDrilledIn((prev) => [...prev, fromMenuId]);
setDrilldownPath((prev) => [...prev, pathId]);
setActiveMenu(toMenuId);
}, []);
const drillOut = useCallback((toMenuId) => {
setMenuDrilledIn((prev) => prev.slice(0, prev.length - 1));
setDrilldownPath((prev) => prev.slice(0, prev.length - 1));
setActiveMenu(toMenuId);
}, []);
const setHeight = useCallback((menuId: string, height: number) => {
// do not try to simplify this ternary's condition as some heights are 0, resulting in an infinite loop.
setMenuHeights((prev) => (prev[menuId] === height ? prev : { ...prev, [menuId]: height }));
}, []);
const workspacesMenuItems = useMemo(() => {
if (activeMenu === `dd${props.workspace.descriptor.workspaceId}`) {
return <></>;
}
return (
<WorkspacesMenuItems
activeMenu={activeMenu}
currentWorkspace={props.workspace}
onSelectFile={() => setFilesDropdownOpen(false)}
filesDropdownMode={filesDropdownMode}
setFilesDropdownMode={setFilesDropdownMode}
/>
);
}, [activeMenu, filesDropdownMode, props.workspace]);
return (
<>
<Flex alignItems={{ default: "alignItemsCenter" }} flexWrap={{ default: "nowrap" }}>
<FlexItem style={{ display: "flex", alignItems: "baseline" }}>
<Dropdown
style={{ position: "relative" }}
position={"left"}
className={"kogito-tooling--masthead-hoverable"}
isOpen={isFilesDropdownOpen}
isPlain={true}
toggle={
<Toggle
onToggle={(isOpen) =>
setFilesDropdownOpen((prev) => {
if (workspaceFileNameRef.current === document.activeElement) {
return prev;
} else {
return isOpen;
}
})
}
id={"editor-page-masthead-files-dropdown-toggle"}
>
<Flex flexWrap={{ default: "nowrap" }} alignItems={{ default: "alignItemsCenter" }}>
<FlexItem />
<FlexItem>
<b>
<FileLabel extension={props.workspaceFile.extension} />
</b>
</FlexItem>
<Popover
hasAutoWidth={true}
distance={15}
showClose={false}
shouldClose={() => setPopoverVisible(false)}
hideOnOutsideClick={true}
enableFlip={false}
withFocusTrap={false}
bodyContent={
<>
<FolderIcon />
{props.workspaceFile.relativeDirPath.split("/").join(" > ")}
</>
}
isVisible={isPopoverVisible}
position={"bottom-start"}
>
<FlexItem>
<div
data-testid={"toolbar-title"}
className={`kogito--editor__toolbar-name-container ${newFileNameValid ? "" : "invalid"}`}
>
<Title
aria-label={"EmbeddedEditorFile name"}
headingLevel={"h3"}
size={"2xl"}
style={{ fontWeight: "bold" }}
>
{props.workspaceFile.nameWithoutExtension}
</Title>
<Tooltip
content={
<Text component={TextVariants.p}>
{`A file already exists at this location or this name has invalid characters. Please choose a different name.`}
</Text>
}
position={"bottom"}
trigger={"manual"}
isVisible={!newFileNameValid}
className="kogito--editor__light-tooltip"
>
<TextInput
style={{ fontWeight: "bold" }}
onClick={(e) => {
e.stopPropagation();
//FIXME: Change this when it is possible to move a file.
if (props.workspaceFile.relativePath !== props.workspaceFile.name) {
setPopoverVisible(true);
}
}}
onKeyDown={handleWorkspaceFileNameKeyDown}
onChange={checkNewFileName}
ref={workspaceFileNameRef}
type={"text"}
aria-label={"Edit file name"}
className={"kogito--editor__toolbar-title"}
onBlur={(e) => renameWorkspaceFile(e.target.value)}
/>
</Tooltip>
</div>
</FlexItem>
</Popover>
<FlexItem>
<CaretDownIcon />
</FlexItem>
</Flex>
</Toggle>
}
>
<Menu
style={{
boxShadow: "none",
minWidth:
activeMenu === ROOT_MENU_ID
? "400px"
: filesDropdownMode === FilesDropdownMode.CAROUSEL
? "calc(100vw - 16px)"
: filesDropdownMode === FilesDropdownMode.LIST_MODELS
? `${MIN_FILE_SWITCHER_PANEL_WIDTH_IN_PX}px`
: filesDropdownMode === FilesDropdownMode.LIST_MODELS_AND_OTHERS
? `${MIN_FILE_SWITCHER_PANEL_WIDTH_IN_PX * 2}px`
: "",
}}
id={ROOT_MENU_ID}
containsDrilldown={true}
drilldownItemPath={drilldownPath}
drilledInMenus={menuDrilledIn}
activeMenu={activeMenu}
onDrillIn={drillIn}
onDrillOut={drillOut}
onGetMenuHeight={setHeight}
>
<MenuContent
maxMenuHeight={"800px"}
menuHeight={activeMenu === ROOT_MENU_ID ? undefined : `${menuHeights[activeMenu]}px`}
style={{ overflow: "hidden" }}
>
<MenuList>
<MenuItem
itemId={props.workspace.descriptor.workspaceId}
description={"Current"}
direction={"down"}
drilldownMenu={
<DrilldownMenu id={`dd${props.workspace.descriptor.workspaceId}`}>
<FilesMenuItems
shouldFocusOnSearch={activeMenu === `dd${props.workspace.descriptor.workspaceId}`}
filesDropdownMode={filesDropdownMode}
setFilesDropdownMode={setFilesDropdownMode}
workspaceDescriptor={props.workspace.descriptor}
workspaceFiles={props.workspace.files}
currentWorkspaceFile={props.workspaceFile}
onSelectFile={() => setFilesDropdownOpen(false)}
/>
</DrilldownMenu>
}
>
{props.workspace.descriptor.name}
</MenuItem>
{workspacesMenuItems}
</MenuList>
</MenuContent>
</Menu>
</Dropdown>
</FlexItem>
</Flex>
</>
);
}
export function WorkspacesMenuItems(props: {
activeMenu: string;
currentWorkspace: ActiveWorkspace;
onSelectFile: () => void;
filesDropdownMode: FilesDropdownMode;
setFilesDropdownMode: React.Dispatch<React.SetStateAction<FilesDropdownMode>>;
}) {
const editorEnvelopeLocator = useEditorEnvelopeLocator();
const workspaceDescriptorsPromise = useWorkspaceDescriptorsPromise();
const workspaceFilesPromise = useWorkspacesFilesPromise(workspaceDescriptorsPromise.data);
const combined = useCombinedPromiseState({
workspaceDescriptors: workspaceDescriptorsPromise,
workspaceFiles: workspaceFilesPromise,
});
return (
<>
<Divider component={"li"} />
<PromiseStateWrapper
promise={combined}
pending={
<div style={{ padding: "8px" }}>
<Skeleton />
<br />
<Skeleton width={"80%"} />
<br />
<Skeleton />
<br />
<Skeleton width={"80%"} />
<br />
<Skeleton />
<br />
<Skeleton width={"80%"} />
</div>
}
resolved={({ workspaceDescriptors, workspaceFiles }) => (
<>
{workspaceDescriptors
.sort((a, b) => (new Date(a.lastUpdatedDateISO) < new Date(b.lastUpdatedDateISO) ? 1 : -1))
.filter((descriptor) => descriptor.workspaceId !== props.currentWorkspace.descriptor.workspaceId)
.map((descriptor) => (
<React.Fragment key={descriptor.workspaceId}>
{workspaceFiles.get(descriptor.workspaceId)!.length === 1 && (
<FileMenuItem
file={workspaceFiles.get(descriptor.workspaceId)![0]}
onSelectFile={props.onSelectFile}
/>
)}
{workspaceFiles.get(descriptor.workspaceId)!.length > 1 && (
<MenuItem
itemId={descriptor.workspaceId}
description={`${workspaceFiles.get(descriptor.workspaceId)!.length} files, ${
workspaceFiles
.get(descriptor.workspaceId)!
.filter((f) => [...editorEnvelopeLocator.mapping.keys()].includes(f.extension)).length
} models`}
direction={"down"}
drilldownMenu={
<DrilldownMenu id={`dd${descriptor.workspaceId}`}>
<FilesMenuItems
shouldFocusOnSearch={props.activeMenu === `dd${descriptor.workspaceId}`}
filesDropdownMode={props.filesDropdownMode}
setFilesDropdownMode={props.setFilesDropdownMode}
workspaceDescriptor={descriptor}
workspaceFiles={workspaceFiles.get(descriptor.workspaceId) ?? []}
onSelectFile={props.onSelectFile}
/>
</DrilldownMenu>
}
>
<FolderIcon />
{descriptor.name}
<WorkspaceLabel descriptor={descriptor} />
</MenuItem>
)}
</React.Fragment>
))}
</>
)}
/>
</>
);
}
export function FileSvg(props: { workspaceFile: WorkspaceFile }) {
const workspaces = useWorkspaces();
const imgRef = useRef<HTMLImageElement>(null);
const [svg, setSvg] = usePromiseState<string>();
useCancelableEffect(
useCallback(
({ canceled }) => {
Promise.resolve()
.then(async () => workspaces.svgService.getSvg(props.workspaceFile))
.then(async (file) => {
if (canceled.get()) {
return;
}
if (file) {
setSvg({ data: decoder.decode(await file.getFileContents()) });
} else {
setSvg({ error: `Can't find SVG for '${props.workspaceFile.relativePath}'` });
}
});
},
[props.workspaceFile, workspaces, setSvg]
)
);
useEffect(() => {
if (svg.data) {
const blob = new Blob([svg.data], { type: "image/svg+xml" });
const url = URL.createObjectURL(blob);
imgRef.current!.addEventListener("load", () => URL.revokeObjectURL(url), { once: true });
imgRef.current!.src = url;
}
}, [svg]);
return (
<>
<PromiseStateWrapper
pending={<Skeleton height={"180px"} style={{ margin: "10px" }} />}
rejected={() => (
<div style={{ height: "180px", margin: "10px", borderRadius: "5px", backgroundColor: "#EEE" }}>
<Bullseye>
<ImageIcon size={"xl"} color={"gray"} />
</Bullseye>
</div>
)}
promise={svg}
resolved={() => (
// for some reason, the CardBody adds an extra 6px after the image is loaded. 200 - 6 = 194px.
<img style={{ height: "194px" }} ref={imgRef} alt={"SVG for " + props.workspaceFile.relativePath} />
)}
/>
</>
);
}
export function SearchableFilesMenuGroup(props: {
maxHeight: string;
shouldFocusOnSearch: boolean;
filesDropdownMode: FilesDropdownMode;
label: string;
allFiles: WorkspaceFile[];
children: (args: { filteredFiles: WorkspaceFile[] }) => React.ReactNode;
}) {
const [search, setSearch] = useState("");
const searchInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (props.shouldFocusOnSearch) {
setTimeout(() => {
searchInputRef.current?.focus();
}, 500);
}
}, [props.shouldFocusOnSearch, props.filesDropdownMode]);
const filteredFiles = useMemo(
() => props.allFiles.filter((file) => file.name.toLowerCase().includes(search.toLowerCase())),
[props.allFiles, search]
);
return (
<MenuGroup label={props.label}>
<MenuInput>
<TextInput
ref={searchInputRef}
value={search}
aria-label={"Other files menu items"}
iconVariant={"search"}
type={"search"}
onChange={(value) => setSearch(value)}
/>
</MenuInput>
{filteredFiles.length === 0 && search && (
<Bullseye>
<EmptyState>
<EmptyStateIcon icon={CubesIcon} />
<Title headingLevel="h4" size="lg">
{`No files match '${search}'.`}
</Title>
</EmptyState>
</Bullseye>
)}
<div style={{ maxHeight: props.maxHeight, overflowY: "auto" }}>
{filteredFiles.length > 0 && props.children({ filteredFiles })}
</div>
</MenuGroup>
);
}
export function FilesMenuItems(props: {
workspaceDescriptor: WorkspaceDescriptor;
workspaceFiles: WorkspaceFile[];
currentWorkspaceFile?: WorkspaceFile;
onSelectFile: () => void;
filesDropdownMode: FilesDropdownMode;
setFilesDropdownMode: React.Dispatch<React.SetStateAction<FilesDropdownMode>>;
shouldFocusOnSearch: boolean;
}) {
const history = useHistory();
const routes = useRoutes();
const editorEnvelopeLocator = useEditorEnvelopeLocator();
const sortedAndFilteredFiles = useMemo(
() =>
props.workspaceFiles
.sort((a, b) => a.relativePath.localeCompare(b.relativePath))
.filter((file) => file.relativePath !== props.currentWorkspaceFile?.relativePath),
[props.workspaceFiles, props.currentWorkspaceFile]
);
const models = useMemo(
() => sortedAndFilteredFiles.filter((file) => [...editorEnvelopeLocator.mapping.keys()].includes(file.extension)),
[editorEnvelopeLocator, sortedAndFilteredFiles]
);
const otherFiles = useMemo(
() => sortedAndFilteredFiles.filter((file) => ![...editorEnvelopeLocator.mapping.keys()].includes(file.extension)),
[editorEnvelopeLocator, sortedAndFilteredFiles]
);
return (
<>
<Split>
<SplitItem isFilled={true}>
<MenuItem direction="up" itemId={props.workspaceDescriptor.workspaceId}>
All
</MenuItem>
</SplitItem>
{/* FIXME: Uncomment when KOGITO-6181 is fixed */}
{/*<SplitItem>*/}
{/* <FilesDropdownModeIcons*/}
{/* filesDropdownMode={props.filesDropdownMode}*/}
{/* setFilesDropdownMode={props.setFilesDropdownMode}*/}
{/* />*/}
{/* */}
{/*</SplitItem>*/}
</Split>
<Divider component={"li"} />
<Split>
{(props.filesDropdownMode === FilesDropdownMode.LIST_MODELS ||
props.filesDropdownMode === FilesDropdownMode.LIST_MODELS_AND_OTHERS) && (
<SplitItem isFilled={true} style={{ minWidth: `${MIN_FILE_SWITCHER_PANEL_WIDTH_IN_PX}px` }}>
<>
<SearchableFilesMenuGroup
maxHeight={"500px"}
filesDropdownMode={props.filesDropdownMode}
shouldFocusOnSearch={props.shouldFocusOnSearch}
label={`Models in '${props.workspaceDescriptor.name}'`}
allFiles={models}
>
{({ filteredFiles }) =>
filteredFiles.map((file) => (
<FileMenuItem key={file.relativePath} file={file} onSelectFile={props.onSelectFile} />
))
}
</SearchableFilesMenuGroup>
{otherFiles.length > 0 && (
<>
<Divider component={"li"} />
<MenuGroup>
<MenuList>
<MenuItem
onClick={(e) => {
e.stopPropagation();
props.setFilesDropdownMode((prev) =>
prev === FilesDropdownMode.LIST_MODELS
? FilesDropdownMode.LIST_MODELS_AND_OTHERS
: FilesDropdownMode.LIST_MODELS
);
}}
>
{props.filesDropdownMode === FilesDropdownMode.LIST_MODELS
? "View other files"
: "Hide other files"}
{props.filesDropdownMode === FilesDropdownMode.LIST_MODELS ? (
<ArrowRightIcon />
) : (
<ArrowLeftIcon />
)}
</MenuItem>
</MenuList>
</MenuGroup>
</>
)}
</>
</SplitItem>
)}
{props.filesDropdownMode === FilesDropdownMode.LIST_MODELS_AND_OTHERS && (
<SplitItem isFilled={true} style={{ minWidth: `${MIN_FILE_SWITCHER_PANEL_WIDTH_IN_PX}px` }}>
<SearchableFilesMenuGroup
maxHeight={"500px"}
filesDropdownMode={props.filesDropdownMode}
shouldFocusOnSearch={props.shouldFocusOnSearch}
label={`Other files in '${props.workspaceDescriptor.name}'`}
allFiles={otherFiles}
>
{({ filteredFiles }) =>
filteredFiles.map((file) => (
<MenuItem key={file.relativePath}>
<FileName file={file} />
</MenuItem>
))
}
</SearchableFilesMenuGroup>
</SplitItem>
)}
{props.filesDropdownMode === FilesDropdownMode.CAROUSEL && (
<SplitItem isFilled={true}>
<SearchableFilesMenuGroup
maxHeight={"500px"}
filesDropdownMode={props.filesDropdownMode}
shouldFocusOnSearch={props.shouldFocusOnSearch}
label={`Models in '${props.workspaceDescriptor.name}'`}
allFiles={models}
>
{({ filteredFiles }) => (
<Gallery hasGutter={true} style={{ padding: "8px" }}>
{filteredFiles.map((file) => (
<Card
key={file.relativePath}
isSelectable={true}
isRounded={true}
isCompact={true}
isHoverable={true}
isFullHeight={true}
onClick={() => {
history.push({
pathname: routes.workspaceWithFilePath.path({
workspaceId: file.workspaceId,
fileRelativePath: file.relativePathWithoutExtension,
extension: file.extension,
}),
});
props.onSelectFile();
}}
>
<CardHeader>
<CardHeaderMain>
<CardTitle>
<Flex flexWrap={{ default: "nowrap" }}>
<FlexItem>
<TextContent>
<Text component={TextVariants.h4}>{file.nameWithoutExtension}</Text>
</TextContent>
</FlexItem>
<FlexItem>
<FileLabel extension={file.extension} />
</FlexItem>
</Flex>
</CardTitle>
</CardHeaderMain>
</CardHeader>
<CardBody style={{ padding: 0 }}>
<FileSvg workspaceFile={file} />
</CardBody>
</Card>
))}
</Gallery>
)}
</SearchableFilesMenuGroup>
</SplitItem>
)}
</Split>
</>
);
}
export function FileName(props: { file: WorkspaceFile }) {
return (
<>
<Flex flexWrap={{ default: "nowrap" }}>
<FlexItem>{props.file.nameWithoutExtension}</FlexItem>
<FlexItem>
<FileLabel extension={props.file.extension} />
</FlexItem>
</Flex>
<div className={"pf-c-dropdown__menu-item-description"}>
{props.file.relativeDirPath.split("/").join(" > ")}
</div>
</>
);
}
export function FileMenuItem(props: { file: WorkspaceFile; onSelectFile: () => void }) {
const routes = useRoutes();
return (
<MenuItem onClick={props.onSelectFile}>
<Link
to={routes.workspaceWithFilePath.path({
workspaceId: props.file.workspaceId,
fileRelativePath: props.file.relativePathWithoutExtension,
extension: props.file.extension,
})}
>
<FileName file={props.file} />
</Link>
</MenuItem>
);
}
export function FilesDropdownModeIcons(props: {
filesDropdownMode: FilesDropdownMode;
setFilesDropdownMode: React.Dispatch<React.SetStateAction<FilesDropdownMode>>;
}) {
return (
<>
{props.filesDropdownMode === FilesDropdownMode.CAROUSEL && (
<Button
className={"kogito-tooling--masthead-hoverable"}
variant="plain"
aria-label="Switch to list view"
onClick={(e) => {
e.stopPropagation();
props.setFilesDropdownMode(FilesDropdownMode.LIST_MODELS);
}}
>
<ListIcon />
</Button>
)}
{(props.filesDropdownMode === FilesDropdownMode.LIST_MODELS ||
props.filesDropdownMode === FilesDropdownMode.LIST_MODELS_AND_OTHERS) && (
<Button
className={"kogito-tooling--masthead-hoverable"}
variant="plain"
aria-label="Switch to carousel view"
onClick={(e) => {
e.stopPropagation();
props.setFilesDropdownMode(FilesDropdownMode.CAROUSEL);
}}
>
<ThLargeIcon />
</Button>
)}
</>
);
} | the_stack |
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import requester from "~/core/fetch";
import EventEmitter from "~/core/EventEmitter";
import {
AnyObjectType,
AppDataElementsTypes,
ArgumentsBoolean,
ArgumentsNumber,
ArgumentsString,
} from "~/types/appData";
import { Modules } from "~/types/modules";
import Wrapper from "../Wrapper";
import useGame from "~/hooks/useGame";
import useStyles from "./Roulette.useStyles";
import s from "./Roulette.module.less";
import * as mock from "./mockData";
import classNames from "classnames";
import Backgrounp from "./Backgroup";
import config from "./Roulette.config";
import useLifeCycle from "~/hooks/useLifeCycle";
import { useSelector } from "react-redux";
import { RootState } from "~/redux/store";
import { debounce } from "lodash";
import { setClass } from "./helper";
import { getArgumentsItem } from "~/core/getArgumentsTypeDataFromDataSource";
import message from "~/components/Message";
import Record from "./Record";
export interface RouletteProps extends AppDataElementsTypes {
id: string;
eventEmitter: EventEmitter;
}
export interface PrizeTypes {
prizeId: number; // 奖品id
prizeType: number; // 奖品类型 0 未中奖, 1 实物, 2 虚拟
receiveType?: number; // 领取方式 1:默认;2:填写地址;3:链接类;4:虚拟卡
prizeAlias?: string; // 奖品别名
prizeName: string; // 奖品名称
awardMsg?: string; // 中奖提示信息
gameImg?: string; // 游戏图片
prizeImg: string; // 奖品图片
memo?: string; // 奖品备注
}
const Roulette: Modules<RouletteProps> = (props) => {
const { moduleId, style } = props;
const { currentEditorStylePath } = useSelector(
(state: RootState) => state.controller
);
const [prizes, setPrizes] = useState<PrizeTypes[]>([]);
const [phoneAndRCardId, setPhoneAndRCardId] = useState<AnyObjectType>();
const [receiverInfo, setReceiverInfo] = useState<AnyObjectType>(
mock.receiverInfo
);
const [successmodalParams, setSuccessmodalParams] = useState<AnyObjectType>(
{}
);
// 禁用抽奖
const checked = useRef<{
/**禁用信息 */
message?: string;
/**是否禁用 */
enabled: boolean;
}>({ enabled: true });
// 确定数据是否准备就是,没有准备好时会启用模拟数据
const prizesIsReadyRef = useRef<boolean>();
// 此ref用于存储useLifeCycle组件暴露的事件
const dispatchEventRef = useRef<{
mount: () => void;
unmount: () => void;
onStart: () => void;
onEnd: () => void;
onCancel: () => void;
onEnsure: () => void;
onShowSuccess: () => void;
onShowFailed: () => void;
onShowAddress: () => void;
}>();
// 页面api
const { api } = props;
// 皮肤设置样式
const MId = `gametarget${moduleId}`;
const userClass = useStyles(MId)(style);
// ===========================================组件Api============================================
/**
* 抽奖前置Api, 用于检查是否满足抽奖条件
* */
const apiBeforeStart = useCallback(async () => {
const apiArguments = api?.find((item) => item.apiId === "beforeStart");
// 获取抽奖结果数据, 将结果数据中转到全局数据中
if (apiArguments && apiArguments.url && apiArguments.method) {
try {
return requester(apiArguments || {});
} catch (error) {
throw error;
}
}
}, [api]);
/**
* 抽奖Api, 用于抽奖
*/
const apiStart = useCallback(async () => {
const apiArguments = api?.find((item) => item.apiId === "lottery");
// 获取抽奖结果数据, 将结果数据中转到全局数据中
if (apiArguments && apiArguments.url && apiArguments.method) {
return requester(apiArguments || {});
}
}, [api]);
/**
* 保存地址Api, 用于实物奖品保存地址信息
*/
const apiSaveAddress = useCallback(
async (data) => {
// 这里不需要api设置参数
const apiArguments = api?.find((item) => item.apiId === "saveAddress");
// 获取抽奖结果数据, 将结果数据中转到全局数据中
if (apiArguments) {
apiArguments.body = [
{ type: "object", fieldName: "addressData", data },
];
return requester(apiArguments || {});
}
// 处理收货地址
message.warning("没有设置保存地址Api, 当前不可保存!");
},
[api]
);
/**
* 检查手机验证码
* */
const checkVerificationCode = useCallback(
async (data) => {
// 这里不需要api设置参数
const apiArguments = api?.find(
(item) => item.apiId === "getVerificationCode"
);
// 获取抽奖结果数据, 将结果数据中转到全局数据中
if (apiArguments) {
apiArguments.body = [
{ type: "object", fieldName: "addressData", data },
];
return requester(apiArguments || {});
}
// 处理收货地址
message.warning("没有设置获取验证码Api!");
},
[api]
);
// ===========================================组件方法============================================
/**
* 设置奖品数据, 无数据时使用mock
*/
const setRunningPrizes = useCallback((prizes) => {
const prizesArg = getArgumentsItem(prizes) as any[];
if (Array.isArray(prizesArg) && prizesArg.length) {
setPrizes(prizesArg);
prizesIsReadyRef.current = true;
}
// 没有准备过数据会使用mock数据
if (!prizesIsReadyRef.current) {
setPrizes(mock.prizes);
}
}, []);
/**
* 设置玩家基本信息
* @param phone 设置玩家手机号码
* @param cardIdRequest 设置领取奖品时是否需要填写身份证1 隐藏,2 验证,3 为空时不验证有填写时验证,4 不验证
*/
const useConfig = useCallback(
(phone: ArgumentsString, cardIdRequest: ArgumentsNumber) => {
const argOptPhone = getArgumentsItem(phone);
const argCardIdRequest = getArgumentsItem(cardIdRequest);
setPhoneAndRCardId({
phone: argOptPhone,
cardIdRequest: argCardIdRequest,
});
},
[]
);
/**
* 设置中奖弹窗
* @param title 中奖弹窗标题
* @param animation 中奖弹窗动画
*/
const setSuccessModal = useCallback(
(title: ArgumentsString, animation: ArgumentsString) => {
setSuccessmodalParams({
title: getArgumentsItem(title),
animation: getArgumentsItem(animation),
});
},
[]
);
/**
* 检查抽奖
* @param
*/
const checkedLottery = useCallback(
(enabled: ArgumentsBoolean, message: ArgumentsString) => {
const argEnabled = getArgumentsItem(enabled) as boolean;
const argMessage = getArgumentsItem(message) as string;
checked.current = {
enabled: argEnabled,
message: argMessage,
};
},
[]
);
// ==============================================end=============================================
// hank 等待
const setDelayStart = useCallback(
() =>
new Promise((res) =>
setTimeout(() => {
dispatchEventRef.current?.onStart();
res(null);
})
),
[]
);
/**
* 开始抽奖
* */
const startLottery = useCallback(async () => {
// step1、执行前置api 用于抽奖前检查是否满足抽奖条件
await apiBeforeStart();
// step2 执行抽奖事件
await setDelayStart();
// step3、检查状态是否可以抽奖
if (!checked.current.enabled) {
console.log("没有权限,请勿抽奖!");
message.error(checked.current?.message || "暂无抽奖权限!");
throw checked.current?.message;
}
// step4、返回抽奖接口
const settedApi = (await apiStart()) as AnyObjectType;
// step5、执行结束事件,可用于重置数据
dispatchEventRef.current?.onEnd();
if (settedApi?.response?.prizeId !== undefined) {
let currentPrize = settedApi.response;
prizes.some((prize) => {
if (prize.prizeId === currentPrize.prizeId) {
currentPrize = {
...currentPrize,
...(prize || {}),
};
return true;
}
return false;
});
return currentPrize;
}
// 没有设置Api时启用mock数据
if (!settedApi) {
message.warning("活动奖品或抽奖Api未设置正确, 当前使用模拟抽奖!");
const winnerInfo = prizes[Math.floor(Math.random() * prizes.length - 1)];
return winnerInfo;
}
}, [apiBeforeStart, apiStart, checked, prizes, setDelayStart]);
const gamePrames = useMemo(
() => ({
targetId: MId,
parentId: `game${props.moduleId}`,
playerPhone: phoneAndRCardId?.phone,
successModalTitle: successmodalParams.title || "恭喜您,获得",
SuccessModalAnimation: {
form: successmodalParams.animation || "flipInY",
},
cardIdRequest: phoneAndRCardId?.cardIdRequest, // 填写收货地址时是否验证身份证: this.cardIdRequest = 1 隐藏身份证,2 验证身份证,3 身份证为空时不验证有填写时验证,4 不验证身份证
style: mock.initStyle,
start: startLottery,
saveAddress: apiSaveAddress,
receiverInfo,
checkVerificationCode, // 检查手机验证码
prizes,
onCancel: dispatchEventRef.current?.onCancel,
onEnsure: dispatchEventRef.current?.onEnsure,
onShowSuccess: () => {
setClass(`${MId}_successmodal`, userClass.successModal);
dispatchEventRef.current?.onShowSuccess();
},
onShowFailed: () => {
setClass(`${MId}_failedmodal`, userClass.failedModal);
dispatchEventRef.current?.onShowFailed();
},
onShowAddress: () => {
setClass(`${MId}_addressmodal`, userClass.addressModal);
dispatchEventRef.current?.onShowAddress();
},
}),
[
MId,
checkVerificationCode,
phoneAndRCardId?.cardIdRequest,
phoneAndRCardId?.phone,
prizes,
props.moduleId,
receiverInfo,
apiSaveAddress,
startLottery,
successmodalParams.animation,
successmodalParams.title,
userClass.addressModal,
userClass.failedModal,
userClass.successModal,
]
);
/**
* 创建游戏
*/
const [game, nodes] = useGame(gamePrames);
/**
* 设置默认实物奖品邮寄地址,用于地址填写时回填信息
* @param receiverPhone 收货电话
* @param regionName 收货姓名
* @param region 收货人省市区
* @param address 收货人详细地址
* @param idCard 人身份证id
*/
const setDefaultReceiveInfo = useCallback(
(
receiverPhone: ArgumentsString,
regionName: ArgumentsString,
region: ArgumentsString,
address: ArgumentsString,
idCard: ArgumentsString
) => {
const argReceiverPhone = getArgumentsItem(receiverPhone);
let argRegionName: any = getArgumentsItem(regionName);
let argRegion: any = getArgumentsItem(region);
const argAddress = getArgumentsItem(address);
const argIdCard = getArgumentsItem(idCard);
argRegionName = argRegionName
?.replace(/,/g, ",")
?.split(",")
?.filter(Boolean);
argRegion = argRegion?.replace(/,/g, ",")?.split(",");
const parames = {
receiverPhone: argReceiverPhone,
address: argAddress,
region: argRegion,
idCard: argIdCard,
};
if (!!argRegionName.length) {
(parames as any).regionName = argRegionName;
}
console.log(game.core.AddressModal);
game.core.AddressModal.updateParams(parames as any);
setReceiverInfo(parames);
},
[game]
);
/**
* 抽奖方法
*/
const lottery = useCallback(() => {
game?.core.lottery();
}, [game]);
/**
* 编辑弹窗样式时可视化弹窗
* 做高频编辑防抖处理
*/
const onChangeDebounce = useMemo(
() =>
debounce(() => {
if (game && currentEditorStylePath?.length) {
const path = currentEditorStylePath?.map((item) => item.value);
if (path.includes("successcontainer")) {
game.core.showSuccessModal(mock.prizes[0]);
}
if (path.includes("failedcontainer")) {
game.core.showFailedModal(mock.prizes[1]);
}
if (path.includes("addressmodalcontainer")) {
game.core.showAddressModal();
}
}
}, 1000),
[currentEditorStylePath, game]
);
const editorShow = useCallback(() => {
onChangeDebounce();
}, [onChangeDebounce]);
useEffect(() => {
editorShow();
}, [editorShow]);
// lifeCycle
const [dispatchEvent] = useLifeCycle(
moduleId,
{
mount: "初始化",
unmount: "卸载",
onStart: "抽奖",
onEnd: "抽奖结束",
onCancel: "放弃中奖/关闭弹窗",
onEnsure: "确认中奖结果",
onShowSuccess: "显示中奖",
onShowFailed: "显示未中奖",
onShowAddress: "显示地址",
},
{
setRunningPrizes,
lottery,
checkedLottery,
useConfig,
setDefaultReceiveInfo,
setSuccessModal,
},
api?.find((item) => item.apiId === "init")
);
// ref存储
dispatchEventRef.current = dispatchEvent;
const [visibleRecord, setVisibleRecord] = useState(true);
return (
<>
<Wrapper {...props}>
<div
className={classNames(s.root, s.bag, userClass.wrap)}
id={`game${props.moduleId}`}
style={{ visibility: !!prizes?.length ? "visible" : "hidden" }}
ref={nodes}
>
<div className={classNames(s.root, s.bgwrap, `${MId}_light`)}>
<Backgrounp />
</div>
</div>
<Record
id={MId}
visible={visibleRecord}
classNameGroup={{
content: userClass.recordModalContent,
close: userClass.recordModalClose,
}}
onClose={() => setVisibleRecord(false)}
/>
</Wrapper>
<div style={{ width: "200px" }} onClick={() => setVisibleRecord(true)}>
中奖记录
</div>
</>
);
};
// bind static
for (const key in config) {
if (Object.prototype.hasOwnProperty.call(config, key)) {
Roulette[key] = config[key];
}
}
export default Roulette; | the_stack |
import * as React from "react"
import styled from "../utils/styled"
import { SearchIcon, CaretDownIcon, CaretUpIcon, EnterIcon, NoIcon } from "../Icon"
import useHotkey from "../useHotkey"
import Chip from "../Chip/Chip"
import { getHighlightColor } from "../utils/constants"
export interface SearchInputProps<TCategory> {
value: string
placeholder?: string
onChange: (values: { search: string; category?: TCategory }) => void
onClear?: () => void
category?: TCategory
categories?: TCategory[]
readonly?: boolean
condensed?: boolean
}
const getIconWidth = (isCondensed: boolean) => (isCondensed ? 12 : 16)
export function SearchInput<T extends string = never>(props: SearchInputProps<T>) {
const [isOpen, setIsOpen] = React.useState(false)
const toggleOpen = React.useCallback(
(event: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
event.stopPropagation()
setIsOpen(i => !i)
},
[setIsOpen],
)
React.useEffect(() => {
if (isOpen) {
const hideOnScroll = () => setIsOpen(false)
document.addEventListener("scroll", hideOnScroll)
return () => {
document.removeEventListener("scroll", hideOnScroll)
}
}
}, [isOpen, setIsOpen])
const [activeItemIndex, setActiveItemIndex] = React.useState(0)
const [focusEl, setFocusEl] = React.useState<"clearIcon" | null>(null)
const inputRef = React.useRef<HTMLInputElement>(null)
const containerRef = React.useRef<HTMLDivElement>(null)
useHotkey(containerRef, { key: "ArrowDown" }, () => {
setIsOpen(true)
setActiveItemIndex(prev => (prev + 1) % (props.categories || []).length)
})
useHotkey(containerRef, { key: "ArrowUp" }, () =>
setActiveItemIndex(prev => {
const length = (props.categories || []).length
const previousIndex = prev - 1
return previousIndex < 0 ? length - 1 : previousIndex
}),
)
useHotkey(containerRef, { key: "Enter" }, () => {
if (focusEl === "clearIcon" && props.onClear) {
props.onClear() // Handle keyboard interaction for clear icon
return
}
if (!props.categories || !props.category) {
return
}
props.onChange({ search: props.value, category: props.categories[activeItemIndex] })
setIsOpen(false)
})
useHotkey(containerRef, { key: "Escape" }, () => {
setIsOpen(false)
if (props.category && props.categories) {
const activeCategoryIndex = props.categories.findIndex(i => i === props.category)
setActiveItemIndex(activeCategoryIndex)
}
})
if (!props.value && props.onClear && focusEl === "clearIcon") {
setFocusEl(null) // Clear focus state if the element is not on the screen
}
if (props.categories && !props.categories.includes(props.category!)) {
throw new Error("[SearchInput] `categories` and `category` props don't match!")
}
return (
<Container
ref={containerRef}
isCondensed={Boolean(props.condensed)}
hasCategory={Boolean(props.category)}
isClearable={Boolean(props.value && props.onClear)}
isOpen={isOpen}
onClick={() => {
if (inputRef.current) {
inputRef.current.focus()
}
}}
>
{isOpen && (
/**
* Why do we have two `InvisibleOverlay`?
* Because we can focus with tab in two different directions!
* So we need to trap the focus before and after our `Input`
*/
<InvisibleOverlay
onClick={e => {
e.stopPropagation()
setIsOpen(false)
}}
onFocus={() => setIsOpen(false)} /* Close dropdown if the focus is away */
tabIndex={0}
aria-hidden="true"
/>
)}
{props.readonly ? (
<ReadonlyChip columnSize={2 + (props.category ? 1 : 0) + (props.onClear ? 1 : 2)}>{props.value}</ReadonlyChip>
) : (
<>
<SearchIcon color="color.text.default" size={getIconWidth(Boolean(props.condensed))} />
{props.category && (
<CategoryDropdown onClick={toggleOpen} isCondensed={Boolean(props.condensed)}>
{props.category}
{isOpen ? <CaretUpIcon size={5} /> : <CaretDownIcon size={5} />}
</CategoryDropdown>
)}
<Input
ref={inputRef}
value={props.value}
aria-label="search"
placeholder={props.placeholder}
onChange={e => {
props.onChange({
search: e.target.value,
category: props.category!, // Force the type-safety of `category` in the public API (this will be `never` if no `categories` are provided)
})
}}
/>
</>
)}
{props.value && props.onClear && (
<ClearIcon
onClick={props.onClear}
size={props.condensed ? 16 : 18}
color="color.text.default"
onFocus={() => setFocusEl("clearIcon")}
onBlur={() => setFocusEl(null)}
/>
)}
{isOpen && props.categories && (
<DropdownContainer aria-activedescendant={`category-${props.categories[activeItemIndex]}`} role="listbox">
{props.categories.map((category, index) => (
<DropdownItem
isCondensed={Boolean(props.condensed)}
isActive={activeItemIndex === index}
aria-selected={activeItemIndex === index ? "true" : undefined}
aria-roledescription="Category"
aria-label={category}
id={`category-${category}`}
role="option"
key={category}
onClick={e => {
setIsOpen(false)
setActiveItemIndex(index)
e.stopPropagation()
props.onChange({ search: props.value, category })
}}
>
<div /* Icon spacing */ />
<CategoryDropdown highlighted isCondensed={Boolean(props.condensed)}>
{category}
<EnterIcon size={8} />
</CategoryDropdown>
{props.value}
</DropdownItem>
))}
</DropdownContainer>
)}
{isOpen && (
<InvisibleOverlay
onClick={e => {
e.stopPropagation()
setIsOpen(false)
}}
onFocus={() => setIsOpen(false)} /* Close dropdown if the focus is away */
tabIndex={0}
aria-hidden="true"
/>
)}
</Container>
)
}
const Container = styled.div<{ hasCategory: boolean; isOpen: boolean; isClearable: boolean; isCondensed: boolean }>`
display: grid;
cursor: text;
grid-template-columns: ${props => {
const iconWidth = getIconWidth(props.isCondensed)
const clearIconZone = props.isClearable ? ` ${iconWidth}px` : ""
return props.hasCategory ? `${iconWidth}px min-content auto${clearIconZone}` : `${iconWidth}px auto${clearIconZone}`
}};
border: 1px solid ${({ theme, isCondensed }) => (isCondensed ? theme.color.separators.light : "transparent")}; /* Avoid jump with hover state */
border-bottom: 1px solid ${({ theme }) => theme.color.separators.light};
grid-gap: ${({ theme, hasCategory, isCondensed }) =>
(isCondensed ? theme.space.small : theme.space.content) +
(hasCategory
? theme.space.small
: 0)}px; /* The offset is for the separator extra width (CategoryDropdown:after.width) */
padding: 0 ${({ theme, isCondensed }) => (isCondensed ? theme.space.small : theme.space.content)}px;
align-items: center;
height: ${props => (props.isCondensed ? 36 : 48)}px;
transition: ease-in-out border 0.2s;
position: relative;
:hover {
border: 1px solid ${({ theme }) => theme.color.separators.light};
}
${({ isOpen, theme }) => isOpen && `border: 1px solid ${theme.color.primary};`}
:focus-within {
border: 1px solid ${({ theme }) => theme.color.primary};
}
`
const CategoryDropdown = styled.div<{ highlighted?: boolean; isCondensed?: boolean }>`
font-size: ${({ theme }) => theme.font.size.body}px;
font-family: ${({ theme }) => theme.font.family.main};
color: ${({ theme }) => theme.color.text.default};
padding: ${({ theme, isCondensed }) => (isCondensed ? theme.space.base : theme.space.small)}px;
border-radius: ${({ theme }) => theme.borderRadius}px;
z-index: ${({ theme }) => theme.zIndex.selectOptions}; /* Ensure to be on top of the InvisibleOverlay */
min-width: 150px;
justify-content: space-between;
display: flex;
align-items: center;
position: relative;
cursor: pointer;
${({ highlighted, theme }) => (highlighted ? `background-color: ${theme.color.background.lighter};` : "")}
:hover {
background-color: ${({ theme, highlighted }) =>
highlighted ? theme.color.background.grey : getHighlightColor(theme)};
color: ${({ theme, highlighted }) => (highlighted ? theme.color.basic : theme.color.primary)};
}
:after {
content: "";
position: absolute;
width: ${({ theme }) => theme.space.small}px;
height: 24px;
border-right: 1px solid ${({ theme }) => theme.color.separators.light};
left: 100%;
}
`
const DropdownContainer = styled.div`
position: absolute;
top: 100%;
left: -1px; /* border offset hack */
width: calc(100% + 2px);
z-index: ${({ theme }) => theme.zIndex.selectOptions};
background-color: ${({ theme }) => theme.color.white};
border: 1px solid ${({ theme }) => theme.color.separators.light};
`
const DropdownItem = styled.div<{ isActive: boolean; isCondensed: boolean }>`
height: ${props => (props.isCondensed ? 36 : 48)}px;
display: grid;
align-items: center;
width: 100%;
grid-template-columns: ${props => getIconWidth(props.isCondensed)}px min-content auto;
grid-gap: ${({ theme, isCondensed }) =>
(isCondensed ? theme.space.small : theme.space.content) +
theme.space.small}px; /* Same as Container.grid-gap (with category) to be aligned */
padding: 0 ${({ theme, isCondensed }) => (isCondensed ? theme.space.small : theme.space.content)}px;
cursor: pointer !important;
${({ isActive }) => (isActive ? "" : ":hover {")}
background-color: ${({ theme }) => theme.color.background.lightest};
> div {
background-color: ${({ theme }) => theme.color.background.grey}; /* CategoryDropdown */
}
${({ isActive }) => (isActive ? "" : "}")}
`
const Input = styled.input`
width: 100%;
appearance: none;
border: 0;
font-size: ${({ theme }) => theme.font.size.body}px;
font-family: ${({ theme }) => theme.font.family.main};
color: ${({ theme }) => theme.color.text.default};
z-index: ${({ theme }) => theme.zIndex.selectOptions}; /* Ensure to be on top of the InvisibleOverlay */
:focus {
outline: none;
}
::placeholder {
color: ${({ theme }) => theme.color.text.disabled};
}
`
const InvisibleOverlay = styled.div`
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
cursor: default;
z-index: ${({ theme }) => theme.zIndex.selectOptions - 1};
`
const ClearIcon = styled(NoIcon)`
z-index: ${({ theme }) => theme.zIndex.selectOptions}; /* Ensure to be on top of the InvisibleOverlay */
`
const ReadonlyChip = styled(Chip)<{ columnSize: number }>`
grid-column: 1 / ${props => props.columnSize};
width: 100%;
`
export default SearchInput | the_stack |
import { useState } from 'react';
import { Link } from 'react-router-dom';
import styles from './PathTreeItem.module.css';
import { sidePanelVisibilityChanged } from '../../store/sidePanelVisibleSlice';
import { useAppDispatch, useAppSelector } from '../../support/hooks';
import { isOnMobile } from '../../support/util';
import { selectIsEditMode } from '../../store/isEditModeSlice';
import {
errorResultsUpdated,
selectErrorResults,
} from '../../store/errorResultsSlice';
import * as api from '../../services/api';
import { pathsUpdated } from '../../store/pathsSlice';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
faPencilAlt,
faTrashAlt,
faCheck,
faTimes,
faFolderPlus,
faFileMedical,
faCaretRight,
faCaretDown,
} from '@fortawesome/free-solid-svg-icons';
export interface PathTreeNode {
name: string;
isDir: boolean;
isFirstMathFile: boolean;
path: string;
children: PathTreeNode[];
}
export interface PathTreeItemProps {
node: PathTreeNode;
viewedPath: string;
}
export const PathTreeItem = (props: PathTreeItemProps) => {
const dispatch = useAppDispatch();
const [isExpanded, setIsExpanded] = useState(
props.node.isDir && props.node.name === 'content'
);
const isEditMode = useAppSelector(selectIsEditMode);
const allErrorResults = useAppSelector(selectErrorResults);
const [inputName, setInputName] = useState('');
const [isEditing, setIsEditing] = useState(false);
const [isDeleting, setIsDeleting] = useState(false);
const reloadAllPaths = async () => {
const allPaths = await api.getAllPaths();
dispatch(pathsUpdated(allPaths));
const res = await api.check();
dispatch(
errorResultsUpdated(
res.errors.map((err) => ({
row: err.row,
column: err.column,
message: err.message,
relativePath: err.path,
}))
)
);
};
const getAllErrorsFor = (
node: PathTreeNode,
allErrors: api.ErrorResult[]
) => {
if (node.isDir) {
let result: api.ErrorResult[] = [];
for (const child of node.children) {
result = result.concat(getAllErrorsFor(child, allErrors));
}
return result;
}
return allErrorResults.filter((err) => err.relativePath === node.path);
};
const getErrorStats = (allErrorResults: api.ErrorResult[]) => {
const thisErrorResults = getAllErrorsFor(props.node, allErrorResults);
if (!isEditMode || thisErrorResults.length === 0) {
return null;
}
const title = thisErrorResults.length === 1 ? ' error' : ' errors';
return (
<span className={styles.errorStats}>
{' '}
({thisErrorResults.length} {title})
</span>
);
};
let name = props.node.name;
const index = name.indexOf('_');
if (index >= 0) {
const prefix = name.substring(0, index);
if (prefix.length > 0 && !isNaN(+prefix)) {
// the prefix is a number so trim it
name = name.substring(index + 1);
}
}
// remove the .math extension and replace underscores with spaces
name = name.replace('.math', '').replace(/_/g, ' ');
const updateInputName = async () => {
if (!inputName || (!props.node.isDir && !inputName.endsWith('.math'))) {
alert(
`The new filename must be non-empty and end in .math but found '${inputName}'`
);
return;
}
const newPathParts = props.node.path.split('/');
newPathParts.pop(); // pop the end
newPathParts.push(inputName); // append the new name
const newPath = newPathParts.join('/');
if (props.node.isDir) {
await api.renameDir(props.node.path, newPath);
await reloadAllPaths();
} else {
await api.renameFile(props.node.path, newPath);
await reloadAllPaths();
}
};
const onSubmit = (event: any) => {
event.preventDefault();
updateInputName();
};
const getEditButtons = () => {
return isEditMode ? (
<span>
<button
className={styles.button}
style={{
display:
props.node.path !== 'content' && !isEditing && !isDeleting
? 'inline'
: 'none',
}}
onClick={() => {
setIsEditing(true);
setIsDeleting(false);
}}
>
<FontAwesomeIcon
icon={faPencilAlt}
style={{
filter: 'drop-shadow(0.45px 0.45px 0px rgba(0, 0, 0, 0.2))',
}}
/>
</button>
{props.node.isDir && !isEditing && !isDeleting ? (
<button
className={styles.button}
onClick={async () => {
const newPath = props.node.path
.split('/')
.concat('Untitled.math')
.join('/');
await api.newFile(newPath);
setIsExpanded(true);
await reloadAllPaths();
}}
>
<FontAwesomeIcon
icon={faFileMedical}
style={{
filter: 'drop-shadow(0.45px 0.45px 0px rgba(0, 0, 0, 0.2))',
}}
/>
</button>
) : null}
{props.node.isDir && !isEditing && !isDeleting ? (
<button
className={styles.button}
onClick={async () => {
const newPath = props.node.path
.split('/')
.concat('Untitled')
.join('/');
await api.newDir(newPath);
setIsExpanded(true);
await reloadAllPaths();
}}
>
<FontAwesomeIcon
icon={faFolderPlus}
style={{
filter: 'drop-shadow(0.45px 0.45px 0px rgba(0, 0, 0, 0.2))',
}}
/>
</button>
) : null}
<button
className={styles.button}
style={{ display: isEditing || isDeleting ? 'inline' : 'none' }}
onClick={async () => {
if (isEditing) {
await updateInputName();
} else {
if (props.node.isDir) {
await api.deleteDir(props.node.path);
await reloadAllPaths();
} else {
await api.deleteFile(props.node.path);
await reloadAllPaths();
}
}
setIsEditing(false);
setIsDeleting(false);
}}
>
<FontAwesomeIcon
icon={faCheck}
style={{
filter: 'drop-shadow(0.45px 0.45px 0px rgba(0, 0, 0, 0.2))',
}}
/>
</button>
<button
className={styles.button}
style={{ display: isEditing || isDeleting ? 'inline' : 'none' }}
onClick={() => {
setIsEditing(false);
setIsDeleting(false);
}}
>
<FontAwesomeIcon
icon={faTimes}
style={{
filter: 'drop-shadow(0.45px 0.45px 0px rgba(0, 0, 0, 0.2))',
}}
/>
</button>
<button
className={styles.button}
style={{
display:
props.node.path !== 'content' && !isEditing && !isDeleting
? 'inline'
: 'none',
}}
onClick={() => {
setIsDeleting(true);
setIsEditing(false);
}}
>
<FontAwesomeIcon
icon={faTrashAlt}
style={{
filter: 'drop-shadow(0.45px 0.45px 0px rgba(0, 0, 0, 0.2))',
}}
/>
</button>
</span>
) : null;
};
if (props.node.isDir) {
return (
<span
className={styles.sidePanelItem}
style={{
width: isEditMode ? 'max-content' : '100%',
maxWidth: isEditMode ? 'max-content' : '100%',
}}
>
<li
className={styles.mathlinguaListDirItem}
onClick={() => setIsExpanded(!isExpanded)}
>
{isExpanded ? (
<button className={styles.triangle}>
<FontAwesomeIcon
icon={faCaretDown}
style={{
filter: 'drop-shadow(0.45px 0.45px 0px rgba(0, 0, 0, 0.2))',
}}
/>
</button>
) : (
<button className={styles.triangle}>
<FontAwesomeIcon
icon={faCaretRight}
style={{
filter: 'drop-shadow(0.45px 0.45px 0px rgba(0, 0, 0, 0.2))',
}}
/>
</button>
)}
{isEditing ? (
<form onSubmit={onSubmit}>
<input
className={styles.input}
type="text"
placeholder={props.node.name}
onChange={(event) => setInputName(event.target.value)}
></input>
{getEditButtons()}
</form>
) : (
<span>
{name}
{getErrorStats(allErrorResults)}
</span>
)}
{!isEditing ? getEditButtons() : null}
</li>
{isExpanded ? (
<ul>
{props.node.children.map((child) => (
<PathTreeItem
key={child.name}
node={child}
viewedPath={props.viewedPath}
/>
))}
</ul>
) : null}
</span>
);
}
return (
<span
className={styles.sidePanelItem}
style={{
width: isEditMode ? 'max-content' : '100%',
maxWidth: isEditMode ? 'max-content' : '100%',
}}
>
<li className={styles.mathlinguaListFileItem}>
{isEditing ? (
<form onSubmit={onSubmit}>
<input
className={styles.input}
type="text"
placeholder={props.node.name}
onChange={(event) => setInputName(event.target.value)}
></input>
{getEditButtons()}
</form>
) : (
<Link
to={`/${props.node.path}`}
key={props.node.name}
className={
props.viewedPath === props.node.path ||
(props.viewedPath === '' && props.node.isFirstMathFile)
? `${styles.link} ${styles.selected}`
: styles.link
}
onClick={() => {
if (isOnMobile()) {
dispatch(sidePanelVisibilityChanged(false));
}
}}
>
{name}
{getErrorStats(allErrorResults)}
</Link>
)}
{!isEditing ? getEditButtons() : null}
</li>
</span>
);
}; | the_stack |
import {
hAlignFromPlacement,
hPlacementFromAlignment,
TextPlacement,
vAlignFromPlacement,
vPlacementFromAlignment
} from "@here/harp-text-canvas";
import { assert } from "@here/harp-utils";
import { LayoutState } from "./LayoutState";
import { RenderState } from "./RenderState";
import { TextElement } from "./TextElement";
import { TextElementType } from "./TextElementType";
/**
* `TextElementState` keeps the current state of a text element while it's being rendered.
*/
export class TextElementState {
/**
* @hidden
* Used during label placement to reserve space from front to back.
*/
private m_viewDistance: number | undefined;
/**
* @hidden
* Used during rendering.
*/
private m_iconRenderState?: RenderState;
/**
* @hidden
* Used during rendering.
*/
private m_textRenderState?: RenderState;
/**
* @hidden
* Used to store recently used text layout.
*/
private m_textLayoutState?: LayoutState;
/**
* @hidden
* Stores index into path for TextElements that are of type LineMarker.
*/
private readonly m_lineMarkerIndex?: number;
/**
*
* @param element - TextElement this state represents
* @param positionIndex - Optional index for TextElements of type LineMarker.
*/
constructor(readonly element: TextElement, positionIndex?: number) {
this.m_lineMarkerIndex = positionIndex;
}
get initialized(): boolean {
return this.m_textRenderState !== undefined || this.m_iconRenderState !== undefined;
}
/**
* @returns `true` if any component of the element is visible, `false` otherwise.
*/
get visible(): boolean {
if (this.m_textRenderState !== undefined && this.m_textRenderState.isVisible()) {
return true;
}
const iconRenderState = this.iconRenderState;
if (iconRenderState !== undefined && iconRenderState.isVisible()) {
return true;
}
return false;
}
/**
* Return the last text placement used.
*
* If the text wasn't yet rendered or have no alternative placements it will fallback to
* style/theme based placement.
*
* @returns [[TextPlacement]] object containing vertical/horizontal align.
*/
get textPlacement(): TextPlacement {
const themeLayout = this.element.layoutStyle!;
const stateLayout = this.m_textLayoutState;
// Would be good to test for persistence when getting state layout, but with this
// most of the isolated placement unit tests will fail.
const lastPlacement =
stateLayout !== undefined
? stateLayout.textPlacement
: {
h: hPlacementFromAlignment(themeLayout.horizontalAlignment),
v: vPlacementFromAlignment(themeLayout.verticalAlignment)
};
return lastPlacement;
}
/**
* Set text placement to be used.
*
* This may be base text anchor placement as defined by style or alternative placement.
*
* @param placement - The new [[TextPlacement]] to be used.
*/
set textPlacement(placement: TextPlacement) {
if (this.m_textLayoutState === undefined && this.isBaseTextPlacement(placement) === true) {
// Do nothing, layout state is not required cause we leave the base placement.
return;
}
if (this.m_textLayoutState === undefined) {
// State is not yet defined, but we have placement to store, either alternative or
// not yet specified in the context of layoutStyle.
this.m_textLayoutState = new LayoutState(placement);
} else {
this.m_textLayoutState.textPlacement = placement;
}
}
/**
* Returns information if the text placement provided is the base one defined in style (theme).
*
* @param placement - The [[TextPlacement]] to check.
* @returns [[true]] if the placement provided is exactly the same as in theme base layout,
* [[false]] if it differs from the basic layout provided in style or
* [[undefined]] if the layout style is not yet defined so it is hard to say.
*/
isBaseTextPlacement(placement: TextPlacement): boolean | undefined {
const themeLayout = this.element.layoutStyle;
if (themeLayout !== undefined) {
return (
hAlignFromPlacement(placement.h) === themeLayout.horizontalAlignment &&
vAlignFromPlacement(placement.v) === themeLayout.verticalAlignment
);
}
return undefined;
}
/**
* Resets the element to an initialized state.
*/
reset() {
if (this.m_textRenderState !== undefined) {
this.m_textRenderState.reset();
}
if (this.m_textLayoutState !== undefined) {
if (this.element.layoutStyle !== undefined) {
this.m_textLayoutState.reset(this.element.layoutStyle);
} else {
this.m_textLayoutState = undefined;
}
}
if (this.iconRenderState) {
(this.m_iconRenderState as RenderState).reset();
}
this.m_viewDistance = undefined;
this.element.textBufferObject = undefined;
this.element.bounds = undefined;
}
/**
* Replaces given text element, inheriting its current state.
* The predecessor text element state is erased.
* @param predecessor - Text element state to be replaced.
*/
replace(predecessor: TextElementState) {
this.m_textRenderState = predecessor.m_textRenderState;
this.m_textLayoutState = predecessor.m_textLayoutState;
this.m_iconRenderState = predecessor.m_iconRenderState;
predecessor.m_textRenderState = undefined;
predecessor.m_textLayoutState = undefined;
predecessor.m_iconRenderState = undefined;
if (this.element.glyphs === undefined) {
// Use the predecessor glyphs and case array until proper ones are computed.
this.element.glyphs = predecessor.element.glyphs;
this.element.glyphCaseArray = predecessor.element.glyphCaseArray;
}
this.element.bounds = undefined;
this.element.textBufferObject = undefined;
}
/**
* Returns the last computed distance of the text element to the camera.
* @returns Distance to camera.
*/
get viewDistance(): number | undefined {
return this.m_viewDistance;
}
/**
* Updates the text element state.
* @param viewDistance - The new view distance to set. If `undefined`, element is considered to
* be out of view.
*/
update(viewDistance: number | undefined) {
if (!this.initialized && viewDistance !== undefined) {
this.initializeRenderStates();
}
this.setViewDistance(viewDistance);
}
/**
* Sets the distance of the element to the current view center.
* @param viewDistance - The new view distance to set. If `undefined`, element is considered to
* be out of view.
*/
setViewDistance(viewDistance: number | undefined) {
this.m_viewDistance = viewDistance;
}
/**
* Return the last distance that has been computed for sorting during placement. This may not be
* the actual distance if the camera is moving, as the distance is computed only during
* placement. If the property `alwaysOnTop` is true, the value returned is always `0`.
*
* @returns 0 or negative distance to camera.
*/
get renderDistance(): number {
return this.element.alwaysOnTop === true
? 0
: this.m_viewDistance !== undefined
? -this.m_viewDistance
: 0;
}
/**
* @returns The text render state.
*/
get textRenderState(): RenderState | undefined {
return this.m_textRenderState;
}
/**
* Returns the icon render state for the case where the text element has only one icon.
* @returns The icon render state if the text element has a single icon, otherwise undefined.
*/
get iconRenderState(): RenderState | undefined {
return this.m_iconRenderState;
}
/**
* Returns the index into the path of the TextElement if the TextElement is of type LineMarker,
* `undefined` otherwise.
*/
public get lineMarkerIndex(): number | undefined {
return this.m_lineMarkerIndex;
}
/**
* Returns the position of the TextElement. If this TextElementState belongs to a TextElement
* of type LineMarker, it returns the position of the marker at the references index in the
* path of the TextElement.
*/
public get position(): THREE.Vector3 {
return this.element.path !== undefined && this.m_lineMarkerIndex !== undefined
? this.element.path[this.m_lineMarkerIndex]
: this.element.position;
}
/**
* Updates the fading state to the specified time.
* @param time - The current time.
* @param disableFading - If `True` there will be no fading transitions, i.e., state will go
* directly from FadedIn to FadedOut and vice versa.
*/
updateFading(time: number, disableFading: boolean): void {
if (this.m_textRenderState !== undefined) {
this.m_textRenderState.updateFading(time, disableFading);
}
if (this.iconRenderState !== undefined) {
this.iconRenderState.updateFading(time, disableFading);
}
}
/**
* Initialize text and icon render states
*/
private initializeRenderStates() {
assert(this.m_textRenderState === undefined);
assert(this.m_textLayoutState === undefined);
assert(this.m_iconRenderState === undefined);
const { textFadeTime } = this.element;
this.m_textRenderState = new RenderState(textFadeTime);
if (
this.element.type === TextElementType.PoiLabel ||
this.element.type === TextElementType.LineMarker
) {
// If there's no fade time for icon, use same as text to keep fading of text and icon
// in sync.
const techniqueIconFadeTime = this.element.poiInfo?.technique.iconFadeTime;
const iconFadeTime =
techniqueIconFadeTime !== undefined ? techniqueIconFadeTime * 1000 : textFadeTime;
this.m_iconRenderState = new RenderState(iconFadeTime);
}
}
}
/**
* Test if the TextElement this {@link TextElementState} refers to is of type LineMarker.
* @param state - Text element state to test.
*/
export function isLineMarkerElementState(state: TextElementState) {
return (state as any).m_lineMarkerIndex !== undefined;
} | the_stack |
// Based upon the TypeScript language services example at https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#incremental-build-support-using-the-language-services
import * as ts from "../../../../modules/typescript";
/**
* Abstraction over the file system
*/
export interface FileSystemInterface {
/**
* Deterimine if the particular file exists in the resources
* @param {string} filename
* @return {boolean}
*/
fileExists(filename: string): boolean;
/**
* Grab the contents of the file
* @param {string} filename
* @return {string}
*/
getFile(filename: string): string;
/**
* Write the contents to the file specified
* @param {string} filename
* @param {string} contents
*/
writeFile(filename: string, contents: string);
/**
* Returns the current directory / root of the source tree
* @return {string}
*/
getCurrentDirectory(): string;
}
/**
* Resource extension that handles compiling or transpling typescript on file save.
*/
export class TypescriptLanguageService {
constructor(fs: FileSystemInterface, tsconfig: any) {
this.fs = fs;
this.setTsConfig(tsconfig);
// Create the language service files
this.documentRegistry = ts.createDocumentRegistry();
this.createLanguageService(this.documentRegistry);
}
private fs: FileSystemInterface = null;
private languageService: ts.LanguageService = null;
private documentRegistry: ts.DocumentRegistry = null;
private compilerOptions: ts.CompilerOptions = null;
name: string = "TypescriptLanguageService";
private projectFiles: string[] = [];
private versionMap: ts.Map<{ version: number, snapshot?: ts.IScriptSnapshot }> = {};
private createLanguageService(documentRegistry: ts.DocumentRegistry) {
// Create the language service host to allow the LS to communicate with the host
const servicesHost: ts.LanguageServiceHost = {
getScriptFileNames: () => this.projectFiles,
getScriptVersion: (fileName) => this.versionMap[fileName] && this.versionMap[fileName].version.toString(),
getScriptSnapshot: (filename) => {
const scriptVersion = this.versionMap[filename];
// Grab the cached version
if (scriptVersion) {
if (scriptVersion.snapshot) {
return scriptVersion.snapshot;
} else {
let sourceFile = this.documentRegistry.acquireDocument(filename, this.compilerOptions, ts.ScriptSnapshot.fromString(""), scriptVersion.version.toString());
return ts.ScriptSnapshot.fromString(sourceFile.text);
}
}
},
getCurrentDirectory: () => this.fs.getCurrentDirectory(),
getCompilationSettings: () => this.compilerOptions,
getDefaultLibFileName: (options) => undefined
};
this.languageService = ts.createLanguageService(servicesHost, documentRegistry);
}
/**
* Sets the tsconfig file and parses out the command line options
* @param {any} tsConfig
* @return {[type]}
*/
setTsConfig(tsConfig: any) {
// Need to pass a stub in. It's not going to be used, but the JSON Config Parser needs an object in order to parse the tsconfig
const stubParseConfigHost: ts.ParseConfigHost = {
readDirectory(rootDir: string, extension: string, exclude: string[] ): string[] {
return null;
},
fileExists(fileName: string): boolean {
return false;
},
readFile(fileName: string): string {
return "";
}
};
let cmdLine = ts.parseJsonConfigFileContent(tsConfig, stubParseConfigHost, ".");
this.compilerOptions = cmdLine.options;
// Set a dummy out directory because we need to be able to handle JS files
// and if we don't set one, then the compiler complains that it will
// overwrite a source file. During emit, we just won't emit
// js files
this.compilerOptions.outDir = "DUMMY_OUT_DIR";
}
/**
* Release a project file from the internal project cache
* @param {string} filename
*/
releaseProjectFile(filename: string) {
if (this.versionMap[filename]) {
const fileIndex = this.projectFiles.indexOf(filename);
if (fileIndex > -1) {
this.projectFiles.splice(fileIndex, 1);
}
delete this.versionMap[filename];
this.documentRegistry.releaseDocument(filename, this.compilerOptions);
}
}
/**
* Adds a file to the internal project cache
* @param {string} filename the full path of the file to add
* @param [{sring}] fileContents optional file contents. If not provided, the filesystem object will be queried
*/
addProjectFile(filename: string, fileContents?: string): ts.SourceFile {
if (this.projectFiles.indexOf(filename) == -1) {
console.log("Added project file: " + filename);
if (fileContents == null) {
this.versionMap[filename] = {
version: 0,
snapshot: ts.ScriptSnapshot.fromString(this.fs.getFile(filename))
};
} else {
this.versionMap[filename] = {
version: 0,
snapshot: ts.ScriptSnapshot.fromString(fileContents)
};
}
this.projectFiles.push(filename);
return this.documentRegistry.acquireDocument(
filename,
this.compilerOptions,
this.versionMap[filename].snapshot,
"0");
} else {
return null;
}
}
/**
* Updates the internal file representation.
* @param {string} filename name of the file
* @param {string} fileContents optional contents of the file.
* @return {ts.SourceFile}
*/
updateProjectFile(filename: string, fileContents: string): ts.SourceFile {
if (this.projectFiles.indexOf(filename) == -1) {
return this.addProjectFile(filename, fileContents);
} else {
console.log("Updating file: " + filename);
this.versionMap[filename].version++;
this.versionMap[filename].snapshot = ts.ScriptSnapshot.fromString(fileContents);
return this.documentRegistry.updateDocument(
filename,
this.compilerOptions,
this.versionMap[filename].snapshot,
this.versionMap[filename].version.toString());
}
}
/**
* returns a file previously registered
* @param {string} filename
* @return {ts.SourceFile}
*/
getSourceFile(filename: string): ts.SourceFile {
return this.documentRegistry.acquireDocument(
filename,
this.compilerOptions,
this.versionMap[filename].snapshot,
this.versionMap[filename].version.toString());
}
/**
* Updates the internal file version number
* @param {string} filename name of the file
* @return {ts.SourceFile}
*/
updateProjectFileVersionNumber(filename: string): ts.SourceFile {
this.versionMap[filename].version++;
return this.documentRegistry.updateDocument(
filename,
this.compilerOptions,
this.versionMap[filename].snapshot,
this.versionMap[filename].version.toString());
}
/**
* Returns the list of project files
* @return {string[]}
*/
getProjectFiles(): string[] {
return this.projectFiles;
}
getDiagnostics(filename: string) {
let allDiagnostics = this.languageService.getSyntacticDiagnostics(filename);
if (filename.endsWith(".ts")) {
allDiagnostics = allDiagnostics.concat(this.languageService.getSemanticDiagnostics(filename));
}
return allDiagnostics.map(diagnostic => {
return {
message: ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"),
type: diagnostic.category == 1 ? "error" : "warning",
start: diagnostic.start,
length: diagnostic.length,
code: diagnostic.code,
source: filename
};
});
}
/**
* Simply transpile the typescript file. This is much faster and only checks for syntax errors
* @param {string[]} fileNames array of files to transpile
*/
transpile(fileNames: string[]): void {
fileNames.forEach((fileName) => {
console.log(`${this.name}: Transpiling ${fileName}`);
let script = this.fs.getFile(fileName);
let diagnostics: ts.Diagnostic[] = [];
let result = ts.transpile(script, this.compilerOptions, fileName, diagnostics);
if (diagnostics.length) {
this.logErrors(diagnostics);
}
if (diagnostics.length == 0) {
this.fs.writeFile(fileName.replace(".ts", ".js"), result);
}
});
}
/**
* Converts the line and character offset to a position
* @param {ts.SourceFile} file
* @param {number} line
* @param {number} character
* @return {number}
*/
getPositionOfLineAndCharacter(file: ts.SourceFile, line: number, character: number): number {
return ts.getPositionOfLineAndCharacter(file, line, character);
}
/**
* Returns the completions available at the provided position
* @param {string} filename
* @param {number} position
* @return {ts.CompletionInfo}
*/
getCompletions(filename: string, pos: number): ts.CompletionInfo {
return this.languageService.getCompletionsAtPosition(filename, pos);
}
/**
* Returns details of this completion entry
* @param {string} filename
* @param {number} pos
* @param {string} entryname
* @return {ts.CompletionEntryDetails}
*/
getCompletionEntryDetails(filename: string, pos: number, entryname: string): ts.CompletionEntryDetails {
return this.languageService.getCompletionEntryDetails(filename, pos, entryname);
}
/**
* Returns hover information about a position
* @param {string} filename
* @param {number} pos
*/
getQuickInfoAtPosition(filename: string, pos: number) {
let results = this.languageService.getQuickInfoAtPosition(filename, pos);
if (results) {
return {
contents: ts.displayPartsToString(results.displayParts),
range: results.textSpan,
documentation: ts.displayPartsToString(results.documentation)
};
} else {
return null;
}
}
/**
* Returns information about the current element in a function signature
* @param {string} filename
* @param {number} pos
*/
getSignatureHelpItems(filename: string, pos: number) {
let results = this.languageService.getSignatureHelpItems(filename, pos);
if (results) {
return {
selectedItemIndex: results.selectedItemIndex,
argumentIndex: results.argumentIndex,
items: results.items
};
} else {
return null;
}
}
/**
* Compile the provided file to javascript with full type checking etc
* @param {string} a list of file names to compile
* @param {function} optional callback which will be called for every file compiled and will provide any errors
*/
compile(files: string[], progress?: (filename: string, errors: ts.Diagnostic[]) => void): ts.Diagnostic[] {
let start = new Date().getTime();
//Make sure we have these files in the project
files.forEach((file) => {
this.addProjectFile(file);
});
// We need to run through and release any transpiled JS files
this.projectFiles
.filter(f => f.endsWith(".js"))
.forEach(f => {
if (this.projectFiles.indexOf(f.replace(/\.js$/, ".ts")) > -1) {
this.releaseProjectFile(f);
}
});
let errors: ts.Diagnostic[] = [];
// if we have a 0 length for files, let's compile all files
if (files.length == 0) {
files = this.projectFiles;
}
files.forEach(filename => {
let currentErrors = this.compileFile(filename);
errors = errors.concat(currentErrors);
if (progress) {
progress(filename, currentErrors);
}
});
console.log(`${this.name}: Compiling complete after ${new Date().getTime() - start} ms`);
return errors;
}
/**
* Delete a file from the project store
* @param {string} filepath
*/
deleteProjectFile(filepath: string) {
if (this.versionMap[filepath]) {
delete this.versionMap[filepath];
}
let idx = this.projectFiles.indexOf(filepath);
if (idx > -1) {
console.log(`delete project file from ${filepath}`);
this.projectFiles.splice(idx, 1);
}
}
/**
* rename a file in the project store
* @param {string} filepath the old path to the file
* @param {string} newpath the new path to the file
*/
renameProjectFile(filepath: string, newpath: string): void {
let oldFile = this.versionMap[filepath];
if (oldFile) {
this.releaseProjectFile(filepath);
oldFile.version++;
this.versionMap[newpath] = oldFile;
this.projectFiles.push(newpath);
this.documentRegistry.acquireDocument(
newpath,
this.compilerOptions,
oldFile.snapshot,
oldFile.version.toString());
}
}
/**
* clear out any caches, etc.
*/
reset() {
this.projectFiles = [];
this.versionMap = {};
//this.languageService = null;
}
/**
* Compile an individual file
* @param {string} filename the file to compile
* @return {[ts.Diagnostic]} a list of any errors
*/
private compileFile(filename: string): ts.Diagnostic[] {
console.log(`${this.name}: Compiling version ${this.versionMap[filename].version} of ${filename}`);
//if (!filename.match("\.d\.ts$")) {
try {
return this.emitFile(filename);
} catch (err) {
console.log(`${this.name}: problem encountered compiling ${filename}: ${err}`);
return [];
// console.log(err.stack);
}
//}
}
/**
* writes out a file from the compile process
* @param {string} filename [description]
* @return {[ts.Diagnostic]} a list of any errors
*/
private emitFile(filename: string): ts.Diagnostic[] {
let allDiagnostics: ts.Diagnostic[] = [];
if (filename.endsWith(".ts")) {
let output = this.languageService.getEmitOutput(filename);
if (output.emitSkipped) {
console.log(`${this.name}: Failure Emitting ${filename}`);
allDiagnostics = this.languageService.getCompilerOptionsDiagnostics()
.concat(this.languageService.getSyntacticDiagnostics(filename))
.concat(this.languageService.getSemanticDiagnostics(filename));
} else {
output.outputFiles.forEach(o => {
this.fs.writeFile(filename.replace(/\.ts$/, ".js"), o.text);
});
}
}
return allDiagnostics;
}
/**
* Logs errors from the diagnostics returned from the compile/transpile process
* @param {ts.Diagnostic} diagnostics information about the errors
* @return {[type]} [description]
*/
private logErrors(diagnostics: ts.Diagnostic[]) {
let msg = [];
diagnostics.forEach(diagnostic => {
let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
if (diagnostic.file) {
let d = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
let line = d.line;
let character = d.character;
// NOTE: Destructuring throws an error in chrome web view
//let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
msg.push(`${this.name}: Error ${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
}
else {
msg.push(`${this.name} Error: ${message}`);
}
});
console.log(`TypeScript Errors:\n${msg.join("\n")}`);
throw new Error(`TypeScript Errors:\n${msg.join("\n")}`);
}
} | the_stack |
import { Input, Switch, Select, Slider } from 'antd';
import {
TrademarkCircleOutlined,
DeploymentUnitOutlined,
BranchesOutlined,
ApartmentOutlined,
GatewayOutlined,
CopyrightCircleOutlined,
ForkOutlined,
ShareAltOutlined,
MediumOutlined,
} from '@ant-design/icons';
import TwoInput from './twoInput';
import { LayoutConfig } from '..';
const graphLayoutConfig: {
[key: string]: LayoutConfig[];
} = {
graphLayout_force: [
{
title: '经典力导向布局',
type: 'force',
icon: BranchesOutlined,
items: [
{
component: TwoInput,
label: 'center',
labelZh: '布局中心',
key: 'layoutConfig.center',
inputLabel: ['x', 'y'],
defaultValue: [500, 300],
description: '布局的中心点,默认为图的中心点',
},
{
component: Slider,
label: 'linkDistance',
labelZh: '边长度',
key: 'layoutConfig.linkDistance',
defaultValue: 150,
max: 500,
min: 1,
description: '边的长度,默认为50',
},
{
component: Slider,
label: 'nodeStrength',
labelZh: '节点作用力',
key: 'layoutConfig.nodeStrength',
defaultValue: -35,
min: -100,
max: 500,
description: '节点作用力,正数代表节点之间的引力作用,负数代表节点之间的斥力作用',
},
{
component: Slider,
label: 'edgeStrength',
labelZh: '边作用力',
key: 'layoutConfig.edgeStrength',
defaultValue: 0.2,
step: 0.1,
min: 0,
max: 1,
description: '边的作用力,默认根据节点的出入度自适应',
},
{
component: Switch,
isSwitch: true,
label: 'preventOverlap',
labelZh: '是否防止重叠',
key: 'layoutConfig.preventOverlap',
defaultValue: true,
size: 'small',
description:
'是否防止重叠,设置为true以后,可以避免节点重叠在一起,该参数必须配合nodeSize使用,只有当nodeSize与节点大小相同时,才能够进行重叠的碰撞检测',
},
{
component: Slider,
label: 'nodeSize',
labelZh: '节点占布局空间',
key: 'layoutConfig.nodeSize',
defaultValue: 0,
min: 0,
max: 200,
description: '节点在布局中所占空间大小(直径),用于碰撞检测,若设置为0,则使用节点本身的大小',
},
{
component: Slider,
label: 'nodeSpacing',
labelZh: '节点间距',
key: 'layoutConfig.nodeSpacing',
defaultValue: 15,
min: 0,
max: 200,
description: 'preventOverlap为true时生效,防止重叠时节点边缘间距的最小值',
},
{
component: Slider,
label: 'collideStrength',
labelZh: '防重叠力强度',
key: 'layoutConfig.collideStrength',
max: 5,
min: 0,
defaultValue: 1,
step: 0.2,
description: '防止重叠的力的强度,取值范围[0, 1],默认值为1',
},
{
component: Slider,
label: 'alpha',
labelZh: '收敛阈值',
key: 'layoutConfig.alpha',
max: 1,
min: 0.001,
defaultValue: 0.3,
step: 0.001,
description: '当前迭代的收敛阈值,默认值为0.3,该值设置的越大,迭代越容易收敛,但布局质量不高',
},
{
component: Slider,
label: 'alphaDecay',
labelZh: '衰减率',
key: 'layoutConfig.alphaDecay',
defaultValue: 0.028,
max: 1,
min: 0.001,
step: 0.001,
description: '力导布局迭代阈值的衰减率,范围为[0, 1],默认值为0.028,对应的迭代数为300',
},
{
component: Slider,
label: 'alphaMin',
labelZh: '停止迭代阈值',
key: 'layoutConfig.alphaMin',
defaultValue: 0.002,
max: 1,
min: 0.001,
step: 0.001,
description: '停止迭代的阈值,当收敛阈值小于该值时,就会停止迭代',
},
],
},
],
graphLayout_concentric: [
{
title: '同心圆布局',
type: 'concentric',
icon: DeploymentUnitOutlined,
items: [
{
component: TwoInput,
label: 'center',
labelZh: '中心点',
key: 'layoutConfig.center',
defaultValue: [500, 300],
description: '布局的中心点,默认值为图的中心',
},
{
component: Slider,
label: 'nodeSize',
labelZh: '节点大小',
key: 'layoutConfig.nodeSize',
defaultValue: 50,
description: '节点的大小(直径),用于防止节点重叠时的碰撞检测',
},
{
component: Slider,
label: 'minNodeSpacing',
labelZh: '最小间距',
key: 'layoutConfig.minNodeSpacing',
defaultValue: 10,
description: '环与环之间的最小间距,用于调整半径,默认值为10',
},
{
component: Switch,
isSwitch: true,
label: 'preventOverlap',
labelZh: '是否防止重叠',
key: 'layoutConfig.preventOverlap',
defaultValue: true,
size: 'small',
description:
'是否防止重叠,设置为true后,可以避免节点之间相互重叠,必须配置nodeSize使用,只有当nodeSIze设置为和节点大小一致时,才会进行节点重叠的碰撞检测',
},
{
component: Slider,
label: 'sweep',
labelZh: '弧度差',
key: 'layoutConfig.sweep',
defaultValue: undefined,
min: 0,
max: 10,
description: '第一个节点和最后一个节点之间的弧度差',
},
{
component: Switch,
isSwitch: true,
label: 'equidistant',
labelZh: '是否等间距',
key: 'layoutConfig.equidistant',
defaultValue: false,
size: 'small',
description: '环与环之间的距离是否相等,默认为false,设置为true,在视觉上比较统一',
},
{
component: Slider,
label: 'startAngle',
labelZh: '起始弧度',
key: 'layoutConfig.startAngle',
defaultValue: (3 / 2) * Math.PI,
min: 0,
max: 2 * Math.PI,
step: 0.1 * Math.PI,
description: '节点的起始弧度值,默认为3 / 2 * Math.PI',
},
{
component: Switch,
isSwitch: true,
label: 'clockwise',
labelZh: '是否顺时针',
key: 'layoutConfig.clockwise',
defaultValue: false,
size: 'small',
description: '是否按照顺时针方向排列,默认为false',
},
{
component: Select,
label: 'sortBy',
labelZh: '排序依据',
key: 'layoutConfig.sortBy',
size: 'small',
defaultValue: null,
options: [
{ label: null, value: null },
{ label: 'topology', value: 'topology' },
{ label: 'degree', value: 'degree' },
],
description: '指定排序的依据,即节点的某个属性名,数值越高则该节点被放置的越中心',
},
],
},
],
graphLayout_radial: [
{
title: '辐射布局',
type: 'radial',
icon: ShareAltOutlined,
items: [
{
component: TwoInput,
label: 'center',
labelZh: '中心点',
key: 'layoutConfig.center',
defaultValue: [500, 300],
description: '布局的中心点,默认值为图的中心',
},
{
component: Slider,
label: 'unitRadius',
labelZh: '层级距离',
key: 'layoutConfig.unitRadius',
defaultValue: 100,
max: 500,
min: 1,
description: '每一圈距离上一圈的距离,默认值为100,填充整个画布,即根据图的大小决定',
},
{
component: Slider,
label: 'linkDistance',
labelZh: '边长度',
key: 'layoutConfig.linkDistance',
defaultValue: 50,
min: 1,
max: 500,
description: '边的长度,默认值50',
},
{
component: Slider,
label: 'maxIteration',
labelZh: '最大迭代次数',
key: 'layoutConfig.maxIteration',
defaultValue: 1000,
max: 10000,
min: 1,
description: '最大迭代次数,当迭代达到设定的值时,就会停止迭代',
},
{
component: Input,
label: 'focusNode',
labelZh: '中心节点',
key: 'layoutConfig.focusNode',
size: 'small',
defaultValue: null,
description: '辐射的中心节点,默认为数据中第一个节点,可以设置为节点的ID',
},
{
component: Slider,
label: 'nodeSize',
labelZh: '节点占布局空间',
key: 'layoutConfig.nodeSize',
defaultValue: 0,
min: 0,
max: 200,
description:
'节点在布局计算中所占空间大小(直径),用于防止节点重叠时的碰撞检测。设置为0时,将使用节点本身大小',
},
{
component: Switch,
isSwitch: true,
label: 'preventOverlap',
labelZh: '是否防止重叠',
key: 'layoutConfig.preventOverlap',
defaultValue: true,
size: 'small',
description:
'是否防止重叠,开启后,可以避免节点之间的相互重叠,必须配置nodeSize使用,只有当设置的nodeSize值与节点大小相同时,才会进行节点重叠的碰撞检测',
},
{
component: Slider,
label: 'nodeSpacing',
labelZh: '节点间距',
key: 'layoutConfig.nodeSpacing',
defaultValue: 20,
min: 1,
max: 100,
description: 'preventOverlap为true时生效,防止重叠时节点边缘间距的最小值,默认值为10',
},
{
component: Slider,
label: 'maxPreventOverlapIteration',
labelZh: '最大重叠迭代',
key: 'layoutConfig.maxPreventOverlapIteration',
defaultValue: 200,
max: 1000,
min: 1,
description: '防止重叠步骤的最大迭代次数,当超过设置的迭代次数后,及时还有节点重叠,也不会再进行迭代调整',
},
{
component: Switch,
isSwitch: true,
label: 'strictRadial',
labelZh: '是否严格',
key: 'layoutConfig.strictRadial',
defaultValue: false,
size: 'small',
description: '是否是严格的辐射布局,即每一层的节点严格在一个环上,preventOverlap为true时生效',
},
{
component: Input,
label: 'sortBy',
labelZh: '排序依据',
key: 'layoutConfig.sortBy',
size: 'small',
defaultValue: undefined,
description:
'同层节点布局后相距远近的依据,默认为undefined,表示根据数据的拓扑结构排序,可以设置为数据中某个字段,根据指定的字段进行排序',
},
{
component: Slider,
label: 'sortStrength',
labelZh: '排序强度',
key: 'layoutConfig.sortStrength',
defaultValue: 10,
min: 1,
max: 100,
description:
'同层节点根据sortBy排列的强度,sortBy不为undefined时生效,数值越大,sortBy指定的方式计算出距离越小的越靠近',
},
],
},
],
graphLayout_circular: [
{
title: '圆形布局',
type: 'circular',
icon: CopyrightCircleOutlined,
items: [
{
component: TwoInput,
label: 'center',
labelZh: '中心点',
key: 'layoutConfig.center',
defaultValue: [500, 300],
description: '布局的中心点,默认值为图的中心',
},
{
component: Slider,
label: 'radius',
labelZh: '半径',
key: 'layoutConfig.radius',
defaultValue: 100,
max: 2500,
min: 1,
description: '圆的半径,默认值为100',
},
{
component: Slider,
label: 'startAngle',
labelZh: '起始角度',
key: 'layoutConfig.startAngle',
defaultValue: 0,
max: 2 * Math.PI,
min: 0,
step: 0.1 * Math.PI,
description: '圆环起始的位置对应的角度',
},
{
component: Slider,
label: 'endAngle',
labelZh: '结束角度',
key: 'layoutConfig.starAngle',
defaultValue: 2 * Math.PI,
max: 2 * Math.PI,
min: 0,
step: 0.1 * Math.PI,
description: '圆环结束的位置对应的角度',
},
// {
// component: Slider,
// label: 'startRadius',
// labelZh: '起始半径',
// key: 'layoutConfig.startRadius',
// },
// {
// component: Slider,
// label: 'endRadius',
// key: 'layoutConfig.endRadius',
// },
{
component: Switch,
isSwitch: true,
label: 'clockwise',
labelZh: '是否顺时针',
key: 'layoutConfig.clockwise',
defaultValue: true,
size: 'small',
description: '是否顺时针排列,默认值为true',
},
{
component: Slider,
label: 'divisions',
labelZh: '分段数',
key: 'layoutConfig.divisions',
defaultValue: 1,
max: 10,
min: 1,
description: '节点在环上的分段数,设置后将会均匀分布在圆环上',
},
{
component: Select,
label: 'ordering',
labelZh: '排序依据',
key: 'layoutConfig.ordering',
size: 'small',
defaultValue: null,
options: [
{ label: null, value: null },
{ label: 'topology', value: 'topology' },
{ label: 'degree', value: 'degree' },
],
description:
'节点在环上的排序的依据,默认null代表直接使用数据中的顺序,topology表示按拓扑排序,degree表示按节点度数排序',
},
{
component: Slider,
label: 'angleRatio',
labelZh: '间隔',
key: 'layoutConfig.angleRatio',
defaultValue: 1,
description: '从第一个节点到最后一个节点之间相隔多少个2*PI,表示节点之间的紧密程度',
},
],
},
],
graphLayout_dagre: [
{
title: 'Dagre布局',
type: 'dagre',
icon: ApartmentOutlined,
items: [
{
component: Select,
label: 'rankdir',
labelZh: '布局方向',
key: 'layoutConfig.rankdir',
defaultValue: 'TB',
size: 'small',
options: [
{ label: 'TB', value: 'TB' },
{ label: 'BT', value: 'BT' },
{ label: 'LR', value: 'LR' },
{ label: 'RL', value: 'RL' },
],
description:
'布局的方向,默认值TB,即从上至下布局,TB表示从上至下布局,BT表示从下至上布局,LR表示从左至右布局,RL表示从右至左布局',
},
{
component: Select,
label: 'align',
labelZh: '对齐方式',
key: 'layoutConfig.align',
defaultValue: undefined,
size: 'small',
options: [
{ label: null, value: null },
{ label: 'UL', value: 'UL' },
{ label: 'UR', value: 'UR' },
{ label: 'DL', value: 'DL' },
{ label: 'DR', value: 'DR' },
],
description:
'节点的对齐方式,默认为UL,即对齐到左上角,UL表示对齐到左上角,UR表示对齐到右下角,DL表示对齐到左下角,DR表示对齐到右下角',
},
{
component: Slider,
label: 'nodeSize',
labelZh: '节点占布局空间',
key: 'layoutConfig.nodeSize',
defaultValue: 0,
max: 200,
min: 0,
description: '节点参与布局所占的空间大小。若设置为0,将使用节点本身的大小',
},
{
component: Slider,
label: 'nodesep',
labelZh: '节点间距',
key: 'layoutConfig.nodesep',
defaultValue: 10,
max: 200,
min: 1,
description: '节点的间距,rankdir为TB或BT时是水平间距,rankdir为LR或RL时为垂直方向上的间距',
},
{
component: Input,
label: 'ranksep',
labelZh: '层间距',
key: 'layoutConfig.ranksep',
size: 'small',
defaultValue: 10,
max: 200,
min: 1,
description:
'各层之间的间距,rankdir为TB或BT时是垂直方向相邻层之间的间距,rankdir为LR或RL时为水平方向上相邻层之间的间距',
},
// 控制点适用于 polyline,目前使用的是 quadratic
// {
// component: Switch,
// isSwitch: true,
// label: 'controlPoints',
// labelZh: '是否保留控制点',
// key: 'layoutConfig.controlPoints',
// defaultValue: true,
// size: 'small',
// description: '是否保留布局连线的控制点,默认为true,设置为false后,则连接到节点的中心点'
// },
],
},
],
graphLayout_grid: [
{
title: '网格布局',
type: 'grid',
icon: GatewayOutlined,
items: [
{
component: TwoInput,
label: 'begin',
labelZh: '起始位置',
key: 'layoutConfig.begin',
inputLabel: ['x', 'y'],
isPx: false,
defaultValue: [50, 150],
description: '网格左上角的位置,默认值为(0, 0)点',
},
{
component: Slider,
label: 'width',
labelZh: '布局宽度',
key: 'layoutConfig.width',
defaultValue: 200,
min: 10,
max: 5000,
description: '布局的宽度',
},
{
component: Slider,
label: 'height',
labelZh: '布局高度',
key: 'layoutConfig.height',
defaultValue: 200,
min: 10,
max: 5000,
description: '布局的高度',
},
{
component: Switch,
isSwitch: true,
label: 'preventOverlap',
labelZh: '是否避免重叠',
key: 'layoutConfig.preventOverlap',
defaultValue: false,
size: 'small',
description:
'是否防止节点重叠,开启后可以避免节点重叠在一起,必须配合nodeSize属性使用,只有设置了与图中节点大小相同的nodeSize值,才能够进行碰撞检测',
},
{
component: Slider,
label: 'preventOverlapPadding',
labelZh: '节点间距',
key: 'layoutConfig.preventOverlapPadding',
defaultValue: 10,
min: 1,
max: 100,
description: '避免重叠时节点的间距值,当preventOverlap为true时生效',
},
{
component: Switch,
isSwitch: true,
label: 'condense',
labelZh: '是否压缩',
key: 'layoutConfig.condense',
defaultValue: false,
size: 'small',
description: '为true时利用最小画布空间,为false时利用所有可用画布大小',
},
{
component: Slider,
label: 'rows',
labelZh: '网格行数',
key: 'layoutConfig.rows',
defaultValue: 10,
min: 1,
max: 500,
description: '网格的行数,默认值为10',
},
{
component: Slider,
label: 'cols',
labelZh: '网格列数',
key: 'layoutConfig.cols',
defaultValue: 10,
min: 1,
max: 500,
description: '网格的列数,默认值为10',
},
{
component: Select,
label: 'sortBy',
labelZh: '排序依据',
key: 'layoutConfig.sortBy',
size: 'small',
defaultValue: null,
options: [
{ label: null, value: null },
{ label: 'topology', value: 'topology' },
{ label: 'degree', value: 'degree' },
],
description:
'指定排序的依据,即根据节点的哪个属性进行排序,数值越高则该节点被放置得越中心,如果不指定,则会计算节点的度数,度数越高,节点将被放置得越中心',
},
],
},
],
graphLayout_fruchterman: [
{
title: 'Fruchterman布局',
type: 'fructherman',
icon: ForkOutlined,
items: [
{
component: TwoInput,
label: 'center',
labelZh: '中心点',
key: 'layoutConfig.center',
defaultValue: [500, 300],
description: '布局的中心点,默认值为图的中心',
},
{
component: Slider,
label: 'maxIteration',
labelZh: '最大迭代次数',
key: 'layoutConfig.maxIteration',
defaultValue: 1000,
max: 10000,
min: 1,
description: '最大的迭代次数,默认值为1000,超过该值就会停止迭代',
},
{
component: Slider,
label: 'gravity',
labelZh: '重力大小',
key: 'layoutConfig.gravity',
defaultValue: 10,
min: 0,
max: 1000,
description: '重力的大小,该值会影响布局的紧凑程度,默认值为10',
},
{
component: Slider,
label: 'speed',
labelZh: '移动速度',
key: 'layoutConfig.speed',
defaultValue: 1,
min: 1,
max: 1000,
description: '每次迭代时节点的移动速度,速度太快可能会导致强烈震荡',
},
{
component: Switch,
isSwitch: true,
label: 'clustering',
labelZh: '是否聚类',
key: 'layoutConfig.clustering',
defaultValue: false,
size: 'small',
description:
'是否按照聚类布局,开启后,布局时就会将同一类型的节点布局到一起,布局结果就会呈现出明显的聚类效果',
},
{
component: Slider,
label: 'clusterGravity',
labelZh: '聚类重力',
key: 'layoutConfig.clusterGravity',
defaultValue: 10,
min: 0,
max: 1000,
description: '聚类内部的重力大小,影响聚类的紧凑程度,只有在clustering为true时生效',
},
{
component: Slider,
label: 'width',
labelZh: '宽度',
key: 'layoutConfig.width',
max: 5000,
min: 10,
defaultValue: 800,
description: '布局的宽度,默认值为画布宽度',
},
{
component: Slider,
label: 'height',
labelZh: '高度',
key: 'layoutConfig.height',
max: 5000,
min: 10,
defaultValue: 500,
description: '布局的高度,默认值为画布高度',
},
],
},
],
graphLayout_mds: [
{
title: 'MDS 布局',
type: 'mds',
icon: MediumOutlined,
items: [
{
component: TwoInput,
label: 'center',
labelZh: '中心点',
key: 'layoutConfig.center',
defaultValue: [500, 300],
description: '布局的中心点,默认值为图的中心',
},
{
component: Slider,
label: 'linkDistance',
labelZh: '边长度',
key: 'layoutConfig.linkDistance',
defaultValue: 200,
max: 500,
min: 1,
description: '边的长度,默认值为50',
},
],
},
],
graphLayout_random: [
{
title: '随机布局',
type: 'random',
icon: TrademarkCircleOutlined,
items: [
{
component: TwoInput,
label: 'center',
defaultValue: [500, 300],
labelZh: '中心点',
key: 'layoutConfig.center',
description: '布局的中心点,默认值为图的中心',
},
{
component: Slider,
label: 'width',
labelZh: '宽度',
key: 'layoutConfig.width',
max: 5000,
min: 10,
defaultValue: 800,
description: '布局的宽度,默认值为画布宽度',
},
{
component: Slider,
label: 'height',
labelZh: '高度',
key: 'layoutConfig.height',
max: 5000,
min: 10,
defaultValue: 500,
description: '布局的高度,默认值为画布高度',
},
],
},
],
};
export default graphLayoutConfig; | the_stack |
import { SlideEffects } from './swiper-interfaces';
import { CLS, eachChild, isHorizontal, transform, transition, triggerTransitionEnd } from './swiper-utils';
import { isIosUIWebView, isSafari } from '../../../platform/platform-utils';
/*=========================
Effects
===========================*/
export const SWIPER_EFFECTS: SlideEffects = {
'fade': {
setTranslate: function (s) {
for (var i = 0; i < s._slides.length; i++) {
var slide = s._slides[i];
var offset = slide.swiperSlideOffset;
var tx = -offset;
if (!s.virtualTranslate) {
tx = tx - s._translate;
}
var ty = 0;
if (!isHorizontal(s)) {
ty = tx;
tx = 0;
}
var slideOpacity = s.fade.crossFade ?
Math.max(1 - Math.abs(slide.progress), 0) :
1 + Math.min(Math.max(slide.progress, -1), 0);
slide.style.opacity = <any>slideOpacity;
transform(slide, 'translate3d(' + tx + 'px, ' + ty + 'px, 0px)');
}
},
setTransition: function (s, plt, duration) {
var slides = s._slides;
for (var i = 0; i < slides.length; i++) {
transition(slides[i], duration);
}
if (s.virtualTranslate && duration !== 0) {
var eventTriggered = false;
for (let i = 0; i < slides.length; i++) {
plt.transitionEnd(slides[i], () => {
if (eventTriggered || !s) return;
eventTriggered = true;
s._animating = false;
triggerTransitionEnd(plt, s._wrapper);
});
}
}
}
},
'flip': {
setTranslate: function (s, plt) {
for (var i = 0; i < s._slides.length; i++) {
var slide = s._slides[i];
var progress = slide.progress;
if (s.flip.limitRotation) {
progress = Math.max(Math.min(slide.progress, 1), -1);
}
var offset = slide.swiperSlideOffset;
var rotate = -180 * progress,
rotateY = rotate,
rotateX = 0,
tx = -offset,
ty = 0;
if (!isHorizontal(s)) {
ty = tx;
tx = 0;
rotateX = -rotateY;
rotateY = 0;
} else if (s._rtl) {
rotateY = -rotateY;
}
slide.style.zIndex = <any>-Math.abs(Math.round(progress)) + s._slides.length;
if (s.flip.slideShadows) {
// Set shadows
var shadowBefore = <HTMLElement>(isHorizontal(s) ? slide.querySelector('.swiper-slide-shadow-left') : slide.querySelector('.swiper-slide-shadow-top'));
var shadowAfter = <HTMLElement>(isHorizontal(s) ? slide.querySelector('.swiper-slide-shadow-right') : slide.querySelector('.swiper-slide-shadow-bottom'));
if (!shadowBefore) {
shadowBefore = plt.doc().createElement('div');
shadowBefore.className = 'swiper-slide-shadow-' + (isHorizontal(s) ? 'left' : 'top');
slide.appendChild(shadowBefore);
}
if (!shadowAfter) {
shadowAfter = plt.doc().createElement('div');
shadowAfter.className = 'swiper-slide-shadow-' + (isHorizontal(s) ? 'right' : 'bottom');
slide.appendChild(shadowAfter);
}
if (shadowBefore) {
shadowBefore.style.opacity = <any>Math.max(-progress, 0);
}
if (shadowAfter) {
shadowAfter.style.opacity = <any>Math.max(progress, 0);
}
}
transform(slide, 'translate3d(' + tx + 'px, ' + ty + 'px, 0px) rotateX(' + rotateX + 'deg) rotateY(' + rotateY + 'deg)');
}
},
setTransition: function (s, plt, duration) {
for (var i = 0; i < s._slides.length; i++) {
var slide = s._slides[i];
transition(slide, duration);
eachChild(slide, '.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left', el => {
transition(el, duration);
});
}
if (s.virtualTranslate && duration !== 0) {
var eventTriggered = false;
plt.transitionEnd(s._slides[s._activeIndex], (ev) => {
if (eventTriggered || !s) return;
if (!(<HTMLElement>ev.target).classList.contains(CLS.slideActive)) {
return;
}
eventTriggered = true;
s._animating = false;
triggerTransitionEnd(plt, s._wrapper);
});
}
}
},
'cube': {
setTranslate: function (s, plt) {
var wrapperRotate = 0;
var cubeShadow: HTMLElement;
if (s.cube.shadow) {
if (isHorizontal(s)) {
cubeShadow = <HTMLElement>s._wrapper.querySelector('.swiper-cube-shadow');
if (!cubeShadow) {
cubeShadow = plt.doc().createElement('div');
cubeShadow.className = 'swiper-cube-shadow';
s._wrapper.appendChild(cubeShadow);
}
cubeShadow.style.height = s.renderedWidth + 'px';
} else {
cubeShadow = <HTMLElement>s.container.querySelector('.swiper-cube-shadow');
if (!cubeShadow) {
cubeShadow = plt.doc().createElement('div');
cubeShadow.className = 'swiper-cube-shadow';
s._wrapper.appendChild(cubeShadow);
}
}
}
for (var i = 0; i < s._slides.length; i++) {
var slide = s._slides[i];
var slideAngle = i * 90;
var round = Math.floor(slideAngle / 360);
if (s._rtl) {
slideAngle = -slideAngle;
round = Math.floor(-slideAngle / 360);
}
var progress = Math.max(Math.min(slide.progress, 1), -1);
var tx = 0, ty = 0, tz = 0;
if (i % 4 === 0) {
tx = - round * 4 * s._renderedSize;
tz = 0;
} else if ((i - 1) % 4 === 0) {
tx = 0;
tz = - round * 4 * s._renderedSize;
} else if ((i - 2) % 4 === 0) {
tx = s._renderedSize + round * 4 * s._renderedSize;
tz = s._renderedSize;
} else if ((i - 3) % 4 === 0) {
tx = - s._renderedSize;
tz = 3 * s._renderedSize + s._renderedSize * 4 * round;
}
if (s._rtl) {
tx = -tx;
}
if (!isHorizontal(s)) {
ty = tx;
tx = 0;
}
var transformStr = 'rotateX(' + (isHorizontal(s) ? 0 : -slideAngle) + 'deg) rotateY(' + (isHorizontal(s) ? slideAngle : 0) + 'deg) translate3d(' + tx + 'px, ' + ty + 'px, ' + tz + 'px)';
if (progress <= 1 && progress > -1) {
wrapperRotate = i * 90 + progress * 90;
if (s._rtl) wrapperRotate = -i * 90 - progress * 90;
}
transform(slide, transformStr);
if (s.cube.slideShadows) {
// Set shadows
var shadowBefore = <HTMLElement>(isHorizontal(s) ? slide.querySelector('.swiper-slide-shadow-left') : slide.querySelector('.swiper-slide-shadow-top'));
var shadowAfter = <HTMLElement>(isHorizontal(s) ? slide.querySelector('.swiper-slide-shadow-right') : slide.querySelector('.swiper-slide-shadow-bottom'));
if (!shadowBefore) {
shadowBefore = plt.doc().createElement('div');
shadowBefore.className = 'swiper-slide-shadow-' + (isHorizontal(s) ? 'left' : 'top');
slide.appendChild(shadowBefore);
}
if (!shadowAfter) {
shadowAfter = plt.doc().createElement('div');
shadowAfter.className = 'swiper-slide-shadow-' + (isHorizontal(s) ? 'right' : 'bottom');
slide.appendChild(shadowAfter);
}
if (shadowBefore) shadowBefore.style.opacity = <any>Math.max(-progress, 0);
if (shadowAfter) shadowAfter.style.opacity = <any>Math.max(progress, 0);
}
}
s._wrapper.style.transformOrigin = s._wrapper.style.webkitTransformOrigin = '50% 50% -' + (s._renderedSize / 2) + 'px';
if (s.cube.shadow) {
if (isHorizontal(s)) {
transform(cubeShadow, 'translate3d(0px, ' + (s.renderedWidth / 2 + s.cube.shadowOffset) + 'px, ' + (-s.renderedWidth / 2) + 'px) rotateX(90deg) rotateZ(0deg) scale(' + (s.cube.shadowScale) + ')');
} else {
var shadowAngle = Math.abs(wrapperRotate) - Math.floor(Math.abs(wrapperRotate) / 90) * 90;
var multiplier = 1.5 - (Math.sin(shadowAngle * 2 * Math.PI / 360) / 2 + Math.cos(shadowAngle * 2 * Math.PI / 360) / 2);
var scale1 = s.cube.shadowScale;
var scale2 = s.cube.shadowScale / multiplier;
var offset = s.cube.shadowOffset;
transform(cubeShadow, 'scale3d(' + scale1 + ', 1, ' + scale2 + ') translate3d(0px, ' + (s.renderedHeight / 2 + offset) + 'px, ' + (-s.renderedHeight / 2 / scale2) + 'px) rotateX(-90deg)');
}
}
var zFactor = (isSafari(plt) || isIosUIWebView(plt)) ? (-s._renderedSize / 2) : 0;
transform(s._wrapper, 'translate3d(0px,0,' + zFactor + 'px) rotateX(' + (isHorizontal(s) ? 0 : wrapperRotate) + 'deg) rotateY(' + (isHorizontal(s) ? -wrapperRotate : 0) + 'deg)');
},
setTransition: function (s, _plt, duration) {
for (var i = 0; i < s._slides.length; i++) {
var slide = s._slides[i];
transition(slide, duration);
eachChild(slide, '.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left', el => {
transition(el, duration);
});
}
if (s.cube.shadow && !isHorizontal(s)) {
eachChild(s.container, '.swiper-cube-shadow', el => {
transition(el, duration);
});
}
}
},
'coverflow': {
setTranslate: function (s, plt) {
var transformStr = s._translate;
var center = isHorizontal(s) ? -transformStr + s.renderedWidth / 2 : -transformStr + s.renderedHeight / 2;
var rotate = isHorizontal(s) ? s.coverflow.rotate : -s.coverflow.rotate;
var translate = s.coverflow.depth;
// Each slide offset from center
for (var i = 0, length = s._slides.length; i < length; i++) {
var slide = s._slides[i];
var slideSize = s._slidesSizesGrid[i];
var slideOffset = slide.swiperSlideOffset;
var offsetMultiplier = (center - slideOffset - slideSize / 2) / slideSize * s.coverflow.modifier;
var rotateY = isHorizontal(s) ? rotate * offsetMultiplier : 0;
var rotateX = isHorizontal(s) ? 0 : rotate * offsetMultiplier;
// var rotateZ = 0
var translateZ = -translate * Math.abs(offsetMultiplier);
var translateY = isHorizontal(s) ? 0 : s.coverflow.stretch * (offsetMultiplier);
var translateX = isHorizontal(s) ? s.coverflow.stretch * (offsetMultiplier) : 0;
// Fix for ultra small values
if (Math.abs(translateX) < 0.001) translateX = 0;
if (Math.abs(translateY) < 0.001) translateY = 0;
if (Math.abs(translateZ) < 0.001) translateZ = 0;
if (Math.abs(rotateY) < 0.001) rotateY = 0;
if (Math.abs(rotateX) < 0.001) rotateX = 0;
var slideTransform = 'translate3d(' + translateX + 'px,' + translateY + 'px,' + translateZ + 'px) rotateX(' + rotateX + 'deg) rotateY(' + rotateY + 'deg)';
transform(slide, slideTransform);
slide.style.zIndex = <any>-Math.abs(Math.round(offsetMultiplier)) + 1;
if (s.coverflow.slideShadows) {
// Set shadows
var shadowBefore = <HTMLElement>(isHorizontal(s) ? slide.querySelector('.swiper-slide-shadow-left') : slide.querySelector('.swiper-slide-shadow-top'));
var shadowAfter = <HTMLElement>(isHorizontal(s) ? slide.querySelector('.swiper-slide-shadow-right') : slide.querySelector('.swiper-slide-shadow-bottom'));
if (!shadowBefore) {
shadowBefore = plt.doc().createElement('div');
shadowBefore.className = 'swiper-slide-shadow-' + (isHorizontal(s) ? 'left' : 'top');
slide.appendChild(shadowBefore);
}
if (!shadowAfter) {
shadowAfter = plt.doc().createElement('div');
shadowAfter.className = 'swiper-slide-shadow-' + (isHorizontal(s) ? 'right' : 'bottom');
slide.appendChild(shadowAfter);
}
if (shadowBefore) {
shadowBefore.style.opacity = <any>(offsetMultiplier > 0 ? offsetMultiplier : 0);
}
if (shadowAfter) {
shadowAfter.style.opacity = <any>((-offsetMultiplier) > 0 ? -offsetMultiplier : 0);
}
}
}
},
setTransition: function (s, _plt, duration) {
for (var i = 0; i < s._slides.length; i++) {
var slide = s._slides[i];
transition(slide, duration);
eachChild(slide, '.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left', (el) => {
transition(el, duration);
});
}
}
}
}; | the_stack |
"use strict";
import * as path from 'path';
import { draftsObject } from './compile';
import * as TreeModel from 'tree-model';
import { window, Disposable, StatusBarAlignment, StatusBarItem, TextDocument, workspace } from 'vscode';
import {totalLength, draftRoot} from './compile';
import simpleGit, {SimpleGit} from 'simple-git';
import {distance} from 'fastest-levenshtein';
let projectCharacterCountNum = 0;
if( draftRoot() != ""){
projectCharacterCountNum = totalLength(draftRoot());
} else {
projectCharacterCountNum = 0;
}
export class CharacterCounter {
private _statusBarItem!: StatusBarItem;
private _countingFolder = '';
private _countingTargetNum = 0;
private _folderCount = {
label: '',
amountLengthNum: 0,
};
private _isEditorChildOfTargetFolder = false;
timeoutID: unknown;
public updateCharacterCount(): void {
if (!this._statusBarItem) {
this._statusBarItem = window.createStatusBarItem(StatusBarAlignment.Left);
}
const editor = window.activeTextEditor;
if (!editor) {
this._statusBarItem.hide();
return;
}
if (editor.document.languageId != "novel" && editor.document.languageId != "markdown" && editor.document.languageId != "plaintext") {
this._statusBarItem.hide();
return;
}
const doc = editor.document;
const docPath = editor.document.uri.fsPath;
const characterCountNum = this._getCharacterCount(doc);
const characterCount = Intl.NumberFormat().format(characterCountNum);
const countingTarget = Intl.NumberFormat().format(this._countingTargetNum);
let savedCharacterCountNum = 0;
if( draftRoot() == ""){
//テキストファイルを直接開いているとき
this._statusBarItem.text = `$(note) ${Intl.NumberFormat().format(this._getCharacterCount(doc))} 文字`;
} else {
savedCharacterCountNum = this._lengthByPath(docPath);
}
const totalCharacterCountNum = projectCharacterCountNum - savedCharacterCountNum + characterCountNum;
const totalCharacterCount = Intl.NumberFormat().format(totalCharacterCountNum);
let editDistance = '';
if(this.ifEditDistance){
if(this.editDistance == -1){
editDistance = `/$(compare-changes)$(sync)文字`;
this._updateEditDistanceDelay();
}else if(this.keyPressFlag){
editDistance = `/$(compare-changes)${Intl.NumberFormat().format(this.editDistance)}$(sync)文字`;
} else{
editDistance = `/$(compare-changes)${Intl.NumberFormat().format(this.editDistance)}文字`;
}
}
if( this._countingFolder != '' ){
//締め切りフォルダーが設定されている時_countingTargetNum
let targetNumberTextNum = this._folderCount.amountLengthNum;
let targetNumberText = Intl.NumberFormat().format(targetNumberTextNum);
if(this._isEditorChildOfTargetFolder){
targetNumberTextNum = targetNumberTextNum - savedCharacterCountNum + characterCountNum;
targetNumberText = Intl.NumberFormat().format(targetNumberTextNum);
}
if(this._countingTargetNum != 0){
targetNumberText += '/' + countingTarget;
}
this._statusBarItem.text = ` ${totalCharacterCount}文字 $(folder-opened) ${this._folderCount.label} ${targetNumberText}文字 $(note) ${characterCount} 文字${editDistance}`;
} else {
this._statusBarItem.text = `$(book) ${totalCharacterCount}文字/$(note) ${characterCount} 文字${editDistance}`;
}
this._statusBarItem.show();
}
public _getCharacterCount(doc: TextDocument): number {
let docContent = doc.getText();
// カウントに含めない文字を削除する
docContent = docContent
.replace(/\s/g, '') // すべての空白文字
.replace(/《(.+?)》/g, '') // ルビ範囲指定記号とその中の文字
.replace(/[||]/g, '') // ルビ開始記号
.replace(/<!--(.+?)-->/, ''); // コメントアウト
let characterCount = 0;
if (docContent !== "") {
characterCount = docContent.length;
}
return characterCount;
}
public _updateProjectCharacterCount(): void{
projectCharacterCountNum = totalLength(draftRoot());
if(this._countingFolder != ''){
//締め切りフォルダーの更新
this._folderCount = {
label:path.basename(this._countingFolder),
amountLengthNum: totalLength(this._countingFolder),
};
}
this.updateCharacterCount();
}
public _setCounterToFolder( pathToFolder: string, targetCharacter: number ): void{
this._countingFolder = pathToFolder;
this._countingTargetNum = targetCharacter;
this._updateProjectCharacterCount();
this._setIfChildOfTarget();
}
private _lengthByPath(dirPath: string): number{
if(draftRoot() == ""){
return 0;
}
const tree = new TreeModel();
const draftTree = tree.parse({dir: draftRoot(),name: 'root',length: 0});
//console.log('rootだけ',draftsObject(draftRoot()));
draftsObject(draftRoot()).forEach(element => {
const draftNode = tree.parse(element);
draftTree.addChild(draftNode);
});
const targetFileNode = draftTree.first(node => node.model.dir === dirPath);
if(targetFileNode){
return targetFileNode.model.length;
} else {
return 0;
}
}
public _setIfChildOfTarget(): boolean{
if(draftRoot() == ""){
return false;
}
const tree = new TreeModel();
const draftTree = tree.parse({dir: draftRoot(),name: 'root',length: 0});
const activeDocumentPath = window.activeTextEditor?.document.uri.fsPath;
draftsObject(draftRoot()).forEach(element => {
const draftNode = tree.parse(element);
draftTree.addChild(draftNode);
});
const deadLineFolderNode = draftTree.first(node => node.model.dir === this._countingFolder);
if(deadLineFolderNode?.hasChildren){
const treeForTarget = new TreeModel();
const targetTree = treeForTarget.parse(deadLineFolderNode.model);
const ifEditorIsChild = targetTree.first(node => node.model.dir === activeDocumentPath);
if(ifEditorIsChild){
this._isEditorChildOfTargetFolder = true;
return true;
}
}
this._isEditorChildOfTargetFolder = false;
return false;
}
public _updateCountingObject(): boolean{
//this._countingObject = draftsObject(draftRoot());
return true;
}
public editDistance = -1;
public latestText ='';
private projectPath = '';
public ifEditDistance = false;
public _setEditDistance(): void{
if( workspace.workspaceFolders == undefined ){
return;
}
const activeDocumentPath = window.activeTextEditor?.document.uri.fsPath;
if (typeof activeDocumentPath != "string") return;
this.projectPath = workspace.workspaceFolders[0].uri.fsPath;
const relatevePath = path.relative(this.projectPath, activeDocumentPath);
const git: SimpleGit = simpleGit(this.projectPath);
console.log('git.revparse()',git.revparse(['--is-inside-work-tree']));
git.revparse('--is-inside-work-tree')
.then(() => {
let latestHash = '';
const logOption = {file: relatevePath,'--until': 'today00:00:00',n: 1};
let showString = '';
git.log(logOption)
.then((logs) => {
//console.log(logs);
if(logs.total === 0){ //昨日以前のコミットがなかった場合、当日中に作られた最古のコミットを比較対象に設定する。
const logOptionLatest = {file: relatevePath,'--reverse': null, '--max-count': '10'};
git.log(logOptionLatest)
.then((logsLatest) => {
if(logsLatest?.total === 0){
window.showInformationMessage(`比較対象になるファイルがGitにコミットされていないようです`);
this.ifEditDistance = false;
this.latestText = '';
this.updateCharacterCount();
} else {
latestHash = logsLatest.all[0].hash;
showString = latestHash+":"+relatevePath;
console.log('最終更新: ',showString);
git.show(showString)
.then((showLog) =>{
console.log('最終更新テキスト: ',typeof showLog,showLog);
if(typeof showLog === 'string'){
if(showLog == '') showLog = ' ';
this.latestText = showLog;
this.ifEditDistance = true;
this.updateCharacterCount();
}
})
.catch((err) => console.error('failed to git show:', err))
}})
.catch((err) => console.error('failed to git show:', err))
} else {
latestHash = logs.all[0].hash;
showString = latestHash+":"+relatevePath;
//console.log('showString: ',showString);
git.show(showString)
.then((showLog) =>{
if(typeof showLog === 'string'){
this.latestText = showLog;
this.ifEditDistance = true;
this.updateCharacterCount();
}
})
.catch((err) => console.error('failed to git show:', err))
}
})
.catch((err) => {
console.error('failed:',err);
window.showInformationMessage(`Gitのレポジトリを確かめてください`);
this.ifEditDistance = false;
this.latestText = '';
this.updateCharacterCount();
});
})
.catch((err) => {
console.error('git.revparse:',err);
})
}
public _setLatestUpdate(latestGitText: string): void{
this.latestText = latestGitText;
console.log('latest from Git:', latestGitText);
this._updateEditDistanceDelay();
}
private keyPressFlag = false;
public _updateEditDistanceActual(): void{
const currentText = window.activeTextEditor?.document.getText();
console.log('現在の原稿',currentText);
console.log('latestの原稿',this.latestText);
if(this.latestText != '' && typeof currentText == "string"){
this.editDistance = distance(this.latestText, currentText);
this.keyPressFlag = false;
this.updateCharacterCount();
}
delete this.timeoutID;
}
public _updateEditDistanceDelay(): void{
if (!this.keyPressFlag && window.activeTextEditor){
this.keyPressFlag = true;
const updateCounter = Math.min(
Math.ceil(
window.activeTextEditor.document.getText().length / 100),
500
);
console.log('timeoutID',this.timeoutID,updateCounter);
this.timeoutID = setTimeout(() => {
this._updateEditDistanceActual();
}, updateCounter);
}
}
public _timerCancel(): void{
if(typeof this.timeoutID == "number") {
this.clearTimeout(this.timeoutID);
delete this.timeoutID;
}
}
clearTimeout(timeoutID: number): void{
throw new Error('Method not implemented.'+ timeoutID);
}
public dispose(): void {
this._statusBarItem.dispose();
}
}
export class CharacterCounterController {
private _characterCounter: CharacterCounter;
private _disposable: Disposable;
constructor(characterCounter: CharacterCounter) {
this._characterCounter = characterCounter;
this._characterCounter._setEditDistance();
this._characterCounter.updateCharacterCount();
const subscriptions: Disposable[] = [];
window.onDidChangeTextEditorSelection(this._onEvent, this, subscriptions);
workspace.onDidSaveTextDocument(this._onSave, this, subscriptions);
window.onDidChangeActiveTextEditor(this._onFocusChanged, this, subscriptions);
this._disposable = Disposable.from(...subscriptions);
}
private _onEvent() {
this._characterCounter.updateCharacterCount();
if(this._characterCounter.ifEditDistance) this._characterCounter._updateEditDistanceDelay();
}
private _onFocusChanged() {
this._characterCounter._setIfChildOfTarget();
//編集処理の初期化
this._characterCounter.ifEditDistance = false;
this._characterCounter.latestText = '\n';
this._characterCounter.editDistance = -1;
this._characterCounter._setEditDistance();
this._characterCounter._updateCountingObject();
}
private _onSave() {
this._characterCounter._updateCountingObject();
this._characterCounter._updateProjectCharacterCount();
}
public dispose(): void {
this._disposable.dispose();
}
} | the_stack |
import { IncomingMessage, ServerResponse } from 'http';
import { FC } from './fc';
import { SCF } from './scf';
interface CookieGetOption {
signed: boolean;
}
interface CookieSetOption {
/**
* a number representing the milliseconds from Date.now() for expiry
*/
maxAge?: number;
/**
* a Date object indicating the cookie's expiration
* date (expires at the end of session by default).
*/
expires?: Date;
/**
* a string indicating the path of the cookie (/ by default).
*/
path?: string;
/**
* a string indicating the domain of the cookie (no default).
*/
domain?: string;
/**
* a boolean indicating whether the cookie is only to be sent
* over HTTPS (false by default for HTTP, true by default for HTTPS).
*/
secure?: boolean;
/**
* "secureProxy" option is deprecated; use "secure" option, provide "secure" to constructor if needed
*/
secureProxy?: boolean;
/**
* a boolean indicating whether the cookie is only to be sent over HTTP(S),
* and not made available to client JavaScript (true by default).
*/
httpOnly?: boolean;
/**
* a boolean or string indicating whether the cookie is a "same site" cookie (false by default).
* This can be set to 'strict', 'lax', or true (which maps to 'strict').
*/
sameSite?: 'strict' | 'lax' | 'none' | boolean;
/**
* a boolean indicating whether the cookie is to be signed (false by default).
* If this is true, another cookie of the same name with the .sig suffix
* appended will also be sent, with a 27-byte url-safe base64 SHA1 value
* representing the hash of cookie-name=cookie-value against the first Keygrip key.
* This signature key is used to detect tampering the next time a cookie is received.
*/
signed?: boolean;
/**
* a boolean indicating whether to overwrite previously set
* cookies of the same name (false by default). If this is true,
* all cookies set during the same request with the same
* name (regardless of path or domain) are filtered out of
* the Set-Cookie header when setting this cookie.
*/
overwrite?: boolean;
}
interface Cookies {
secure: boolean;
request: IncomingMessage;
response: ServerResponse;
/**
* This extracts the cookie with the given name from the
* Cookie header in the request. If such a cookie exists,
* its value is returned. Otherwise, nothing is returned.
*/
get(name: string, opts?: CookieGetOption): string | undefined;
/**
* This sets the given cookie in the response and returns
* the current context to allow chaining.If the value is omitted,
* an outbound header with an expired date is used to delete the cookie.
*/
set(name: string, value: string, opts?: CookieSetOption): this;
set(name: string, opts?: CookieSetOption): this;
}
interface ContextDelegatedRequest {
/**
* Check if the given `type(s)` is acceptable, returning
* the best match when true, otherwise `undefined`, in which
* case you should respond with 406 "Not Acceptable".
*
* The `type` value may be a single mime type string
* such as "application/json", the extension name
* such as "json" or an array `["json", "html", "text/plain"]`. When a list
* or array is given the _best_ match, if any is returned.
*
* Examples:
*
* // Accept: text/html
* this.accepts('html');
* // => "html"
*
* // Accept: text/*, application/json
* this.accepts('html');
* // => "html"
* this.accepts('text/html');
* // => "text/html"
* this.accepts('json', 'text');
* // => "json"
* this.accepts('application/json');
* // => "application/json"
*
* // Accept: text/*, application/json
* this.accepts('image/png');
* this.accepts('png');
* // => undefined
*
* // Accept: text/*;q=.5, application/json
* this.accepts(['html', 'json']);
* this.accepts('html', 'json');
* // => "json"
*/
accepts(): string[] | boolean;
accepts(...types: string[]): string | boolean;
accepts(types: string[]): string | boolean;
/**
* Return accepted encodings or best fit based on `encodings`.
*
* Given `Accept-Encoding: gzip, deflate`
* an array sorted by quality is returned:
*
* ['gzip', 'deflate']
*/
acceptsEncodings(): string[] | boolean;
acceptsEncodings(...encodings: string[]): string | boolean;
acceptsEncodings(encodings: string[]): string | boolean;
/**
* Return accepted charsets or best fit based on `charsets`.
*
* Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
* an array sorted by quality is returned:
*
* ['utf-8', 'utf-7', 'iso-8859-1']
*/
acceptsCharsets(): string[] | boolean;
acceptsCharsets(...charsets: string[]): string | boolean;
acceptsCharsets(charsets: string[]): string | boolean;
/**
* Return accepted languages or best fit based on `langs`.
*
* Given `Accept-Language: en;q=0.8, es, pt`
* an array sorted by quality is returned:
*
* ['es', 'pt', 'en']
*/
acceptsLanguages(): string[] | boolean;
acceptsLanguages(...langs: string[]): string | boolean;
acceptsLanguages(langs: string[]): string | boolean;
/**
* Check if the incoming request contains the "Content-Type"
* header field, and it contains any of the give mime `type`s.
* If there is no request body, `null` is returned.
* If there is no content type, `false` is returned.
* Otherwise, it returns the first `type` that matches.
*
* Examples:
*
* // With Content-Type: text/html; charset=utf-8
* this.is('html'); // => 'html'
* this.is('text/html'); // => 'text/html'
* this.is('text/*', 'application/json'); // => 'text/html'
*
* // When Content-Type is application/json
* this.is('json', 'urlencoded'); // => 'json'
* this.is('application/json'); // => 'application/json'
* this.is('html', 'application/*'); // => 'application/json'
*
* this.is('html'); // => false
*/
// is(): string | boolean;
is(...types: string[]): string | boolean;
is(types: string[]): string | boolean;
/**
* Return request header. If the header is not set, will return an empty
* string.
*
* The `Referrer` header field is special-cased, both `Referrer` and
* `Referer` are interchangeable.
*
* Examples:
*
* this.get('Content-Type');
* // => "text/plain"
*
* this.get('content-type');
* // => "text/plain"
*
* this.get('Something');
* // => ''
*/
get(field: string): string;
/**
* Get parsed host from event
*/
host: string;
/**
* Get parsed host from event
*/
hostname: string;
/**
* Request remote address.
*/
ip: string;
/**
* Get/Set request URL.
*/
url: string;
accept: any;
/**
* Get request pathname.
*/
path: string;
/**
* Get request method.
*/
method: string;
/**
* Return request header.
*/
header: { [key: string]: string };
/**
* Return request header, alias as request.header
*/
headers: { [key: string]: string };
/**
* Get parsed query-string.
*/
query: { [key: string]: any };
/**
* Get parsed params
*/
params: { [key: string]: string };
}
export interface FaaSHTTPRequest extends ContextDelegatedRequest {
/**
* Get parsed request body from event
*/
body: any;
/**
* Get Parsed path parameters from event
*/
pathParameters: any;
}
interface ContextDelegatedResponse {
/**
* Get/Set response status code.
*/
status: number;
/**
* Get/Set response body.
*/
body: any;
/**
* Return parsed response Content-Length when present.
* Set Content-Length field to `n`.
*/
length: number;
/**
* Return the response mime type void of
* parameters such as "charset".
*
* Set Content-Type response header with `type` through `mime.lookup()`
* when it does not contain a charset.
*
* Examples:
*
* this.type = '.html';
* this.type = 'html';
* this.type = 'json';
* this.type = 'application/json';
* this.type = 'png';
*/
type: string;
/**
* Get the Last-Modified date in Date form, if it exists.
* Set the Last-Modified date using a string or a Date.
*
* this.response.lastModified = new Date();
* this.response.lastModified = '2013-09-13';
*/
lastModified: Date;
/**
* Get/Set the ETag of a response.
* This will normalize the quotes if necessary.
*
* this.response.etag = 'md5hashsum';
* this.response.etag = '"md5hashsum"';
* this.response.etag = 'W/"123456789"';
*
* @param {String} etag
* @api public
*/
etag: string;
/**
* Set header `field` to `val`, or pass
* an object of header fields.
*
* Examples:
*
* this.set('Foo', ['bar', 'baz']);
* this.set('Accept', 'application/json');
* this.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
*/
set(field: { [key: string]: string }): void;
set(field: string, val: string | string[]): void;
/**
* Append additional header `field` with value `val`.
*
* Examples:
*
* ```
* this.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
* this.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
* this.append('Warning', '199 Miscellaneous warning');
* ```
*/
append(field: string, val: string | string[]): void;
/**
* Remove header `field`.
*/
remove(field: string): void;
/**
* Perform a 302 redirect to `url`.
*
* The string "back" is special-cased
* to provide Referrer support, when Referrer
* is not present `alt` or "/" is used.
*
* Examples:
*
* this.redirect('back');
* this.redirect('back', '/index.html');
* this.redirect('/login');
* this.redirect('http://google.com');
*/
redirect(url: string, alt?: string): void;
}
export interface FaaSHTTPResponse extends ContextDelegatedResponse {
/**
* Return response header.
*/
header: { [key: string]: any };
/**
* Return response header, alias as response.header
*/
headers: { [key: string]: any };
/**
* Check whether the response is one of the listed types.
* Pretty much the same as `this.request.is()`.
*
* @param {String|Array} types...
* @return {String|false}
* @api public
*/
// is(): string;
is(...types: string[]): string;
is(types: string[]): string;
/**
* Return response header. If the header is not set, will return an empty
* string.
*
* The `Referrer` header field is special-cased, both `Referrer` and
* `Referer` are interchangeable.
*
* Examples:
*
* this.get('Content-Type');
* // => "text/plain"
*
* this.get('content-type');
* // => "text/plain"
*
* this.get('Something');
* // => ''
*/
get(field: string): string;
}
export interface FaaSHTTPContext
extends ContextDelegatedRequest,
ContextDelegatedResponse {
/**
* Alias to this.request
*/
req: FaaSHTTPRequest;
/**
* Alias to this.Response
*/
res: FaaSHTTPResponse;
/**
* FaaS http request object
*/
request: FaaSHTTPRequest;
/**
* FaaS http response object
*/
response: FaaSHTTPResponse;
/**
* FaaS original context object.
*/
originContext: FaaSOriginContext;
/**
* FaaS original event object.
*/
originEvent: any;
/**
* FaaS Cookies Object
*/
cookies: Cookies;
/**
* Throw an error with `msg` and optional `status`
* defaulting to 500. Note that these are user-level
* errors, and the message may be exposed to the client.
*
* this.throw(403)
* this.throw('name required', 400)
* this.throw(400, 'name required')
* this.throw('something exploded')
* this.throw(new Error('invalid'), 400);
* this.throw(400, new Error('invalid'));
*
* See: https://github.com/jshttp/http-errors
*/
throw(
message: string,
code?: number,
properties?: Record<string, unknown>
): never;
throw(status: number): never;
throw(...properties: Array<number | string | Record<string, unknown>>): never;
}
export type FaaSOriginContext = FC.RequestContext | SCF.RequestContext; | the_stack |
declare module '@babel/core';
declare module '@babel/plugin-syntax-import-meta';
declare module '@babel/plugin-syntax-dynamic-import';
declare module '@babel/helper-plugin-utils';
declare module '@babel/template';
declare module '@babel/traverse' {
import * as t from 'babel-types';
export type Node = t.Node;
export class Scope {
constructor(path: NodePath, parentScope?: Scope);
path: NodePath;
block: Node;
parentBlock: Node;
parent: Scope;
// hub: Hub;
bindings: {[name: string]: Binding;};
/** Generate a unique identifier and add it to the current scope. */
generateDeclaredUidIdentifier(name?: string): t.Identifier;
/** Generate a unique identifier. */
generateUidIdentifier(name?: string): t.Identifier;
/** Generate a unique `_id1` binding. */
generateUid(name?: string): string;
/** Walks the scope tree and gathers **all** bindings. */
getAllBindings(...kinds: string[]): object;
}
export class Binding {
constructor(opts: {
existing: Binding; identifier: t.Identifier; scope: Scope; path: NodePath;
kind: 'var' | 'let' | 'const';
});
identifier: t.Identifier;
scope: Scope;
path: NodePath;
kind: 'var'|'let'|'const'|'module';
referenced: boolean;
references: number;
referencePaths: NodePath[];
constant: boolean;
constantViolations: NodePath[];
}
export class NodePath<T = Node> {
node: T;
scope: Scope;
traverse(visitor: Visitor, state?: any): void;
// ------------------------- replacement -------------------------
/**
* Replace a node with an array of multiple. This method performs the
* following steps:
*
* - Inherit the comments of first provided node with that of the current
* node.
* - Insert the provided nodes after the current node.
* - Remove the current node.
*/
replaceWithMultiple(nodes: Node[]): void;
/**
* Parse a string as an expression and replace the current node with the
* result.
*
* NOTE: This is typically not a good idea to use. Building source strings
* when transforming ASTs is an antipattern and SHOULD NOT be encouraged.
* Even if it's easier to use, your transforms will be extremely brittle.
*/
replaceWithSourceString(replacement: any): void;
/** Replace the current node with another. */
replaceWith(replacement: Node|NodePath): void;
/**
* This method takes an array of statements nodes and then explodes it
* into expressions. This method retains completion records which is
* extremely important to retain original semantics.
*/
replaceExpressionWithStatements(nodes: Node[]): Node;
replaceInline(nodes: Node|Node[]): void;
}
// The Visitor has to be generic because babel binds `this` for each property.
// `this` is usually used in babel plugins to pass plugin state from
// `pre` -> `visitor` -> `post`. An example of this can be seen in the
// official babel handbook:
// https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#-pre-and-post-in-plugins
export interface Visitor<S = Node> extends VisitNodeObject<Node> {
ArrayExpression?: VisitNode<S, t.ArrayExpression>;
AssignmentExpression?: VisitNode<S, t.AssignmentExpression>;
LVal?: VisitNode<S, t.LVal>;
Expression?: VisitNode<S, t.Expression>;
BinaryExpression?: VisitNode<S, t.BinaryExpression>;
Directive?: VisitNode<S, t.Directive>;
DirectiveLiteral?: VisitNode<S, t.DirectiveLiteral>;
BlockStatement?: VisitNode<S, t.BlockStatement>;
BreakStatement?: VisitNode<S, t.BreakStatement>;
Identifier?: VisitNode<S, t.Identifier>;
CallExpression?: VisitNode<S, t.CallExpression>;
CatchClause?: VisitNode<S, t.CatchClause>;
ConditionalExpression?: VisitNode<S, t.ConditionalExpression>;
ContinueStatement?: VisitNode<S, t.ContinueStatement>;
DebuggerStatement?: VisitNode<S, t.DebuggerStatement>;
DoWhileStatement?: VisitNode<S, t.DoWhileStatement>;
Statement?: VisitNode<S, t.Statement>;
EmptyStatement?: VisitNode<S, t.EmptyStatement>;
ExpressionStatement?: VisitNode<S, t.ExpressionStatement>;
File?: VisitNode<S, t.File>;
Program?: VisitNode<S, t.Program>;
ForInStatement?: VisitNode<S, t.ForInStatement>;
VariableDeclaration?: VisitNode<S, t.VariableDeclaration>;
ForStatement?: VisitNode<S, t.ForStatement>;
FunctionDeclaration?: VisitNode<S, t.FunctionDeclaration>;
FunctionExpression?: VisitNode<S, t.FunctionExpression>;
IfStatement?: VisitNode<S, t.IfStatement>;
LabeledStatement?: VisitNode<S, t.LabeledStatement>;
StringLiteral?: VisitNode<S, t.StringLiteral>;
NumericLiteral?: VisitNode<S, t.NumericLiteral>;
NullLiteral?: VisitNode<S, t.NullLiteral>;
BooleanLiteral?: VisitNode<S, t.BooleanLiteral>;
RegExpLiteral?: VisitNode<S, t.RegExpLiteral>;
LogicalExpression?: VisitNode<S, t.LogicalExpression>;
MemberExpression?: VisitNode<S, t.MemberExpression>;
NewExpression?: VisitNode<S, t.NewExpression>;
ObjectExpression?: VisitNode<S, t.ObjectExpression>;
ObjectMethod?: VisitNode<S, t.ObjectMethod>;
ObjectProperty?: VisitNode<S, t.ObjectProperty>;
RestElement?: VisitNode<S, t.RestElement>;
ReturnStatement?: VisitNode<S, t.ReturnStatement>;
SequenceExpression?: VisitNode<S, t.SequenceExpression>;
SwitchCase?: VisitNode<S, t.SwitchCase>;
SwitchStatement?: VisitNode<S, t.SwitchStatement>;
ThisExpression?: VisitNode<S, t.ThisExpression>;
ThrowStatement?: VisitNode<S, t.ThrowStatement>;
TryStatement?: VisitNode<S, t.TryStatement>;
UnaryExpression?: VisitNode<S, t.UnaryExpression>;
UpdateExpression?: VisitNode<S, t.UpdateExpression>;
VariableDeclarator?: VisitNode<S, t.VariableDeclarator>;
WhileStatement?: VisitNode<S, t.WhileStatement>;
WithStatement?: VisitNode<S, t.WithStatement>;
AssignmentPattern?: VisitNode<S, t.AssignmentPattern>;
ArrayPattern?: VisitNode<S, t.ArrayPattern>;
ArrowFunctionExpression?: VisitNode<S, t.ArrowFunctionExpression>;
ClassBody?: VisitNode<S, t.ClassBody>;
ClassDeclaration?: VisitNode<S, t.ClassDeclaration>;
ClassExpression?: VisitNode<S, t.ClassExpression>;
ExportAllDeclaration?: VisitNode<S, t.ExportAllDeclaration>;
ExportDefaultDeclaration?: VisitNode<S, t.ExportDefaultDeclaration>;
ExportNamedDeclaration?: VisitNode<S, t.ExportNamedDeclaration>;
Declaration?: VisitNode<S, t.Declaration>;
ExportSpecifier?: VisitNode<S, t.ExportSpecifier>;
ForOfStatement?: VisitNode<S, t.ForOfStatement>;
ImportDeclaration?: VisitNode<S, t.ImportDeclaration>;
ImportDefaultSpecifier?: VisitNode<S, t.ImportDefaultSpecifier>;
ImportNamespaceSpecifier?: VisitNode<S, t.ImportNamespaceSpecifier>;
ImportSpecifier?: VisitNode<S, t.ImportSpecifier>;
MetaProperty?: VisitNode<S, t.MetaProperty>;
ClassMethod?: VisitNode<S, t.ClassMethod>;
ObjectPattern?: VisitNode<S, t.ObjectPattern>;
SpreadElement?: VisitNode<S, t.SpreadElement>;
Super?: VisitNode<S, t.Super>;
TaggedTemplateExpression?: VisitNode<S, t.TaggedTemplateExpression>;
TemplateLiteral?: VisitNode<S, t.TemplateLiteral>;
TemplateElement?: VisitNode<S, t.TemplateElement>;
YieldExpression?: VisitNode<S, t.YieldExpression>;
AnyTypeAnnotation?: VisitNode<S, t.AnyTypeAnnotation>;
ArrayTypeAnnotation?: VisitNode<S, t.ArrayTypeAnnotation>;
BooleanTypeAnnotation?: VisitNode<S, t.BooleanTypeAnnotation>;
BooleanLiteralTypeAnnotation?: VisitNode<S, t.BooleanLiteralTypeAnnotation>;
NullLiteralTypeAnnotation?: VisitNode<S, t.NullLiteralTypeAnnotation>;
ClassImplements?: VisitNode<S, t.ClassImplements>;
ClassProperty?: VisitNode<S, t.ClassProperty>;
DeclareClass?: VisitNode<S, t.DeclareClass>;
DeclareFunction?: VisitNode<S, t.DeclareFunction>;
DeclareInterface?: VisitNode<S, t.DeclareInterface>;
DeclareModule?: VisitNode<S, t.DeclareModule>;
DeclareTypeAlias?: VisitNode<S, t.DeclareTypeAlias>;
DeclareVariable?: VisitNode<S, t.DeclareVariable>;
ExistentialTypeParam?: VisitNode<S, t.ExistentialTypeParam>;
FunctionTypeAnnotation?: VisitNode<S, t.FunctionTypeAnnotation>;
FunctionTypeParam?: VisitNode<S, t.FunctionTypeParam>;
GenericTypeAnnotation?: VisitNode<S, t.GenericTypeAnnotation>;
InterfaceExtends?: VisitNode<S, t.InterfaceExtends>;
InterfaceDeclaration?: VisitNode<S, t.InterfaceDeclaration>;
IntersectionTypeAnnotation?: VisitNode<S, t.IntersectionTypeAnnotation>;
MixedTypeAnnotation?: VisitNode<S, t.MixedTypeAnnotation>;
NullableTypeAnnotation?: VisitNode<S, t.NullableTypeAnnotation>;
NumericLiteralTypeAnnotation?: VisitNode<S, t.NumericLiteralTypeAnnotation>;
NumberTypeAnnotation?: VisitNode<S, t.NumberTypeAnnotation>;
StringLiteralTypeAnnotation?: VisitNode<S, t.StringLiteralTypeAnnotation>;
StringTypeAnnotation?: VisitNode<S, t.StringTypeAnnotation>;
ThisTypeAnnotation?: VisitNode<S, t.ThisTypeAnnotation>;
TupleTypeAnnotation?: VisitNode<S, t.TupleTypeAnnotation>;
TypeofTypeAnnotation?: VisitNode<S, t.TypeofTypeAnnotation>;
TypeAlias?: VisitNode<S, t.TypeAlias>;
TypeAnnotation?: VisitNode<S, t.TypeAnnotation>;
TypeCastExpression?: VisitNode<S, t.TypeCastExpression>;
TypeParameterDeclaration?: VisitNode<S, t.TypeParameterDeclaration>;
TypeParameterInstantiation?: VisitNode<S, t.TypeParameterInstantiation>;
ObjectTypeAnnotation?: VisitNode<S, t.ObjectTypeAnnotation>;
ObjectTypeCallProperty?: VisitNode<S, t.ObjectTypeCallProperty>;
ObjectTypeIndexer?: VisitNode<S, t.ObjectTypeIndexer>;
ObjectTypeProperty?: VisitNode<S, t.ObjectTypeProperty>;
QualifiedTypeIdentifier?: VisitNode<S, t.QualifiedTypeIdentifier>;
UnionTypeAnnotation?: VisitNode<S, t.UnionTypeAnnotation>;
VoidTypeAnnotation?: VisitNode<S, t.VoidTypeAnnotation>;
JSXAttribute?: VisitNode<S, t.JSXAttribute>;
JSXIdentifier?: VisitNode<S, t.JSXIdentifier>;
JSXNamespacedName?: VisitNode<S, t.JSXNamespacedName>;
JSXElement?: VisitNode<S, t.JSXElement>;
JSXExpressionContainer?: VisitNode<S, t.JSXExpressionContainer>;
JSXClosingElement?: VisitNode<S, t.JSXClosingElement>;
JSXMemberExpression?: VisitNode<S, t.JSXMemberExpression>;
JSXOpeningElement?: VisitNode<S, t.JSXOpeningElement>;
JSXEmptyExpression?: VisitNode<S, t.JSXEmptyExpression>;
JSXSpreadAttribute?: VisitNode<S, t.JSXSpreadAttribute>;
JSXText?: VisitNode<S, t.JSXText>;
Noop?: VisitNode<S, t.Noop>;
ParenthesizedExpression?: VisitNode<S, t.ParenthesizedExpression>;
AwaitExpression?: VisitNode<S, t.AwaitExpression>;
BindExpression?: VisitNode<S, t.BindExpression>;
Decorator?: VisitNode<S, t.Decorator>;
DoExpression?: VisitNode<S, t.DoExpression>;
ExportDefaultSpecifier?: VisitNode<S, t.ExportDefaultSpecifier>;
ExportNamespaceSpecifier?: VisitNode<S, t.ExportNamespaceSpecifier>;
RestProperty?: VisitNode<S, t.RestProperty>;
SpreadProperty?: VisitNode<S, t.SpreadProperty>;
Binary?: VisitNode<S, t.Binary>;
Scopable?: VisitNode<S, t.Scopable>;
BlockParent?: VisitNode<S, t.BlockParent>;
Block?: VisitNode<S, t.Block>;
Terminatorless?: VisitNode<S, t.Terminatorless>;
CompletionStatement?: VisitNode<S, t.CompletionStatement>;
Conditional?: VisitNode<S, t.Conditional>;
Loop?: VisitNode<S, t.Loop>;
While?: VisitNode<S, t.While>;
ExpressionWrapper?: VisitNode<S, t.ExpressionWrapper>;
For?: VisitNode<S, t.For>;
ForXStatement?: VisitNode<S, t.ForXStatement>;
Function?: VisitNode<S, t.Function>;
FunctionParent?: VisitNode<S, t.FunctionParent>;
Pureish?: VisitNode<S, t.Pureish>;
Literal?: VisitNode<S, t.Literal>;
Immutable?: VisitNode<S, t.Immutable>;
UserWhitespacable?: VisitNode<S, t.UserWhitespacable>;
Method?: VisitNode<S, t.Method>;
ObjectMember?: VisitNode<S, t.ObjectMember>;
Property?: VisitNode<S, t.Property>;
UnaryLike?: VisitNode<S, t.UnaryLike>;
Pattern?: VisitNode<S, t.Pattern>;
Class?: VisitNode<S, t.Class>;
ModuleDeclaration?: VisitNode<S, t.ModuleDeclaration>;
ExportDeclaration?: VisitNode<S, t.ExportDeclaration>;
ModuleSpecifier?: VisitNode<S, t.ModuleSpecifier>;
Flow?: VisitNode<S, t.Flow>;
FlowBaseAnnotation?: VisitNode<S, t.FlowBaseAnnotation>;
FlowDeclaration?: VisitNode<S, t.FlowDeclaration>;
JSX?: VisitNode<S, t.JSX>;
Scope?: VisitNode<S, t.Scopable>;
}
export type VisitNode<T, P> = VisitNodeFunction<T, P>|VisitNodeObject<T>;
export type VisitNodeFunction<T, P> =
(this: T, path: NodePath<P>, state: any) => void;
export interface VisitNodeObject<T> {
enter?(path: NodePath<T>, state: any): void;
exit?(path: NodePath<T>, state: any): void;
}
} | the_stack |
export abstract class Condition {
/**
* Matches if variable is present
*/
public static isPresent(variable: string): Condition {
return new VariableComparison(variable, ComparisonOperator.IsPresent, true);
}
/**
* Matches if variable is not present
*/
public static isNotPresent(variable: string): Condition {
return new VariableComparison(variable, ComparisonOperator.IsPresent, false);
}
/**
* Matches if variable is a string
*/
public static isString(variable: string): Condition {
return new VariableComparison(variable, ComparisonOperator.IsString, true);
}
/**
* Matches if variable is not a string
*/
public static isNotString(variable: string): Condition {
return new VariableComparison(variable, ComparisonOperator.IsString, false);
}
/**
* Matches if variable is numeric
*/
public static isNumeric(variable: string): Condition {
return new VariableComparison(variable, ComparisonOperator.IsNumeric, true);
}
/**
* Matches if variable is not numeric
*/
public static isNotNumeric(variable: string): Condition {
return new VariableComparison(variable, ComparisonOperator.IsNumeric, false);
}
/**
* Matches if variable is boolean
*/
public static isBoolean(variable: string): Condition {
return new VariableComparison(variable, ComparisonOperator.IsBoolean, true);
}
/**
* Matches if variable is not boolean
*/
public static isNotBoolean(variable: string): Condition {
return new VariableComparison(variable, ComparisonOperator.IsBoolean, false);
}
/**
* Matches if variable is a timestamp
*/
public static isTimestamp(variable: string): Condition {
return new VariableComparison(variable, ComparisonOperator.IsTimestamp, true);
}
/**
* Matches if variable is not a timestamp
*/
public static isNotTimestamp(variable: string): Condition {
return new VariableComparison(variable, ComparisonOperator.IsTimestamp, false);
}
/**
* Matches if variable is not null
*/
public static isNotNull(variable: string): Condition {
return new VariableComparison(variable, ComparisonOperator.IsNull, false);
}
/**
* Matches if variable is Null
*/
public static isNull(variable: string): Condition {
return new VariableComparison(variable, ComparisonOperator.IsNull, true);
}
/**
* Matches if a boolean field has the given value
*/
public static booleanEquals(variable: string, value: boolean): Condition {
return new VariableComparison(variable, ComparisonOperator.BooleanEquals, value);
}
/**
* Matches if a boolean field equals to a value at a given mapping path
*/
public static booleanEqualsJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.BooleanEqualsPath, value);
}
/**
* Matches if a string field equals to a value at a given mapping path
*/
public static stringEqualsJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.StringEqualsPath, value);
}
/**
* Matches if a string field has the given value
*/
public static stringEquals(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.StringEquals, value);
}
/**
* Matches if a string field sorts before a given value
*/
public static stringLessThan(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.StringLessThan, value);
}
/**
* Matches if a string field sorts before a given value at a particular mapping
*/
public static stringLessThanJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.StringLessThanPath, value);
}
/**
* Matches if a string field sorts equal to or before a given value
*/
public static stringLessThanEquals(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.StringLessThanEquals, value);
}
/**
* Matches if a string field sorts equal to or before a given mapping
*/
public static stringLessThanEqualsJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.StringLessThanEqualsPath, value);
}
/**
* Matches if a string field sorts after a given value
*/
public static stringGreaterThan(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.StringGreaterThan, value);
}
/**
* Matches if a string field sorts after a value at a given mapping path
*/
public static stringGreaterThanJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.StringGreaterThanPath, value);
}
/**
* Matches if a string field sorts after or equal to value at a given mapping path
*/
public static stringGreaterThanEqualsJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.StringGreaterThanEqualsPath, value);
}
/**
* Matches if a string field sorts after or equal to a given value
*/
public static stringGreaterThanEquals(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.StringGreaterThanEquals, value);
}
/**
* Matches if a numeric field has the given value
*/
public static numberEquals(variable: string, value: number): Condition {
return new VariableComparison(variable, ComparisonOperator.NumericEquals, value);
}
/**
* Matches if a numeric field has the value in a given mapping path
*/
public static numberEqualsJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.NumericEqualsPath, value);
}
/**
* Matches if a numeric field is less than the given value
*/
public static numberLessThan(variable: string, value: number): Condition {
return new VariableComparison(variable, ComparisonOperator.NumericLessThan, value);
}
/**
* Matches if a numeric field is less than the value at the given mapping path
*/
public static numberLessThanJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.NumericLessThanPath, value);
}
/**
* Matches if a numeric field is less than or equal to the given value
*/
public static numberLessThanEquals(variable: string, value: number): Condition {
return new VariableComparison(variable, ComparisonOperator.NumericLessThanEquals, value);
}
/**
* Matches if a numeric field is less than or equal to the numeric value at given mapping path
*/
public static numberLessThanEqualsJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.NumericLessThanEqualsPath, value);
}
/**
* Matches if a numeric field is greater than the given value
*/
public static numberGreaterThan(variable: string, value: number): Condition {
return new VariableComparison(variable, ComparisonOperator.NumericGreaterThan, value);
}
/**
* Matches if a numeric field is greater than the value at a given mapping path
*/
public static numberGreaterThanJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.NumericGreaterThanPath, value);
}
/**
* Matches if a numeric field is greater than or equal to the given value
*/
public static numberGreaterThanEquals(variable: string, value: number): Condition {
return new VariableComparison(variable, ComparisonOperator.NumericGreaterThanEquals, value);
}
/**
* Matches if a numeric field is greater than or equal to the value at a given mapping path
*/
public static numberGreaterThanEqualsJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.NumericGreaterThanEqualsPath, value);
}
/**
* Matches if a timestamp field is the same time as the given timestamp
*/
public static timestampEquals(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.TimestampEquals, value);
}
/**
* Matches if a timestamp field is the same time as the timestamp at a given mapping path
*/
public static timestampEqualsJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.TimestampEqualsPath, value);
}
/**
* Matches if a timestamp field is before the given timestamp
*/
public static timestampLessThan(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.TimestampLessThan, value);
}
/**
* Matches if a timestamp field is before the timestamp at a given mapping path
*/
public static timestampLessThanJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.TimestampLessThanPath, value);
}
/**
* Matches if a timestamp field is before or equal to the given timestamp
*/
public static timestampLessThanEquals(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.TimestampLessThanEquals, value);
}
/**
* Matches if a timestamp field is before or equal to the timestamp at a given mapping path
*/
public static timestampLessThanEqualsJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.TimestampLessThanEqualsPath, value);
}
/**
* Matches if a timestamp field is after the given timestamp
*/
public static timestampGreaterThan(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.TimestampGreaterThan, value);
}
/**
* Matches if a timestamp field is after the timestamp at a given mapping path
*/
public static timestampGreaterThanJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.TimestampGreaterThanPath, value);
}
/**
* Matches if a timestamp field is after or equal to the given timestamp
*/
public static timestampGreaterThanEquals(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.TimestampGreaterThanEquals, value);
}
/**
* Matches if a timestamp field is after or equal to the timestamp at a given mapping path
*/
public static timestampGreaterThanEqualsJsonPath(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.TimestampGreaterThanEqualsPath, value);
}
/**
* Matches if a field matches a string pattern that can contain a wild card (*) e.g: log-*.txt or *LATEST*.
* No other characters other than "*" have any special meaning - * can be escaped: \\*
*/
public static stringMatches(variable: string, value: string): Condition {
return new VariableComparison(variable, ComparisonOperator.StringMatches, value);
}
/**
* Combine two or more conditions with a logical AND
*/
public static and(...conditions: Condition[]): Condition {
return new CompoundCondition(CompoundOperator.And, ...conditions);
}
/**
* Combine two or more conditions with a logical OR
*/
public static or(...conditions: Condition[]): Condition {
return new CompoundCondition(CompoundOperator.Or, ...conditions);
}
/**
* Negate a condition
*/
public static not(condition: Condition): Condition {
return new NotCondition(condition);
}
/**
* Render Amazon States Language JSON for the condition
*/
public abstract renderCondition(): any;
}
/**
* Comparison Operator types
*/
enum ComparisonOperator {
StringEquals,
StringEqualsPath,
StringLessThan,
StringLessThanPath,
StringGreaterThan,
StringGreaterThanPath,
StringLessThanEquals,
StringLessThanEqualsPath,
StringGreaterThanEquals,
StringGreaterThanEqualsPath,
NumericEquals,
NumericEqualsPath,
NumericLessThan,
NumericLessThanPath,
NumericGreaterThan,
NumericGreaterThanPath,
NumericLessThanEquals,
NumericLessThanEqualsPath,
NumericGreaterThanEquals,
NumericGreaterThanEqualsPath,
BooleanEquals,
BooleanEqualsPath,
TimestampEquals,
TimestampEqualsPath,
TimestampLessThan,
TimestampLessThanPath,
TimestampGreaterThan,
TimestampGreaterThanPath,
TimestampLessThanEquals,
TimestampLessThanEqualsPath,
TimestampGreaterThanEquals,
TimestampGreaterThanEqualsPath,
IsNull,
IsBoolean,
IsNumeric,
IsString,
IsTimestamp,
IsPresent,
StringMatches,
}
/**
* Compound Operator types
*/
enum CompoundOperator {
And,
Or,
}
/**
* Scalar comparison
*/
class VariableComparison extends Condition {
constructor(private readonly variable: string, private readonly comparisonOperator: ComparisonOperator, private readonly value: any) {
super();
if (!/^\$|(\$[.[])/.test(variable)) {
throw new Error(`Variable reference must be '$', start with '$.', or start with '$[', got '${variable}'`);
}
}
public renderCondition(): any {
return {
Variable: this.variable,
[ComparisonOperator[this.comparisonOperator]]: this.value,
};
}
}
/**
* Logical compound condition
*/
class CompoundCondition extends Condition {
private readonly conditions: Condition[];
constructor(private readonly operator: CompoundOperator, ...conditions: Condition[]) {
super();
this.conditions = conditions;
if (conditions.length === 0) {
throw new Error('Must supply at least one inner condition for a logical combination');
}
}
public renderCondition(): any {
return {
[CompoundOperator[this.operator]]: this.conditions.map(c => c.renderCondition()),
};
}
}
/**
* Logical unary condition
*/
class NotCondition extends Condition {
constructor(private readonly comparisonOperation: Condition) {
super();
}
public renderCondition(): any {
return {
Not: this.comparisonOperation.renderCondition(),
};
}
} | the_stack |
import "@logseq/libs";
import {
BlockEntity,
BlockPageName,
BlockUUID,
ILSPluginUser,
PageEntity,
} from "@logseq/libs/dist/LSPlugin";
import { N, TempCache } from "./type";
import { schemaVersion } from "../../package.json";
import hotkeys from "hotkeys-js";
import { useCommandStore } from "@/stores/command";
import { useColorStore } from "@/stores/color";
import { useSearchStore } from "@/stores/search";
export const clearBlocksHighlight = async (blocks: BlockEntity[]) => {
for (const block of blocks) {
const regex = /<mark class="vim-shortcuts-highlight">(.*?)<\/mark>/;
if (regex.test(block.content)) {
const content = block.content.replace(regex, "$1");
await logseq.Editor.updateBlock(block.uuid, content);
}
if (block.children.length > 0) {
await clearBlocksHighlight(block.children as BlockEntity[]);
}
}
};
export const clearCurrentPageBlocksHighlight = async () => {
let page = await logseq.Editor.getCurrentPage();
let blocks;
if (page) {
blocks = await logseq.Editor.getCurrentPageBlocksTree();
} else {
const block = await logseq.Editor.getCurrentBlock();
if (block) {
page = await logseq.Editor.getPage(block.page.id);
blocks = await logseq.Editor.getPageBlocksTree(page.name);
}
}
if (blocks && blocks.length > 0) {
await clearBlocksHighlight(blocks);
}
};
export async function createPageIfNotExists(pageName): Promise<PageEntity> {
let page = await logseq.Editor.getPage(pageName);
if (!page) {
page = await logseq.Editor.createPage(
pageName,
{},
{
createFirstBlock: true,
redirect: false,
}
);
}
return page;
}
export async function setHotkeys(logseq: ILSPluginUser) {
hotkeys("esc", () => {
hideMainUI();
return false;
});
hotkeys("command+shift+;, ctrl+shift+;, shift+;", () => {
const $input = document.querySelector(
".command-input input"
) as HTMLInputElement;
$input && $input.focus();
return false;
});
}
export async function getGraphKey(key: string): Promise<string> {
const graph = await logseq.App.getCurrentGraph();
return (
"logseq-plugin-vim-shortcuts:" +
key +
":" +
schemaVersion +
":" +
(graph?.path ?? "nograph")
);
}
export function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
const tempCache: TempCache = {
clipboard: "",
lastPage: "",
visualMode: false,
};
export const writeClipboard = (content: string) => {
tempCache.clipboard = content;
};
export const readClipboard = (): string => {
return tempCache.clipboard;
};
export const setVisualMode = (visualMode: boolean, message = true) => {
if (visualMode) {
message && logseq.App.showMsg("Visual block mode enabled", "success");
// logseq.App.registerUIItem("pagebar", {
// key: "vim-shortcut-mode",
// template: `
// <span class="">
// <a title="Visual mode" class="button" data-on-click="">
// Visual
// </a>
// </span>
// `,
// });
} else {
message && logseq.App.showMsg("Visual block mode disabled", "success");
// logseq.App.registerUIItem("pagebar", {
// key: "vim-shortcut-mode",
// template: `
// <span class="">
// <a title="Non-Visual mode" class="button" data-on-click="">
// Normal
// </a>
// </span>
// `,
// });
}
tempCache.visualMode = visualMode;
};
export const getVisualMode = (): boolean => {
return tempCache.visualMode;
};
const numberCache: N = {
n: 1,
lastChange: null,
};
export const resetNumber = () => {
numberCache.n = 1;
numberCache.lastChange = null;
};
export const getNumber = (): number => {
const now = new Date();
if (
numberCache.lastChange &&
now.getTime() - numberCache.lastChange.getTime() >= 10000
) {
resetNumber();
}
return numberCache.n;
};
export const setNumber = (n: number) => {
const now = new Date();
if (numberCache.lastChange === null) {
if (n > 0) {
numberCache.n = n;
numberCache.lastChange = now;
}
} else {
if (now.getTime() - numberCache.lastChange.getTime() >= 1000) {
numberCache.n = n;
numberCache.lastChange = now;
} else {
numberCache.n = numberCache.n * 10 + n;
numberCache.lastChange = now;
}
}
};
let commandHistory: string[] = [];
let commandCursor = 0;
export const pushCommandHistory = (command: string) => {
commandHistory.unshift(command);
commandCursor = 0;
if (commandHistory.length > 1000) {
commandHistory.pop();
}
};
export const getCommandFromHistoryBack = (): string => {
commandCursor = commandCursor % commandHistory.length;
const command = commandHistory[commandCursor] || "";
commandCursor++;
return command;
};
export const getCommandFromHistoryForward = (): string => {
commandCursor =
commandCursor < 0 ? commandCursor + commandHistory.length : commandCursor;
const command = commandHistory[commandCursor] || "";
commandCursor--;
return command;
};
export const resetCommandCursor = () => {
commandCursor = 0;
};
export const showMainUI = (inputVisible) => {
const commandStore = useCommandStore();
commandStore.setVisible(inputVisible);
logseq.showMainUI({
autoFocus: true,
});
};
export const hideMainUI = () => {
const commandStore = useCommandStore();
commandStore.emptyInput();
commandStore.hide();
const searchStore = useSearchStore();
searchStore.hide();
const colorStore = useColorStore();
colorStore.hide();
logseq.hideMainUI({
restoreEditingCursor: true,
});
logseq.Editor.restoreEditingCursor();
resetCommandCursor();
};
let markCache: {
[key: string]: {
page: string;
block?: BlockUUID | undefined;
};
} = {};
export const setMark = async (
number: number,
page: BlockPageName,
block: BlockUUID | undefined = undefined
) => {
markCache[number] = {
page,
block,
};
const graphKey = await getGraphKey("markCache");
localStorage.setItem(graphKey, JSON.stringify(markCache));
};
export const loadMarks = async () => {
const graphKey = await getGraphKey("markCache");
const markCacheStr = localStorage.getItem(graphKey);
if (markCacheStr) {
markCache = JSON.parse(markCacheStr) || {};
} else {
markCache = {};
}
};
export const getMark = (number: number) => {
return markCache[number] || undefined;
};
export const getMarks = () => {
return markCache;
};
export const delMark = async (number: string) => {
delete markCache[number];
const graphKey = await getGraphKey("markCache");
localStorage.setItem(graphKey, JSON.stringify(markCache));
};
export const clearMarks = async () => {
markCache = {};
const graphKey = await getGraphKey("markCache");
localStorage.setItem(graphKey, JSON.stringify(markCache));
};
const debugMode = false;
export const debug = (msg: string, status = "success") => {
if (debugMode) {
// logseq.App.showMsg(msg, status);
console.log(msg);
}
};
const settingsVersion = "v2";
export const defaultSettings = {
keyBindings: {
bottom: "shift+g",
changeCase: "mod+shift+u",
changeCaseUpper: "g shift+u",
changeCaseLower: "g u",
collapse: "z m",
collapseAll: "z shift+m",
copyCurrentBlockContent: "y y",
copyCurrentBlockRef: "shift+y",
deleteCurrentBlock: "d d",
down: "j",
extend: "z o",
extendAll: "z shift+o",
highlightFocusIn: "shift+l",
highlightFocusOut: "shift+h",
indent: "l",
insert: ["i", "a"],
insertBefore: "shift+i",
nextNewBlock: "o",
nextSibling: "shift+j",
outdent: "h",
pasteNext: "p",
pastePrev: "shift+p",
prevNewBlock: "shift+o",
prevSibling: "shift+k",
redo: "ctrl+r",
search: "/",
searchPrev: "shift+n",
searchNext: "n",
searchCleanup: "s q",
searchBaidu: "s b",
searchGithub: "s h",
searchGoogle: "s g",
searchStackoverflow: "s s",
searchWikipedia: "s e",
searchYoutube: "s y",
top: "shift+t",
undo: "u",
up: "k",
exitEditing: ["mod+j mod+j", "ctrl+["],
jumpInto: "mod+shift+enter",
joinNextLine: "mod+alt+j",
toggleVisualMode: "ctrl+v",
markSave: "m",
markJump: "'",
markJumpSidebar: "mod+'",
increase: "ctrl+a",
decrease: "ctrl+x",
cut: "x",
cutWord: "shift+x",
command: ["mod+alt+;", "mod+shift+;"],
emoji: "mod+/",
},
settingsVersion,
disabled: false,
};
export type DefaultSettingsType = typeof defaultSettings;
export const initSettings = () => {
let settings = logseq.settings;
const shouldUpdateSettings =
!settings || settings.settingsVersion != defaultSettings.settingsVersion;
if (shouldUpdateSettings) {
settings = defaultSettings;
logseq.updateSettings(settings);
}
};
export const getSettings = (): DefaultSettingsType => {
let settings = logseq.settings;
const merged = Object.assign(defaultSettings, settings);
return merged;
};
export const scrollToBlockInPage = (
pageName: BlockPageName,
blockId: BlockUUID
) => {
logseq.Editor.scrollToBlockInPage(pageName, blockId);
};
export const getCurrentBlockUUID = async (): Promise<BlockUUID | undefined> => {
let block = await logseq.Editor.getCurrentBlock();
return block?.uuid;
};
export const getCurrentPage = async () => {
let page = await logseq.Editor.getCurrentPage();
if (!page) {
let blockUUID = await getCurrentBlockUUID();
if (blockUUID) {
let block = await logseq.Editor.getBlock(blockUUID);
if (block?.page.id) {
page = await logseq.Editor.getPage(block.page.id);
}
}
}
if (page?.name) {
tempCache.lastPage = page.name;
}
return page;
};
export function hexToRgb(hex) {
const hexCode = hex.charAt(0) === "#" ? hex.substr(1, 6) : hex;
const hexR = parseInt(hexCode.substr(0, 2), 16);
const hexG = parseInt(hexCode.substr(2, 2), 16);
const hexB = parseInt(hexCode.substr(4, 2), 16);
return [hexR, hexG, hexB];
}
export function filterDarkColor(hexColor) {
const [r, g, b] = hexToRgb(hexColor);
return r * 0.299 + g * 0.587 + b * 0.114 < 150;
} | the_stack |
import { FunctionComponent, useCallback, useEffect, useRef } from 'react';
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import Peer from 'simple-peer';
import { MAX_BANDWIDTH, MIN_BANDWIDTH } from 'utils/settings';
import { transformSdp, blankVideo } from 'utils/helper';
import {
addMessageSelector,
preferencesState,
remoteStreamsState,
userStreamState,
PeerData,
Message,
displayStreamState,
addRemoteStreamsSelector,
RemoteStream,
} from 'store';
import { VitaPeer } from 'react-app-env';
import toast, {
Timeout,
ToastType,
} from 'components/VideoCallComponents/toast';
import { socket } from 'service/socket';
interface SignalMessage {
from: string;
signal?: any;
}
interface PeerProps extends Peer.Options {
partnerId: string;
partnerName?: string;
}
interface PeerInternals extends Peer.Instance {
_remoteStreams?: MediaStream[];
_remoteTracks?: {
stream: MediaStream;
track: MediaStreamTrack;
}[];
_connected?: boolean;
}
type ErrorCodes =
| 'ERR_WEBRTC_SUPPORT'
| 'ERR_CREATE_OFFER'
| 'ERR_CREATE_ANSWER'
| 'ERR_SET_LOCAL_DESCRIPTION'
| 'ERR_SET_REMOTE_DESCRIPTION'
| 'ERR_ADD_ICE_CANDIDATE'
| 'ERR_ICE_CONNECTION_FAILURE'
| 'ERR_SIGNALING'
| 'ERR_DATA_CHANNEL'
| 'ERR_CONNECTION_FAILURE';
interface PeerError {
code: ErrorCodes;
}
const createSdpTransform = (badwidth: number) => (sdp: string) =>
transformSdp(sdp, badwidth);
const PeerComponent: FunctionComponent<PeerProps> = (props) => {
const addMessage = useSetRecoilState(addMessageSelector);
// Get the setter function for getting the copy of remote streams
const addRemoteStreams = useSetRecoilState(addRemoteStreamsSelector);
const preferences = useRecoilValue(preferencesState); // Name
const { partnerId, partnerName, ...opts } = props;
const [remoteStreams, setRemoteStreams] = useRecoilState(remoteStreamsState);
const remoteStreamRef = useRef(new MediaStream());
const userStream = useRecoilValue(userStreamState);
const displayStream = useRecoilValue(displayStreamState);
const peerRef = useRef<Peer.Instance>();
if (!peerRef.current) {
const LEN = (window.vitaPeers?.length || 0) + 1;
let bandwidth = MAX_BANDWIDTH / Math.sqrt(LEN);
if (bandwidth < MIN_BANDWIDTH) bandwidth = MIN_BANDWIDTH;
peerRef.current = new Peer({
sdpTransform: createSdpTransform(bandwidth) as any,
...opts,
});
}
const saveInstance = () => {
const peer = peerRef.current as Peer.Instance;
const vitaPeer: VitaPeer = { peer, partnerId };
if (!window.vitaPeers) window.vitaPeers = [vitaPeer];
// Remove old copy
window.vitaPeers = window.vitaPeers.filter(
(p) => p.partnerId !== partnerId,
);
// Update
window.vitaPeers.push(vitaPeer);
};
saveInstance();
const onMetaData = useCallback(
(str: string) => {
try {
const data: PeerData = JSON.parse(str);
if (data.metadata?.state === 'NO_STREAM') {
remoteStreamRef.current.getTracks().forEach((t) => {
t.stop();
remoteStreamRef.current.removeTrack(t);
});
setRemoteStreams(
remoteStreams.filter((r) => r.partnerId !== partnerId),
);
}
// If (data.metadata?.state === 'ONLY_DISPLAY') {
// }
} catch (err) {
// Consoel.err
}
},
[remoteStreams, setRemoteStreams, partnerId],
);
const onRemoteStream = useCallback(
(stream: MediaStream, dontStopPrev?: boolean) => {
// Console.log('onstream', dontStopPrev, stream.getTracks())
const remoteStream = remoteStreamRef.current;
// Remove prev tracks
if (!dontStopPrev) {
remoteStream.getTracks().forEach((t) => {
if (t.kind === 'video') t.stop();
remoteStream.removeTrack(t);
});
}
const toAdd: RemoteStream[] = [];
// Check for display stream
const videoTracks = stream.getVideoTracks();
const displayTrack = videoTracks[1] as MediaStreamTrack | undefined; // TODO 1?
if (displayTrack) {
stream.removeTrack(displayTrack);
const rdStream = new MediaStream([displayTrack]);
// If this track already exists in dispay stream, return
if (
remoteStreams.find(
(rs) =>
rs.isDisplay &&
rs.partnerId === partnerId &&
rs.stream
.getVideoTracks()
.find(
(vt) =>
vt.id === displayTrack.id &&
vt.enabled &&
vt.readyState === 'live',
),
)
)
return;
// Push new one
toAdd.push({
stream: rdStream,
isDisplay: true,
partnerId,
partnerName,
});
}
// Add new tracks
stream.getTracks().forEach((t) => {
if (
dontStopPrev &&
remoteStream.getTracks().find((rt) => rt.id === t.id)
)
return;
remoteStream.addTrack(t);
});
toAdd.unshift({
stream: remoteStream,
partnerId,
partnerName,
});
addRemoteStreams(toAdd);
},
[addRemoteStreams, remoteStreams, partnerId, partnerName],
);
// Just to make sure that every track is loaded
const onTrack = useCallback(
(track: MediaStreamTrack, stream: MediaStream) => {
const pr = window.vitaPeers?.find((p) => p.partnerId === partnerId)
?.peer as PeerInternals | undefined;
const currStream = pr?._remoteStreams?.find((r) => r.active);
if (!currStream || currStream.id !== stream.id) return;
// Proceed only for tracks belonging to currently active stream
// let tr = currStream
// .getTracks()
// .filter(t => t.enabled && t.readyState === 'live')
let tr =
pr?._remoteTracks
?.filter(({ stream: s }) => s.id === currStream.id)
.map((o) => o.track)
.filter((t) => t.enabled && t.readyState === 'live') || [];
if (!tr.find((t) => t.id === track.id)) {
tr = tr.concat(track);
}
const compTr = [
...remoteStreamRef.current.getTracks(),
remoteStreams
.find((r) => r.isDisplay && r.partnerId === partnerId)
?.stream.getVideoTracks()[0],
].filter(Boolean) as MediaStreamTrack[];
// Console.log({ tr, compTr })
if (tr.length > compTr.length) {
const strm = new MediaStream(tr);
onRemoteStream(strm, true);
}
},
[onRemoteStream, remoteStreams, partnerId],
);
// Setting up peer connections
useEffect(() => {
const peer = peerRef.current as Peer.Instance;
const onMessageRecieved = (msg: SignalMessage) => {
const { signal, from } = msg;
if (signal && from === partnerId) {
try {
peer.signal(signal);
} catch (err) {
// Console.error(err)
}
}
};
const onConnected = () => {
toast(`Connected with peer ${partnerName}`, { type: ToastType.success });
};
const onClose = () => {
toast(`Connection closed with peer ${partnerName}`, {
type: ToastType.severeWarning,
});
socket.emit('person_left', { sessionId: partnerId });
};
const onError = (err: PeerError) => {
if (err.code === 'ERR_WEBRTC_SUPPORT') {
toast(`No WebRTC support, on your browser (IE+7)`, {
type: ToastType.error,
});
} else if (err.code === 'ERR_CONNECTION_FAILURE') {
toast(`WebRTC connection failure`, {
type: ToastType.error,
});
}
};
const onLocalSignal = (signal: any) => {
socket.send({
to: partnerId,
signal,
});
};
const onDataRecieved = (str: string) => {
try {
const data: PeerData = JSON.parse(str);
if (data.message) {
const msg: Message = {
...data.message,
mine: false,
};
addMessage([msg]);
toast(`New message from ${msg.author}: ${msg.text}`, {
type: ToastType.info,
});
}
} catch (err) {
toast(`Peer data error`, {
type: ToastType.error,
autoClose: Timeout.SHORT,
});
}
};
peer.on('stream', onRemoteStream);
peer.on('signal', onLocalSignal);
peer.on('data', onDataRecieved);
peer.on('data', onMetaData);
peer.on('connect', onConnected);
peer.on('close', onClose);
peer.on('error', onError);
peer.on('track', onTrack);
socket.on('message', onMessageRecieved);
return () => {
peer.off('stream', onRemoteStream);
peer.off('signal', onLocalSignal);
peer.off('connect', onConnected);
peer.off('data', onDataRecieved);
peer.off('data', onMetaData);
peer.off('close', onClose);
peer.off('error', onError);
peer.off('track', onTrack);
socket.off('message', onMessageRecieved);
};
}, [
onRemoteStream,
socket,
partnerId,
addMessage,
onMetaData,
onTrack,
partnerName,
]);
useEffect(() => {
const peer = peerRef.current as Peer.Instance;
const displayVideoTracks = displayStream?.getVideoTracks();
const tracks = [
...(userStream?.getTracks() || []),
...(displayVideoTracks || []),
];
// Hack so that the other end detects display stream
if (displayVideoTracks?.length && !userStream?.getVideoTracks().length) {
tracks.unshift(blankVideo());
}
const stream = new MediaStream(tracks);
try {
if (!tracks.length) {
const msg: PeerData = { metadata: { state: 'NO_STREAM' } };
peer.send(JSON.stringify(msg));
} else {
peer.addStream(stream);
}
} catch (err) {
// Console.error(err)
}
return () => {
try {
peer.removeStream(stream);
} catch (err) {
// Console.error(err)
}
};
}, [userStream, displayStream]);
// Send proposal to partner to join
useEffect(() => {
if (!opts.initiator) {
socket.send({
to: partnerId,
proposal: true,
name: preferences.name,
});
}
}, []);
// Destroy peer and remote stream when component exits
// CLEAN UP FUNCTION
useEffect(
() => () => {
peerRef.current?.destroy();
remoteStreamRef.current.getTracks().forEach((t) => {
t.stop();
remoteStreamRef.current.removeTrack(t);
});
},
[],
);
return null;
};
export default PeerComponent; | the_stack |
import { CoreConstants } from '@/core/constants';
import { Injectable } from '@angular/core';
import { CoreError } from '@classes/errors/error';
import { CoreSite, CoreSiteWSPreSets } from '@classes/site';
import { CoreCourseCommonModWSOptions } from '@features/course/services/course';
import { CoreCourseLogHelper } from '@features/course/services/log-helper';
import { CoreFilepool } from '@services/filepool';
import { CoreSites, CoreSitesCommonWSOptions, CoreSitesReadingStrategy } from '@services/sites';
import { CoreSync } from '@services/sync';
import { CoreTextUtils } from '@services/utils/text';
import { CoreTimeUtils } from '@services/utils/time';
import { CoreUrlUtils } from '@services/utils/url';
import { CoreUtils } from '@services/utils/utils';
import { CoreWS, CoreWSExternalFile, CoreWSExternalWarning, CoreWSFile, CoreWSPreSets } from '@services/ws';
import { makeSingleton, Translate } from '@singletons';
import { CoreEvents } from '@singletons/events';
import { AddonModScormOffline } from './scorm-offline';
import { AddonModScormAutoSyncEventData, AddonModScormSyncProvider } from './scorm-sync';
// Private constants.
const VALID_STATUSES = ['notattempted', 'passed', 'completed', 'failed', 'incomplete', 'browsed', 'suspend'];
const STATUSES = {
'passed': 'passed',
'completed': 'completed',
'failed': 'failed',
'incomplete': 'incomplete',
'browsed': 'browsed',
'not attempted': 'notattempted',
'p': 'passed',
'c': 'completed',
'f': 'failed',
'i': 'incomplete',
'b': 'browsed',
'n': 'notattempted',
};
const STATUS_TO_ICON = {
assetc: 'far-file-archive',
asset: 'far-file-archive',
browsed: 'fas-book',
completed: 'far-check-square',
failed: 'fas-times',
incomplete: 'far-edit',
minus: 'fas-minus',
notattempted: 'far-square',
passed: 'fas-check',
plus: 'fas-plus',
popdown: 'far-window-close',
popup: 'fas-window-restore',
suspend: 'fas-pause',
wait: 'far-clock',
};
const ROOT_CACHE_KEY = 'mmaModScorm:';
/**
* Service that provides some features for SCORM.
*/
@Injectable({ providedIn: 'root' })
export class AddonModScormProvider {
static readonly COMPONENT = 'mmaModScorm';
// Public constants.
static readonly GRADESCOES = 0;
static readonly GRADEHIGHEST = 1;
static readonly GRADEAVERAGE = 2;
static readonly GRADESUM = 3;
static readonly HIGHESTATTEMPT = 0;
static readonly AVERAGEATTEMPT = 1;
static readonly FIRSTATTEMPT = 2;
static readonly LASTATTEMPT = 3;
static readonly MODEBROWSE = 'browse';
static readonly MODENORMAL = 'normal';
static readonly MODEREVIEW = 'review';
static readonly SCORM_FORCEATTEMPT_NO = 0;
static readonly SCORM_FORCEATTEMPT_ONCOMPLETE = 1;
static readonly SCORM_FORCEATTEMPT_ALWAYS = 2;
static readonly SKIPVIEW_NEVER = 0;
static readonly SKIPVIEW_FIRST = 1;
static readonly SKIPVIEW_ALWAYS = 2;
// Events.
static readonly LAUNCH_NEXT_SCO_EVENT = 'addon_mod_scorm_launch_next_sco';
static readonly LAUNCH_PREV_SCO_EVENT = 'addon_mod_scorm_launch_prev_sco';
static readonly UPDATE_TOC_EVENT = 'addon_mod_scorm_update_toc';
static readonly GO_OFFLINE_EVENT = 'addon_mod_scorm_go_offline';
static readonly DATA_SENT_EVENT = 'addon_mod_scorm_data_sent';
/**
* Calculates the SCORM grade based on the grading method and the list of attempts scores.
* We only treat online attempts to calculate a SCORM grade.
*
* @param scorm SCORM.
* @param onlineAttempts Object with the online attempts.
* @return Grade. -1 if no grade.
*/
calculateScormGrade(scorm: AddonModScormScorm, onlineAttempts: Record<number, AddonModScormAttemptGrade>): number {
if (!onlineAttempts || !Object.keys(onlineAttempts).length) {
return -1;
}
switch (scorm.whatgrade) {
case AddonModScormProvider.FIRSTATTEMPT:
return onlineAttempts[1] ? onlineAttempts[1].grade : -1;
case AddonModScormProvider.LASTATTEMPT: {
// Search the last attempt number.
let max = 0;
Object.keys(onlineAttempts).forEach((attemptNumber) => {
max = Math.max(Number(attemptNumber), max);
});
if (max > 0) {
return onlineAttempts[max].grade;
}
return -1;
}
case AddonModScormProvider.HIGHESTATTEMPT: {
// Search the highest grade.
let grade = 0;
for (const attemptNumber in onlineAttempts) {
grade = Math.max(onlineAttempts[attemptNumber].grade, grade);
}
return grade;
}
case AddonModScormProvider.AVERAGEATTEMPT: {
// Calculate the average.
let sumGrades = 0;
let total = 0;
for (const attemptNumber in onlineAttempts) {
sumGrades += onlineAttempts[attemptNumber].grade;
total++;
}
return Math.round(sumGrades / total);
}
default:
return -1;
}
}
/**
* Calculates the size of a SCORM.
*
* @param scorm SCORM.
* @return Promise resolved with the SCORM size.
*/
async calculateScormSize(scorm: AddonModScormScorm): Promise<number> {
if (scorm.packagesize) {
return scorm.packagesize;
}
return CoreWS.getRemoteFileSize(this.getPackageUrl(scorm));
}
/**
* Count the attempts left for the given scorm.
*
* @param scorm SCORM.
* @param attemptsCount Number of attempts performed.
* @return Number of attempts left.
*/
countAttemptsLeft(scorm: AddonModScormScorm, attemptsCount: number): number {
if (!scorm.maxattempt) {
return Number.MAX_VALUE; // Unlimited attempts.
}
attemptsCount = Number(attemptsCount); // Make sure it's a number.
if (isNaN(attemptsCount)) {
return -1;
}
return Math.max(scorm.maxattempt - attemptsCount, 0);
}
/**
* Returns the mode and attempt number to use based on mode selected and SCORM data.
* This function is based on Moodle's scorm_check_mode.
*
* @param scorm SCORM.
* @param mode Selected mode.
* @param attempt Current attempt.
* @param newAttempt Whether it should start a new attempt.
* @param incomplete Whether current attempt is incomplete.
* @return Mode, attempt number and whether to start a new attempt.
*/
determineAttemptAndMode(
scorm: AddonModScormScorm,
mode: string,
attempt: number,
newAttempt?: boolean,
incomplete?: boolean,
): {mode: string; attempt: number; newAttempt: boolean} {
if (mode == AddonModScormProvider.MODEBROWSE) {
if (scorm.hidebrowse) {
// Prevent Browse mode if hidebrowse is set.
mode = AddonModScormProvider.MODENORMAL;
} else {
// We don't need to check attempts as browse mode is set.
if (attempt == 0) {
attempt = 1;
newAttempt = true;
}
return {
mode: mode,
attempt: attempt,
newAttempt: !!newAttempt,
};
}
}
if (scorm.forcenewattempt == AddonModScormProvider.SCORM_FORCEATTEMPT_ALWAYS) {
// This SCORM is configured to force a new attempt on every re-entry.
return {
mode: AddonModScormProvider.MODENORMAL,
attempt: attempt + 1,
newAttempt: true,
};
}
// Validate user request to start a new attempt.
if (attempt == 0) {
newAttempt = true;
} else if (incomplete) {
// The option to start a new attempt should never have been presented. Force false.
newAttempt = false;
} else if (scorm.forcenewattempt) {
// A new attempt should be forced for already completed attempts.
newAttempt = true;
}
if (newAttempt && (!scorm.maxattempt || attempt < scorm.maxattempt)) {
// Create a new attempt. Force mode normal.
attempt++;
mode = AddonModScormProvider.MODENORMAL;
} else {
if (incomplete) {
// We can't review an incomplete attempt.
mode = AddonModScormProvider.MODENORMAL;
} else {
// We aren't starting a new attempt and the current one is complete, force review mode.
mode = AddonModScormProvider.MODEREVIEW;
}
}
return {
mode: mode,
attempt: attempt,
newAttempt: !!newAttempt,
};
}
/**
* Check if TOC should be displayed in the player.
*
* @param scorm SCORM.
* @return Whether it should display TOC.
*/
displayTocInPlayer(scorm: AddonModScormScorm): boolean {
return scorm.hidetoc !== 3;
}
/**
* This is a little language parser for AICC_SCRIPT.
* Evaluates the expression and returns a boolean answer.
* See 2.3.2.5.1. Sequencing/Navigation Today - from the SCORM 1.2 spec (CAM).
*
* @param prerequisites The AICC_SCRIPT prerequisites expression.
* @param trackData The tracked user data of each SCO.
* @return Whether the prerequisites are fulfilled.
*/
evalPrerequisites(prerequisites: string, trackData: Record<string, Record<string, AddonModScormDataValue>>): boolean {
const stack: string[] = []; // List of prerequisites.
// Expand the amp entities.
prerequisites = prerequisites.replace(/&/gi, '&');
// Find all my parsable tokens.
prerequisites = prerequisites.replace(/(&|\||\(|\)|~)/gi, '\t$1\t');
// Expand operators.
prerequisites = prerequisites.replace(/&/gi, '&&');
prerequisites = prerequisites.replace(/\|/gi, '||');
// Now - grab all the tokens.
const elements = prerequisites.trim().split('\t');
// Process each token to build an expression to be evaluated.
elements.forEach((element) => {
element = element.trim();
if (!element) {
return;
}
if (!element.match(/^(&&|\|\||\(|\))$/gi)) {
// Create each individual expression.
// Search for ~ = <> X*{} .
const re = /^(\d+)\*\{(.+)\}$/; // Sets like 3*{S34, S36, S37, S39}.
const reOther = /^(.+)(=|<>)(.+)$/; // Other symbols.
let matches = element.match(re);
if (matches) {
const repeat = Number(matches[1]);
const set = matches[2].split(',') || [];
let count = 0;
set.forEach((setElement) => {
setElement = setElement.trim();
if (typeof trackData[setElement] != 'undefined' &&
(trackData[setElement].status == 'completed' || trackData[setElement].status == 'passed')) {
count++;
}
});
if (count >= repeat) {
element = 'true';
} else {
element = 'false';
}
} else if (element == '~') {
// Not maps ~.
element = '!';
} else if (reOther.test(element)) {
// Other symbols = | <> .
matches = element.match(reOther)!;
element = matches[1].trim();
if (typeof trackData[element] != 'undefined') {
let value = matches[3].trim().replace(/('|")/gi, '');
let oper: string;
if (typeof STATUSES[value] != 'undefined') {
value = STATUSES[value];
}
if (matches[2] == '<>') {
oper = '!=';
} else {
oper = '==';
}
element = '(\'' + trackData[element].status + '\' ' + oper + ' \'' + value + '\')';
} else {
element = 'false';
}
} else {
// Everything else must be an element defined like S45 ...
if (typeof trackData[element] != 'undefined' &&
(trackData[element].status == 'completed' || trackData[element].status == 'passed')) {
element = 'true';
} else {
element = 'false';
}
}
}
// Add the element to the list of prerequisites.
stack.push(' ' + element + ' ');
});
// eslint-disable-next-line no-eval
return eval(stack.join('') + ';');
}
/**
* Formats a grade to be displayed.
*
* @param scorm SCORM.
* @param grade Grade.
* @return Grade to display.
*/
formatGrade(scorm: AddonModScormScorm, grade: number): string {
if (typeof grade == 'undefined' || grade == -1) {
return Translate.instant('core.none');
}
if (scorm.grademethod !== AddonModScormProvider.GRADESCOES && scorm.maxgrade) {
grade = (grade / scorm.maxgrade) * 100;
return Translate.instant('core.percentagenumber', { $a: CoreTextUtils.roundToDecimals(grade, 2) });
}
return String(grade);
}
/**
* Formats a tree-like TOC into an array.
*
* @param toc SCORM's TOC (tree format).
* @param level The level of the TOC we're right now. 0 by default.
* @return SCORM's TOC (array format).
*/
formatTocToArray(toc: AddonModScormTOCTreeSco[], level: number = 0): AddonModScormTOCListSco[] {
if (!toc || !toc.length) {
return [];
}
let formatted: AddonModScormTOCListSco[] = [];
toc.forEach((node) => {
const sco = <AddonModScormTOCListSco> node;
sco.level = level;
formatted.push(sco);
formatted = formatted.concat(this.formatTocToArray(node.children, level + 1));
});
return formatted;
}
/**
* Get access information for a given SCORM.
*
* @param scormId SCORM ID.
* @param options Other options.
* @return Object with access information.
* @since 3.7
*/
async getAccessInformation(
scormId: number,
options: CoreCourseCommonModWSOptions = {},
): Promise<AddonModScormGetScormAccessInformationWSResponse> {
const site = await CoreSites.getSite(options.siteId);
if (!site.wsAvailable('mod_scorm_get_scorm_access_information')) {
// Access information not available for 3.6 or older sites.
return {};
}
const params: AddonModScormGetScormAccessInformationWSParams = {
scormid: scormId,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getAccessInformationCacheKey(scormId),
component: AddonModScormProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
return site.read('mod_scorm_get_scorm_access_information', params, preSets);
}
/**
* Get cache key for access information WS calls.
*
* @param scormId SCORM ID.
* @return Cache key.
*/
protected getAccessInformationCacheKey(scormId: number): string {
return ROOT_CACHE_KEY + 'accessInfo:' + scormId;
}
/**
* Get the number of attempts done by a user in the given SCORM.
*
* @param scormId SCORM ID.
* @param options Other options.
* @return Promise resolved when done.
*/
async getAttemptCount(
scormId: number,
options: AddonModScormGetAttemptCountOptions = {},
): Promise<AddonModScormAttemptCountResult> {
options.siteId = options.siteId || CoreSites.getCurrentSiteId();
const site = await CoreSites.getSite(options.siteId);
const userId = options.userId || site.getUserId();
const [onlineCount, offlineAttempts] = await Promise.all([
this.getAttemptCountOnline(scormId, options),
AddonModScormOffline.getAttempts(scormId, options.siteId, userId),
]);
const result: AddonModScormAttemptCountResult = {
online: [],
offline: [],
total: onlineCount,
lastAttempt: {
num: onlineCount,
offline: false,
},
};
// Fill online attempts array.
for (let i = 1; i <= onlineCount; i++) {
result.online.push(i);
}
// Get only attempt numbers for offline attempts.
result.offline = offlineAttempts.map((entry) => {
// Calculate last attempt. We use >= to prioritize offline events if an attempt is both online and offline.
if (entry.attempt >= result.lastAttempt.num) {
result.lastAttempt.num = entry.attempt;
result.lastAttempt.offline = true;
}
return entry.attempt;
});
// Calculate the total.
result.offline.forEach((attempt) => {
// Check if this attempt also exists in online, it might have been copied to local.
if (result.online.indexOf(attempt) == -1) {
result.total++;
}
});
return result;
}
/**
* Get cache key for SCORM attempt count WS calls.
*
* @param scormId SCORM ID.
* @param userId User ID. If not defined, current user.
* @return Cache key.
*/
protected getAttemptCountCacheKey(scormId: number, userId: number): string {
return ROOT_CACHE_KEY + 'attemptcount:' + scormId + ':' + userId;
}
/**
* Get the number of attempts done by a user in the given SCORM in online.
*
* @param scormId SCORM ID.
* @param options Other options.
* @return Promise resolved when the attempt count is retrieved.
*/
async getAttemptCountOnline(scormId: number, options: AddonModScormGetAttemptCountOptions = {}): Promise<number> {
const site = await CoreSites.getSite(options.siteId);
const userId = options.userId || site.getUserId();
const params: AddonModScormGetScormAttemptCountWSParams = {
scormid: scormId,
userid: userId,
ignoremissingcompletion: options.ignoreMissing,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getAttemptCountCacheKey(scormId, userId),
updateFrequency: CoreSite.FREQUENCY_SOMETIMES,
component: AddonModScormProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModScormGetScormAttemptCountWSResponse>(
'mod_scorm_get_scorm_attempt_count',
params,
preSets,
);
return response.attemptscount;
}
/**
* Get the grade for a certain SCORM and attempt.
* Based on Moodle's scorm_grade_user_attempt.
*
* @param scorm SCORM.
* @param attempt Attempt number.
* @param offline Whether the attempt is offline.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the grade. If the attempt hasn't reported grade/completion, it will be -1.
*/
async getAttemptGrade(scorm: AddonModScormScorm, attempt: number, offline?: boolean, siteId?: string): Promise<number> {
const attemptScore = {
scos: 0,
values: 0,
max: 0,
sum: 0,
};
// Get the user data and use it to calculate the grade.
const data = await this.getScormUserData(scorm.id, attempt, { offline, cmId: scorm.coursemodule, siteId });
for (const scoId in data) {
const sco = data[scoId];
const userData = sco.userdata;
if (userData.status == 'completed' || userData.status == 'passed') {
attemptScore.scos++;
}
if (userData.score_raw || (typeof scorm.scormtype != 'undefined' &&
scorm.scormtype == 'sco' && typeof userData.score_raw != 'undefined')) {
const scoreRaw = parseFloat(<string> userData.score_raw);
attemptScore.values++;
attemptScore.sum += scoreRaw;
attemptScore.max = Math.max(scoreRaw, attemptScore.max);
}
}
let score = 0;
switch (scorm.grademethod) {
case AddonModScormProvider.GRADEHIGHEST:
score = attemptScore.max;
break;
case AddonModScormProvider.GRADEAVERAGE:
if (attemptScore.values > 0) {
score = attemptScore.sum / attemptScore.values;
} else {
score = 0;
}
break;
case AddonModScormProvider.GRADESUM:
score = attemptScore.sum;
break;
case AddonModScormProvider.GRADESCOES:
score = attemptScore.scos;
break;
default:
score = attemptScore.max; // Remote Learner GRADEHIGHEST is default.
}
return score;
}
/**
* Get the list of a organizations defined in a SCORM package.
*
* @param scormId SCORM ID.
* @param options Other options.
* @return Promise resolved with the list of organizations.
*/
async getOrganizations(scormId: number, options: CoreCourseCommonModWSOptions = {}): Promise<AddonModScormOrganization[]> {
const scos = await this.getScos(scormId, options);
const organizations: AddonModScormOrganization[] = [];
scos.forEach((sco) => {
// Is an organization entry?
if (sco.organization == '' && sco.parent == '/' && sco.scormtype == '') {
organizations.push({
identifier: sco.identifier,
title: sco.title,
sortorder: sco.sortorder,
});
}
});
return organizations;
}
/**
* Get the organization Toc any
*
* @param scormId SCORM ID.
* @param attempt The attempt number (to populate SCO track data).
* @param options Other options.
* @return Promise resolved with the toc object.
*/
async getOrganizationToc(
scormId: number,
attempt: number,
options: AddonModScormGetScosWithDataOptions = {},
): Promise<AddonModScormTOCTreeSco[]> {
const scos = <AddonModScormTOCTreeSco[]> await this.getScosWithData(scormId, attempt, options);
const map: Record<string, number> = {};
const rootScos: AddonModScormTOCTreeSco[] = [];
scos.forEach((sco, index) => {
sco.children = [];
map[sco.identifier] = index;
if (sco.parent !== '/') {
if (sco.parent == options.organization) {
// It's a root SCO, add it to the root array.
rootScos.push(sco);
} else {
// Add this sco to the parent.
scos[map[sco.parent]].children.push(sco);
}
}
});
return rootScos;
}
/**
* Get the package URL of a given SCORM.
*
* @param scorm SCORM.
* @return Package URL.
*/
getPackageUrl(scorm: AddonModScormScorm): string {
if (scorm.packageurl) {
return scorm.packageurl;
}
if (scorm.reference) {
return scorm.reference;
}
return '';
}
/**
* Get the user data for a certain SCORM and attempt.
*
* @param scormId SCORM ID.
* @param attempt Attempt number.
* @param options Other options.
* @return Promise resolved when the user data is retrieved.
*/
async getScormUserData(
scormId: number,
attempt: number,
options: AddonModScormGetUserDataOptions = {},
): Promise<AddonModScormUserDataMap> {
options.siteId = options.siteId || CoreSites.getCurrentSiteId();
if (!options.offline) {
return this.getScormUserDataOnline(scormId, attempt, options);
}
// Get SCOs if not provided.
if (!options.scos) {
options.scos = await this.getScos(scormId, options);
}
return AddonModScormOffline.getScormUserData(scormId, attempt, options.scos, options.siteId);
}
/**
* Get cache key for SCORM user data WS calls.
*
* @param scormId SCORM ID.
* @param attempt Attempt number.
* @return Cache key.
*/
protected getScormUserDataCacheKey(scormId: number, attempt: number): string {
return this.getScormUserDataCommonCacheKey(scormId) + ':' + attempt;
}
/**
* Get common cache key for SCORM user data WS calls.
*
* @param scormId SCORM ID.
* @return Cache key.
*/
protected getScormUserDataCommonCacheKey(scormId: number): string {
return ROOT_CACHE_KEY + 'userdata:' + scormId;
}
/**
* Get the user data for a certain SCORM and attempt in online.
*
* @param scormId SCORM ID.
* @param attempt Attempt number.
* @param options Other options.
* @return Promise resolved when the user data is retrieved.
*/
async getScormUserDataOnline(
scormId: number,
attempt: number,
options: CoreCourseCommonModWSOptions = {},
): Promise<AddonModScormUserDataMap> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModScormGetScormUserDataWSParams = {
scormid: scormId,
attempt: attempt,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getScormUserDataCacheKey(scormId, attempt),
component: AddonModScormProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModScormGetScormUserDataWSResponse>('mod_scorm_get_scorm_user_data', params, preSets);
// Format the response.
const data: AddonModScormUserDataMap = {};
response.data.forEach((sco) => {
data[sco.scoid] = {
scoid: sco.scoid,
defaultdata: <Record<string, AddonModScormDataValue>> CoreUtils.objectToKeyValueMap(
sco.defaultdata,
'element',
'value',
),
userdata: <Record<string, AddonModScormDataValue>> CoreUtils.objectToKeyValueMap(sco.userdata, 'element', 'value'),
};
});
return data;
}
/**
* Get cache key for get SCORM scos WS calls.
*
* @param scormId SCORM ID.
* @return Cache key.
*/
protected getScosCacheKey(scormId: number): string {
return ROOT_CACHE_KEY + 'scos:' + scormId;
}
/**
* Retrieves the list of SCO objects for a given SCORM and organization.
*
* @param scormId SCORM ID.
* @param options Other options.
* @return Promise resolved with a list of SCO.
*/
async getScos(scormId: number, options: AddonModScormOrganizationOptions = {}): Promise<AddonModScormWSSco[]> {
options.siteId = options.siteId || CoreSites.getCurrentSiteId();
const site = await CoreSites.getSite(options.siteId);
// Don't send the organization to the WS, we'll filter them locally.
const params: AddonModScormGetScormScoesWSParams = {
scormid: scormId,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getScosCacheKey(scormId),
updateFrequency: CoreSite.FREQUENCY_SOMETIMES,
component: AddonModScormProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModScormGetScormScoesWSResponse>('mod_scorm_get_scorm_scoes', params, preSets);
if (options.organization) {
// Filter SCOs by organization.
return response.scoes.filter((sco) => sco.organization == options.organization);
}
return response.scoes;
}
/**
* Retrieves the list of SCO objects for a given SCORM and organization, including data about
* a certain attempt (status, isvisible, ...).
*
* @param scormId SCORM ID.
* @param attempt Attempt number.
* @param options Other options.
* @return Promise resolved with a list of SCO objects.
*/
async getScosWithData(
scormId: number,
attempt: number,
options: AddonModScormGetScosWithDataOptions = {},
): Promise<AddonModScormScoWithData[]> {
// Get organization SCOs.
const scos = await this.getScos(scormId, options);
// Get the track data for all the SCOs in the organization for the given attempt.
// We'll use this data to set SCO data like isvisible, status and so.
const userDataOptions: AddonModScormGetUserDataOptions = {
scos,
...options, // Include all options.
};
const data = await this.getScormUserData(scormId, attempt, userDataOptions);
const trackDataBySCO: Record<string, Record<string, AddonModScormDataValue>> = {};
// First populate trackDataBySCO to index by SCO identifier.
// We want the full list first because it's needed by evalPrerequisites.
scos.forEach((sco) => {
trackDataBySCO[sco.identifier] = data[sco.id].userdata;
});
const scosWithData: AddonModScormScoWithData[] = scos;
scosWithData.forEach((sco) => {
// Add specific SCO information (related to tracked data).
const scoData = data[sco.id].userdata;
if (!scoData) {
return;
}
// Check isvisible attribute.
sco.isvisible = typeof scoData.isvisible == 'undefined' || (!!scoData.isvisible && scoData.isvisible !== 'false');
// Check pre-requisites status.
sco.prereq = typeof scoData.prerequisites == 'undefined' ||
this.evalPrerequisites(<string> scoData.prerequisites, trackDataBySCO);
// Add status.
sco.status = (typeof scoData.status == 'undefined' || scoData.status === '') ? 'notattempted' : <string> scoData.status;
// Exit var.
sco.exitvar = typeof scoData.exitvar == 'undefined' ? 'cmi.core.exit' : <string> scoData.exitvar;
sco.exitvalue = <string> scoData[sco.exitvar];
// Copy score.
sco.scoreraw = scoData.score_raw;
});
return scosWithData;
}
/**
* Given a SCORM and a SCO, returns the full launch URL for the SCO.
*
* @param scorm SCORM.
* @param sco SCO.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the URL.
*/
async getScoSrc(scorm: AddonModScormScorm, sco: AddonModScormWSSco, siteId?: string): Promise<string> {
siteId = siteId || CoreSites.getCurrentSiteId();
// Build the launch URL. Moodle web checks SCORM version, we don't need to, it's always SCORM 1.2.
let launchUrl = sco.launch;
const parametersEntry = sco.extradata?.find((entry) => entry.element == 'parameters');
let parameters = <string | undefined> parametersEntry?.value;
if (parameters) {
const connector = launchUrl.indexOf('?') > -1 ? '&' : '?';
if (parameters.charAt(0) == '?') {
parameters = parameters.substr(1);
}
launchUrl += connector + parameters;
}
if (this.isExternalLink(launchUrl)) {
// It's an online URL.
return launchUrl;
}
const dirPath = await CoreFilepool.getPackageDirUrlByUrl(siteId, scorm.moduleurl!);
return CoreTextUtils.concatenatePaths(dirPath, launchUrl);
}
/**
* Get the path to the folder where a SCORM is downloaded.
*
* @param moduleUrl Module URL (returned by get_course_contents).
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the folder path.
*/
getScormFolder(moduleUrl: string, siteId?: string): Promise<string> {
siteId = siteId || CoreSites.getCurrentSiteId();
return CoreFilepool.getPackageDirPathByUrl(siteId, moduleUrl);
}
/**
* Gets a list of files to downlaod for a SCORM, using a format similar to module.contents from get_course_contents.
* It will only return one file: the ZIP package.
*
* @param scorm SCORM.
* @return File list.
*/
getScormFileList(scorm: AddonModScormScorm): CoreWSFile[] {
const files: CoreWSFile[] = [];
if (!this.isScormUnsupported(scorm) && !scorm.warningMessage) {
files.push({
fileurl: this.getPackageUrl(scorm),
filepath: '/',
filename: scorm.reference,
filesize: scorm.packagesize,
timemodified: 0,
});
}
return files;
}
/**
* Get the URL and description of the status icon.
*
* @param sco SCO.
* @param incomplete Whether the SCORM is incomplete.
* @return Image URL and description.
*/
getScoStatusIcon(sco: AddonModScormScoWithData, incomplete?: boolean): AddonModScormScoIcon {
let imageName = '';
let descName = '';
let suspendedStr = '';
const status = sco.status || '';
if (sco.isvisible) {
if (VALID_STATUSES.indexOf(status) >= 0) {
if (sco.scormtype == 'sco') {
imageName = status;
descName = status;
} else {
imageName = 'asset';
descName = 'assetlaunched';
}
if (!incomplete) {
// Check if SCO is completed or not. If SCORM is incomplete there's no need to check SCO.
incomplete = this.isStatusIncomplete(status);
}
if (incomplete && sco.exitvalue == 'suspend') {
imageName = 'suspend';
suspendedStr = ' - ' + Translate.instant('addon.mod_scorm.suspended');
}
} else {
incomplete = true;
if (sco.scormtype == 'sco') {
// Status empty or not valid, use 'notattempted'.
imageName = 'notattempted';
} else {
imageName = 'asset';
}
descName = imageName;
}
}
if (imageName == '') {
imageName = 'notattempted';
descName = 'notattempted';
suspendedStr = '';
}
sco.incomplete = incomplete;
return {
icon: STATUS_TO_ICON[imageName],
description: Translate.instant('addon.mod_scorm.' + descName) + suspendedStr,
};
}
/**
* Get cache key for SCORM data WS calls.
*
* @param courseId Course ID.
* @return Cache key.
*/
protected getScormDataCacheKey(courseId: number): string {
return ROOT_CACHE_KEY + 'scorm:' + courseId;
}
/**
* Get a SCORM with key=value. If more than one is found, only the first will be returned.
*
* @param courseId Course ID.
* @param key Name of the property to check.
* @param value Value to search.
* @param options Other options.
* @return Promise resolved when the SCORM is retrieved.
*/
protected async getScormByField(
courseId: number,
key: string,
value: unknown,
options: AddonModScormGetScormOptions = {},
): Promise<AddonModScormScorm> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModScormGetScormsByCoursesWSParams = {
courseids: [courseId],
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getScormDataCacheKey(courseId),
updateFrequency: CoreSite.FREQUENCY_RARELY,
component: AddonModScormProvider.COMPONENT,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModScormGetScormsByCoursesWSResponse>(
'mod_scorm_get_scorms_by_courses',
params,
preSets,
);
const currentScorm = <AddonModScormScorm> response.scorms.find(scorm => scorm[key] == value);
if (!currentScorm) {
throw new CoreError('SCORM not found.');
}
// If the SCORM isn't available the WS returns a warning and it doesn't return timeopen and timeclosed.
if (typeof currentScorm.timeopen == 'undefined') {
const warning = response.warnings?.find(warning => warning.itemid === currentScorm.id);
currentScorm.warningMessage = warning?.message;
}
currentScorm.moduleurl = options.moduleUrl;
return currentScorm;
}
/**
* Get a SCORM by module ID.
*
* @param courseId Course ID.
* @param cmId Course module ID.
* @param options Other options.
* @return Promise resolved when the SCORM is retrieved.
*/
getScorm(courseId: number, cmId: number, options: AddonModScormGetScormOptions = {}): Promise<AddonModScormScorm> {
return this.getScormByField(courseId, 'coursemodule', cmId, options);
}
/**
* Get a SCORM by SCORM ID.
*
* @param courseId Course ID.
* @param id SCORM ID.
* @param options Other options.
* @return Promise resolved when the SCORM is retrieved.
*/
getScormById(courseId: number, id: number, options: AddonModScormGetScormOptions = {}): Promise<AddonModScormScorm> {
return this.getScormByField(courseId, 'id', id, options);
}
/**
* Get a readable SCORM grade method.
*
* @param scorm SCORM.
* @return Grading method.
*/
getScormGradeMethod(scorm: AddonModScormScorm): string {
if (scorm.maxattempt == 1) {
switch (scorm.grademethod) {
case AddonModScormProvider.GRADEHIGHEST:
return Translate.instant('addon.mod_scorm.gradehighest');
case AddonModScormProvider.GRADEAVERAGE:
return Translate.instant('addon.mod_scorm.gradeaverage');
case AddonModScormProvider.GRADESUM:
return Translate.instant('addon.mod_scorm.gradesum');
case AddonModScormProvider.GRADESCOES:
return Translate.instant('addon.mod_scorm.gradescoes');
default:
return '';
}
}
switch (scorm.whatgrade) {
case AddonModScormProvider.HIGHESTATTEMPT:
return Translate.instant('addon.mod_scorm.highestattempt');
case AddonModScormProvider.AVERAGEATTEMPT:
return Translate.instant('addon.mod_scorm.averageattempt');
case AddonModScormProvider.FIRSTATTEMPT:
return Translate.instant('addon.mod_scorm.firstattempt');
case AddonModScormProvider.LASTATTEMPT:
return Translate.instant('addon.mod_scorm.lastattempt');
default:
return '';
}
}
/**
* Invalidates access information.
*
* @param scormId SCORM ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateAccessInformation(scormId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getAccessInformationCacheKey(scormId));
}
/**
* Invalidates all the data related to a certain SCORM.
*
* @param scormId SCORM ID.
* @param siteId Site ID. If not defined, current site.
* @param userId User ID. If not defined use site's current user.
* @return Promise resolved when the data is invalidated.
*/
async invalidateAllScormData(scormId: number, siteId?: string, userId?: number): Promise<void> {
await Promise.all([
this.invalidateAttemptCount(scormId, siteId, userId),
this.invalidateScos(scormId, siteId),
this.invalidateScormUserData(scormId, siteId),
this.invalidateAccessInformation(scormId, siteId),
]);
}
/**
* Invalidates attempt count.
*
* @param scormId SCORM ID.
* @param siteId Site ID. If not defined, current site.
* @param userId User ID. If not defined use site's current user.
* @return Promise resolved when the data is invalidated.
*/
async invalidateAttemptCount(scormId: number, siteId?: string, userId?: number): Promise<void> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
await site.invalidateWsCacheForKey(this.getAttemptCountCacheKey(scormId, userId));
}
/**
* Invalidate the prefetched content.
*
* @param moduleId The module ID.
* @param courseId Course ID of the module.
* @param siteId Site ID. If not defined, current site.
* @param userId User ID. If not defined use site's current user.
* @return Promise resolved when the data is invalidated.
*/
async invalidateContent(moduleId: number, courseId: number, siteId?: string, userId?: number): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
const scorm = await this.getScorm(courseId, moduleId, { siteId });
await Promise.all([
this.invalidateAllScormData(scorm.id, siteId, userId),
CoreFilepool.invalidateFilesByComponent(siteId, AddonModScormProvider.COMPONENT, moduleId, true),
]);
}
/**
* Invalidates SCORM data.
*
* @param courseId Course ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateScormData(courseId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getScormDataCacheKey(courseId));
}
/**
* Invalidates SCORM user data for all attempts.
*
* @param scormId SCORM ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateScormUserData(scormId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getScormUserDataCommonCacheKey(scormId));
}
/**
* Invalidates SCORM scos for all organizations.
*
* @param scormId SCORM ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateScos(scormId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getScosCacheKey(scormId));
}
/**
* Check if a SCORM's attempt is incomplete.
*
* @param scormId SCORM ID.
* @param attempt Attempt.
* @param options Other options.
* @return Promise resolved with a boolean: true if incomplete, false otherwise.
*/
async isAttemptIncomplete(scormId: number, attempt: number, options: AddonModScormOfflineOptions = {}): Promise<boolean> {
const scos = await this.getScosWithData(scormId, attempt, options);
return scos.some(sco => sco.isvisible && sco.launch && this.isStatusIncomplete(sco.status));
}
/**
* Given a launch URL, check if it's a external link.
* Based on Moodle's scorm_external_link.
*
* @param link Link to check.
* @return Whether it's an external link.
*/
protected isExternalLink(link: string): boolean {
link = link.toLowerCase();
if (link.match(/^https?:\/\//i) && !CoreUrlUtils.isLocalFileUrl(link)) {
return true;
} else if (link.substr(0, 4) == 'www.') {
return true;
}
return false;
}
/**
* Check if the given SCORM is closed.
*
* @param scorm SCORM to check.
* @return Whether the SCORM is closed.
*/
isScormClosed(scorm: AddonModScormScorm): boolean {
return !!(scorm.timeclose && CoreTimeUtils.timestamp() > scorm.timeclose);
}
/**
* Check if the given SCORM is downloadable.
*
* @param scorm SCORM to check.
* @return Whether the SCORM is downloadable.
*/
isScormDownloadable(scorm: AddonModScormScorm): boolean {
return typeof scorm.protectpackagedownloads != 'undefined' && scorm.protectpackagedownloads === false;
}
/**
* Check if the given SCORM is open.
*
* @param scorm SCORM to check.
* @return Whether the SCORM is open.
*/
isScormOpen(scorm: AddonModScormScorm): boolean {
return !!(scorm.timeopen && scorm.timeopen > CoreTimeUtils.timestamp());
}
/**
* Check if a SCORM is unsupported in the app. If it's not, returns the error code to show.
*
* @param scorm SCORM to check.
* @return String with error code if unsupported, undefined if supported.
*/
isScormUnsupported(scorm: AddonModScormScorm): string | undefined {
if (!this.isScormValidVersion(scorm)) {
return 'addon.mod_scorm.errorinvalidversion';
} else if (!this.isScormDownloadable(scorm)) {
return 'addon.mod_scorm.errornotdownloadable';
} else if (!this.isValidPackageUrl(this.getPackageUrl(scorm))) {
return 'addon.mod_scorm.errorpackagefile';
}
}
/**
* Check if it's a valid SCORM 1.2.
*
* @param scorm SCORM to check.
* @return Whether the SCORM is valid.
*/
isScormValidVersion(scorm: AddonModScormScorm): boolean {
return scorm.version == 'SCORM_1.2';
}
/**
* Check if a SCO status is incomplete.
*
* @param status SCO status.
* @return Whether it's incomplete.
*/
isStatusIncomplete(status?: string): boolean {
return !status || status == 'notattempted' || status == 'incomplete' || status == 'browsed';
}
/**
* Check if a package URL is valid.
*
* @param packageUrl Package URL.
* @return Whether it's valid.
*/
isValidPackageUrl(packageUrl: string): boolean {
if (!packageUrl) {
return false;
}
if (packageUrl.indexOf('imsmanifest.xml') > -1) {
return false;
}
return true;
}
/**
* Report a SCO as being launched.
*
* @param scormId SCORM ID.
* @param scoId SCO ID.
* @param name Name of the SCORM.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the WS call is successful.
*/
logLaunchSco(scormId: number, scoId: number, name?: string, siteId?: string): Promise<void> {
const params: AddonModScormLaunchScoWSParams = {
scormid: scormId,
scoid: scoId,
};
return CoreCourseLogHelper.logSingle(
'mod_scorm_launch_sco',
params,
AddonModScormProvider.COMPONENT,
scormId,
name,
'scorm',
{ scoid: scoId },
siteId,
);
}
/**
* Report a SCORM as being viewed.
*
* @param id Module ID.
* @param name Name of the SCORM.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the WS call is successful.
*/
logView(id: number, name?: string, siteId?: string): Promise<void> {
const params: AddonModScormViewScormWSParams = {
scormid: id,
};
return CoreCourseLogHelper.logSingle(
'mod_scorm_view_scorm',
params,
AddonModScormProvider.COMPONENT,
id,
name,
'scorm',
{},
siteId,
);
}
/**
* Saves a SCORM tracking record.
*
* @param scoId Sco ID.
* @param attempt Attempt number.
* @param tracks Tracking data to store.
* @param scorm SCORM.
* @param offline Whether the attempt is offline.
* @param userData User data for this attempt and SCO. If not defined, it will be retrieved from DB. Recommended.
* @return Promise resolved when data is saved.
*/
async saveTracks(
scoId: number,
attempt: number,
tracks: AddonModScormDataEntry[],
scorm: AddonModScormScorm,
offline?: boolean,
userData?: AddonModScormUserDataMap,
siteId?: string,
): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
if (offline) {
if (!userData) {
userData = await this.getScormUserData(scorm.id, attempt, { offline, cmId: scorm.coursemodule, siteId });
}
return AddonModScormOffline.saveTracks(scorm, scoId, attempt, tracks, userData, siteId);
}
await this.saveTracksOnline(scorm.id, scoId, attempt, tracks, siteId);
// Tracks have been saved, update cached user data.
this.updateUserDataAfterSave(scorm.id, attempt, tracks, { cmId: scorm.coursemodule, siteId });
CoreEvents.trigger(AddonModScormProvider.DATA_SENT_EVENT, {
scormId: scorm.id,
scoId: scoId,
attempt: attempt,
}, CoreSites.getCurrentSiteId());
}
/**
* Saves a SCORM tracking record.
*
* @param scormId SCORM ID.
* @param scoId Sco ID.
* @param attempt Attempt number.
* @param tracks Tracking data.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when data is saved.
*/
async saveTracksOnline(
scormId: number,
scoId: number,
attempt: number,
tracks: AddonModScormDataEntry[],
siteId?: string,
): Promise<number[]> {
if (!tracks || !tracks.length) {
return []; // Nothing to save.
}
const site = await CoreSites.getSite(siteId);
const params: AddonModScormInsertScormTracksWSParams = {
scoid: scoId,
attempt: attempt,
tracks: tracks,
};
CoreSync.blockOperation(AddonModScormProvider.COMPONENT, scormId, 'saveTracksOnline', site.id);
try {
const response = await site.write<AddonModScormInsertScormTracksWSResponse>('mod_scorm_insert_scorm_tracks', params);
return response.trackids;
} finally {
CoreSync.unblockOperation(AddonModScormProvider.COMPONENT, scormId, 'saveTracksOnline', site.id);
}
}
/**
* Saves a SCORM tracking record using a synchronous call.
* Please use this function only if synchronous is a must. It's recommended to use saveTracks.
*
* @param scoId Sco ID.
* @param attempt Attempt number.
* @param tracks Tracking data to store.
* @param scorm SCORM.
* @param offline Whether the attempt is offline.
* @param userData User data for this attempt and SCO. Required if offline=true.
* @return In online returns true if data is inserted, false otherwise.
* In offline returns true if data to insert is valid, false otherwise. True doesn't mean that the
* data has been stored, this function can return true but the insertion can still fail somehow.
*/
saveTracksSync(
scoId: number,
attempt: number,
tracks: AddonModScormDataEntry[],
scorm: AddonModScormScorm,
offline?: boolean,
userData?: AddonModScormUserDataMap,
): boolean {
if (offline) {
return AddonModScormOffline.saveTracksSync(scorm, scoId, attempt, tracks, userData!);
} else {
const success = this.saveTracksSyncOnline(scoId, attempt, tracks);
if (success) {
// Tracks have been saved, update cached user data.
this.updateUserDataAfterSave(scorm.id, attempt, tracks, { cmId: scorm.coursemodule });
CoreEvents.trigger(AddonModScormProvider.DATA_SENT_EVENT, {
scormId: scorm.id,
scoId: scoId,
attempt: attempt,
}, CoreSites.getCurrentSiteId());
}
return success;
}
}
/**
* Saves a SCORM tracking record using a synchronous call.
* Please use this function only if synchronous is a must. It's recommended to use saveTracksOnline.
*
* @param scoId Sco ID.
* @param attempt Attempt number.
* @param tracks Tracking data.
* @return True if success, false otherwise.
*/
saveTracksSyncOnline(scoId: number, attempt: number, tracks: AddonModScormDataEntry[]): boolean {
if (!tracks || !tracks.length) {
return true; // Nothing to save.
}
const params: AddonModScormInsertScormTracksWSParams = {
scoid: scoId,
attempt: attempt,
tracks: tracks,
};
const currentSite = CoreSites.getCurrentSite();
if (!currentSite) {
return false;
}
const preSets: CoreWSPreSets = {
siteUrl: currentSite.getURL(),
wsToken: currentSite.getToken(),
};
const wsFunction = 'mod_scorm_insert_scorm_tracks';
// Check if the method is available, use a prefixed version if possible.
if (!currentSite.wsAvailable(wsFunction, false)) {
return false;
}
try {
const response = CoreWS.syncCall<AddonModScormInsertScormTracksWSResponse>(wsFunction, params, preSets);
return !!(response && response.trackids);
} catch {
return false;
}
}
/**
* Check if the SCORM main file should be downloaded.
* This function should only be called if the SCORM can be downloaded (not downloaded or outdated).
*
* @param scorm SCORM to check.
* @param isOutdated True if package outdated, false if not downloaded, undefined to calculate it.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with true if it should be downloaded, false otherwise.
*/
async shouldDownloadMainFile(scorm: AddonModScormScorm, isOutdated?: boolean, siteId?: string): Promise<boolean> {
siteId = siteId || CoreSites.getCurrentSiteId();
const component = AddonModScormProvider.COMPONENT;
if (typeof isOutdated == 'undefined') {
// Calculate if it's outdated.
const data = await CoreUtils.ignoreErrors(CoreFilepool.getPackageData(siteId, component, scorm.coursemodule));
if (!data) {
// Package not found, not downloaded.
return false;
}
const isOutdated = data.status == CoreConstants.OUTDATED ||
(data.status == CoreConstants.DOWNLOADING && data.previous == CoreConstants.OUTDATED);
// Package needs to be downloaded if it's not outdated (not downloaded) or if the hash has changed.
return !isOutdated || data.extra != scorm.sha1hash;
} else if (isOutdated) {
// The package is outdated, but maybe the file hasn't changed.
const extra = await CoreUtils.ignoreErrors(CoreFilepool.getPackageExtra(siteId, component, scorm.coursemodule));
if (!extra) {
// Package not found, not downloaded.
return true;
}
return scorm.sha1hash != extra;
} else {
// Package is not outdated and not downloaded, download the main file.
return true;
}
}
/**
* If needed, updates cached user data after saving tracks in online.
*
* @param scormId SCORM ID.
* @param attempt Attempt number.
* @param tracks Tracking data saved.
* @param options Other options.
* @return Promise resolved when updated.
*/
protected async updateUserDataAfterSave(
scormId: number,
attempt: number,
tracks: AddonModScormDataEntry[],
options: {cmId?: number; siteId?: string},
): Promise<void> {
if (!tracks || !tracks.length) {
return;
}
// Check if we need to update. We only update if we sent some track with a dot notation.
const needsUpdate = tracks.some(track => track.element && track.element.indexOf('.') > -1);
if (!needsUpdate) {
return;
}
await this.getScormUserDataOnline(scormId, attempt, {
cmId: options.cmId,
readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK,
siteId: options.siteId,
});
}
}
export const AddonModScorm = makeSingleton(AddonModScormProvider);
/**
* Params of mod_scorm_get_scorm_access_information WS.
*/
export type AddonModScormGetScormAccessInformationWSParams = {
scormid: number; // Scorm instance id.
};
/**
* Data returned by mod_scorm_get_scorm_access_information WS.
*/
export type AddonModScormGetScormAccessInformationWSResponse = {
warnings?: CoreWSExternalWarning[];
canaddinstance?: boolean; // Whether the user has the capability mod/scorm:addinstance allowed.
canviewreport?: boolean; // Whether the user has the capability mod/scorm:viewreport allowed.
canskipview?: boolean; // Whether the user has the capability mod/scorm:skipview allowed.
cansavetrack?: boolean; // Whether the user has the capability mod/scorm:savetrack allowed.
canviewscores?: boolean; // Whether the user has the capability mod/scorm:viewscores allowed.
candeleteresponses?: boolean; // Whether the user has the capability mod/scorm:deleteresponses allowed.
candeleteownresponses?: boolean; // Whether the user has the capability mod/scorm:deleteownresponses allowed.
};
/**
* Params of mod_scorm_get_scorm_attempt_count WS.
*/
export type AddonModScormGetScormAttemptCountWSParams = {
scormid: number; // SCORM instance id.
userid: number; // User id.
ignoremissingcompletion?: boolean; // Ignores attempts that haven't reported a grade/completion.
};
/**
* Data returned by mod_scorm_get_scorm_attempt_count WS.
*/
export type AddonModScormGetScormAttemptCountWSResponse = {
attemptscount: number; // Attempts count.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_scorm_get_scorm_user_data WS.
*/
export type AddonModScormGetScormUserDataWSParams = {
scormid: number; // Scorm instance id.
attempt: number; // Attempt number.
};
/**
* Data returned by mod_scorm_get_scorm_user_data WS.
*/
export type AddonModScormGetScormUserDataWSResponse = {
data: AddonModScormWSScoUserData[];
warnings?: CoreWSExternalWarning[];
};
/**
* Each entry returned by mod_scorm_get_scorm_user_data WS.
*/
export type AddonModScormWSScoUserData = {
scoid: number; // Sco id.
userdata: AddonModScormDataEntry[];
defaultdata: AddonModScormDataEntry[];
};
/**
* Data for each data entry returned by mod_scorm_get_scorm_user_data WS.
*/
export type AddonModScormDataEntry = {
element: string; // Element name.
value: AddonModScormDataValue; // Element value.
};
/**
* Possible values for a data value.
*/
export type AddonModScormDataValue = string | number;
/**
* Map of formatted user data, indexed by SCO id.
*/
export type AddonModScormUserDataMap = Record<number, AddonModScormScoUserData>;
/**
* User data returned mod_scorm_get_scorm_user_data, but formatted.
*/
export type AddonModScormScoUserData = Omit<AddonModScormWSScoUserData, 'defaultdata'|'userdata'> & {
defaultdata: Record<string, AddonModScormDataValue>;
userdata: Record<string, AddonModScormDataValue>;
};
/**
* Params of mod_scorm_get_scorm_scoes WS.
*/
export type AddonModScormGetScormScoesWSParams = {
scormid: number; // Scorm instance id.
organization?: string; // Organization id.
};
/**
* Data returned by mod_scorm_get_scorm_scoes WS.
*/
export type AddonModScormGetScormScoesWSResponse = {
scoes: AddonModScormWSSco[];
warnings?: CoreWSExternalWarning[];
};
/**
* SCO data returned by mod_scorm_get_scorm_scoes WS.
*/
export type AddonModScormWSSco = {
id: number; // Sco id.
scorm: number; // Scorm id.
manifest: string; // Manifest id.
organization: string; // Organization id.
parent: string; // Parent.
identifier: string; // Identifier.
launch: string; // Launch file.
scormtype: string; // Scorm type (asset, sco).
title: string; // Sco title.
sortorder: number; // Sort order.
extradata?: AddonModScormDataEntry[]; // Additional SCO data.
};
/**
* SCO data with some calculated data.
*/
export type AddonModScormScoWithData = AddonModScormWSSco & {
isvisible?: boolean;
prereq?: boolean;
status?: string;
exitvar?: string;
exitvalue?: string;
scoreraw?: string | number;
incomplete?: boolean;
};
/**
* SCO data, including children to build the TOC.
*/
export type AddonModScormTOCTreeSco = AddonModScormScoWithData & {
children: AddonModScormTOCTreeSco[];
};
/**
* SCO data, including children to build the TOC.
*/
export type AddonModScormTOCListSco = AddonModScormTOCTreeSco & {
level: number;
};
/**
* Params of mod_scorm_get_scorms_by_courses WS.
*/
export type AddonModScormGetScormsByCoursesWSParams = {
courseids?: number[]; // Array of course ids.
};
/**
* Data returned by mod_scorm_get_scorms_by_courses WS.
*/
export type AddonModScormGetScormsByCoursesWSResponse = {
scorms: AddonModScormScormWSData[];
warnings?: CoreWSExternalWarning[];
};
/**
* Scorm data returned by mod_scorm_get_scorms_by_courses WS.
*/
export type AddonModScormScormWSData = {
id: number; // SCORM id.
coursemodule: number; // Course module id.
course: number; // Course id.
name: string; // SCORM name.
intro: string; // The SCORM intro.
introformat: number; // Intro format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
introfiles?: CoreWSExternalFile[];
packagesize?: number; // SCORM zip package size.
packageurl?: string; // SCORM zip package URL.
version?: string; // SCORM version (SCORM_12, SCORM_13, SCORM_AICC).
maxgrade?: number; // Max grade.
grademethod?: number; // Grade method.
whatgrade?: number; // What grade.
maxattempt?: number; // Maximum number of attemtps.
forcecompleted?: boolean; // Status current attempt is forced to "completed".
forcenewattempt?: number; // Controls re-entry behaviour.
lastattemptlock?: boolean; // Prevents to launch new attempts once finished.
displayattemptstatus?: number; // How to display attempt status.
displaycoursestructure?: boolean; // Display contents structure.
sha1hash?: string; // Package content or ext path hash.
md5hash?: string; // MD5 Hash of package file.
revision?: number; // Revison number.
launch?: number; // First content to launch.
skipview?: number; // How to skip the content structure page.
hidebrowse?: boolean; // Disable preview mode?.
hidetoc?: number; // How to display the SCORM structure in player.
nav?: number; // Show navigation buttons.
navpositionleft?: number; // Navigation position left.
navpositiontop?: number; // Navigation position top.
auto?: boolean; // Auto continue?.
popup?: number; // Display in current or new window.
width?: number; // Frame width.
height?: number; // Frame height.
timeopen?: number; // Available from.
timeclose?: number; // Available to.
displayactivityname?: boolean; // Display the activity name above the player?.
scormtype?: string; // SCORM type.
reference?: string; // Reference to the package.
protectpackagedownloads?: boolean; // Protect package downloads?.
updatefreq?: number; // Auto-update frequency for remote packages.
options?: string; // Additional options.
completionstatusrequired?: number; // Status passed/completed required?.
completionscorerequired?: number; // Minimum score required.
completionstatusallscos?: number; // Require all scos to return completion status.
autocommit?: boolean; // Save track data automatically?.
timemodified?: number; // Time of last modification.
section?: number; // Course section id.
visible?: boolean; // Visible.
groupmode?: number; // Group mode.
groupingid?: number; // Group id.
};
/**
* Scorm data with some calculated data
*/
export type AddonModScormScorm = AddonModScormScormWSData & {
warningMessage?: string;
moduleurl?: string;
};
/**
* Params of mod_scorm_insert_scorm_tracks WS.
*/
export type AddonModScormInsertScormTracksWSParams = {
scoid: number; // SCO id.
attempt: number; // Attempt number.
tracks: AddonModScormDataEntry[];
};
/**
* Data returned by mod_scorm_insert_scorm_tracks WS.
*/
export type AddonModScormInsertScormTracksWSResponse = {
trackids: number[];
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_scorm_launch_sco WS.
*/
export type AddonModScormLaunchScoWSParams = {
scormid: number; // SCORM instance id.
scoid?: number; // SCO id (empty for launching the first SCO).
};
/**
* Params of mod_scorm_view_scorm WS.
*/
export type AddonModScormViewScormWSParams = {
scormid: number; // Scorm instance id.
};
/**
* Options to pass to get SCORM.
*/
export type AddonModScormGetScormOptions = CoreSitesCommonWSOptions & {
moduleUrl?: string; // Module URL.
};
/**
* Common options with an organization ID.
*/
export type AddonModScormOrganizationOptions = CoreCourseCommonModWSOptions & {
organization?: string; // Organization ID.
};
/**
* Common options with offline boolean.
*/
export type AddonModScormOfflineOptions = CoreCourseCommonModWSOptions & {
offline?: boolean; // Whether the attempt is offline.
};
/**
* Options to pass to getAttemptCount.
*/
export type AddonModScormGetAttemptCountOptions = CoreCourseCommonModWSOptions & {
ignoreMissing?: boolean; // Whether it should ignore attempts that haven't reported a grade/completion.
userId?: number; // User ID. If not defined use site's current user.
};
/**
* Options to pass to getScormUserData.
*/
export type AddonModScormGetUserDataOptions = AddonModScormOfflineOptions & {
scos?: AddonModScormWSSco[]; // SCOs returned by getScos. Recommended if offline=true.
};
/**
* Options to pass to getScosWithData.
*/
export type AddonModScormGetScosWithDataOptions = AddonModScormOfflineOptions & AddonModScormOrganizationOptions;
/**
* Result of getAttemptCount.
*/
export type AddonModScormAttemptCountResult = {
online: number[]; // List of online attempts numbers.
offline: number[]; // List of offline attempts numbers.
total: number; // Total of unique attempts.
lastAttempt: AddonModScormAttempt; // Last attempt in the SCORM: the number and whether it's offline.
};
/**
* Data for an attempt: number and whether it's offline.
*/
export type AddonModScormAttempt = {
num: number;
offline: boolean;
};
/**
* SCORM organization.
*/
export type AddonModScormOrganization = {
identifier: string;
title: string;
sortorder: number;
};
/**
* Grade for an attempt.
*/
export type AddonModScormAttemptGrade = {
num: number;
grade: number;
};
/**
* Grade for an online attempt.
*/
export type AddonModScormCommonEventData = {
scormId: number;
scoId: number;
attempt: number;
};
/**
* SCO icon data.
*/
export type AddonModScormScoIcon = {
icon: string;
description: string;
};
declare module '@singletons/events' {
/**
* Augment CoreEventsData interface with events specific to this service.
*
* @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
*/
export interface CoreEventsData {
[AddonModScormProvider.LAUNCH_NEXT_SCO_EVENT]: AddonModScormCommonEventData;
[AddonModScormProvider.LAUNCH_PREV_SCO_EVENT]: AddonModScormCommonEventData;
[AddonModScormProvider.UPDATE_TOC_EVENT]: AddonModScormCommonEventData;
[AddonModScormProvider.GO_OFFLINE_EVENT]: AddonModScormCommonEventData;
[AddonModScormProvider.DATA_SENT_EVENT]: AddonModScormCommonEventData;
[AddonModScormSyncProvider.AUTO_SYNCED]: AddonModScormAutoSyncEventData;
}
} | the_stack |
import {
DBCore,
DBCoreAddRequest,
DBCoreDeleteRequest,
DBCoreMutateResponse,
DBCorePutRequest,
DBCoreTable,
DBCoreTransaction,
Middleware
} from 'dexie';
import { DBOperation } from 'dexie-cloud-common';
import { BehaviorSubject } from 'rxjs';
import { DexieCloudDB } from '../db/DexieCloudDB';
import { UserLogin } from '../db/entities/UserLogin';
import { getMutationTable } from '../helpers/getMutationTable';
import { randomString } from '../helpers/randomString';
import { throwVersionIncrementNeeded } from '../helpers/throwVersionIncrementNeeded';
import { guardedTable } from '../middleware-helpers/guardedTable';
import { registerSyncEvent } from '../sync/registerSyncEvent';
import { TXExpandos } from '../types/TXExpandos';
import { outstandingTransactions } from './outstandingTransaction';
export interface MutationTrackingMiddlewareArgs {
currentUserObservable: BehaviorSubject<UserLogin>;
db: DexieCloudDB;
}
/** Tracks all mutations in the same transaction as the mutations -
* so it is guaranteed that no mutation goes untracked - and if transaction
* aborts, the mutations won't be tracked.
*
* The sync job will use the tracked mutations as the source of truth when pushing
* changes to server and cleanup the tracked mutations once the server has
* ackowledged that it got them.
*/
export function createMutationTrackingMiddleware({
currentUserObservable,
db
}: MutationTrackingMiddlewareArgs): Middleware<DBCore> {
return {
stack: 'dbcore',
name: 'MutationTrackingMiddleware',
level: 1,
create: (core) => {
const ordinaryTables = core.schema.tables.filter(
(t) => !/^\$/.test(t.name)
);
let mutTableMap: Map<string, DBCoreTable>;
try {
mutTableMap = new Map(
ordinaryTables.map((tbl) => [
tbl.name,
core.table(`$${tbl.name}_mutations`)
])
);
} catch {
throwVersionIncrementNeeded();
}
return {
...core,
transaction: (tables, mode) => {
let tx: DBCoreTransaction & IDBTransaction & TXExpandos;
if (mode === 'readwrite') {
const mutationTables = tables
.filter((tbl) => db.cloud.schema?.[tbl]?.markedForSync)
.map((tbl) => getMutationTable(tbl));
tx = core.transaction(
[...tables, ...mutationTables],
mode
) as DBCoreTransaction & IDBTransaction & TXExpandos;
} else {
tx = core.transaction(tables, mode) as DBCoreTransaction &
IDBTransaction &
TXExpandos;
}
if (mode === 'readwrite') {
// Give each transaction a globally unique id.
tx.txid = randomString(16);
// Introduce the concept of current user that lasts through the entire transaction.
// This is important because the tracked mutations must be connected to the user.
tx.currentUser = currentUserObservable.value;
outstandingTransactions.value.add(tx);
outstandingTransactions.next(outstandingTransactions.value);
const removeTransaction = () => {
tx.removeEventListener('complete', txComplete);
tx.removeEventListener('error', removeTransaction);
tx.removeEventListener('abort', removeTransaction);
outstandingTransactions.value.delete(tx);
outstandingTransactions.next(outstandingTransactions.value);
};
const txComplete = () => {
if (tx.mutationsAdded && db.cloud.options?.databaseUrl) {
if (db.cloud.usingServiceWorker) {
console.debug('registering sync event');
registerSyncEvent(db, "push");
} else {
db.localSyncEvent.next({purpose: "push"});
}
}
removeTransaction();
};
tx.addEventListener('complete', txComplete);
tx.addEventListener('error', removeTransaction);
tx.addEventListener('abort', removeTransaction);
}
return tx;
},
table: (tableName) => {
const table = core.table(tableName);
if (/^\$/.test(tableName)) {
if (tableName.endsWith('_mutations')) {
// In case application code adds items to ..._mutations tables,
// make sure to set the mutationsAdded flag on transaction.
// This is also done in mutateAndLog() as that function talks to a
// lower level DBCore and wouldn't be catched by this code.
return {
...table,
mutate: (req) => {
if (req.type === 'add' || req.type === 'put') {
(
req.trans as DBCoreTransaction & TXExpandos
).mutationsAdded = true;
}
return table.mutate(req);
}
};
} else if (tableName === '$logins') {
return {
...table,
mutate: (req) => {
//console.debug('Mutating $logins table', req);
return table
.mutate(req)
.then((res) => {
//console.debug('Mutating $logins');
(
req.trans as DBCoreTransaction & TXExpandos
).mutationsAdded = true;
//console.debug('$logins mutated');
return res;
})
.catch((err) => {
console.debug('Failed mutation $logins', err);
return Promise.reject(err);
});
}
};
} else {
return table;
}
}
const { schema } = table;
const mutsTable = mutTableMap.get(tableName)!;
return guardedTable({
...table,
mutate: (req) => {
const trans = req.trans as DBCoreTransaction & TXExpandos;
if (!trans.txid) return table.mutate(req); // Upgrade transactions not guarded by us.
if (trans.disableChangeTracking) return table.mutate(req);
if (!db.cloud.schema?.[tableName]?.markedForSync) return table.mutate(req);
if (!trans.currentUser?.isLoggedIn) {
// Unauthorized user should not log mutations.
// Instead, after login all local data should be logged at once.
return table.mutate(req);
}
return req.type === 'deleteRange'
? table
// Query the actual keys (needed for server sending correct rollback to us)
.query({
query: { range: req.range, index: schema.primaryKey },
trans: req.trans,
values: false
})
// Do a delete request instead, but keep the criteria info for the server to execute
.then((res) => {
return mutateAndLog({
type: 'delete',
keys: res.result,
trans: req.trans,
criteria: { index: null, range: req.range }
});
})
: mutateAndLog(req);
}
});
function mutateAndLog(
req: DBCoreDeleteRequest | DBCoreAddRequest | DBCorePutRequest
): Promise<DBCoreMutateResponse> {
const trans = req.trans as DBCoreTransaction & TXExpandos;
trans.mutationsAdded = true;
const {
txid,
currentUser: { userId }
} = trans;
const { type } = req;
return table.mutate(req).then((res) => {
const { numFailures: hasFailures, failures } = res;
let keys = type === 'delete' ? req.keys! : res.results!;
let values = 'values' in req ? req.values : [];
let changeSpecs = 'changeSpecs' in req ? req.changeSpecs! : [];
if (hasFailures) {
keys = keys.filter((_, idx) => !failures[idx]);
values = values.filter((_, idx) => !failures[idx]);
changeSpecs = changeSpecs.filter((_, idx) => !failures[idx]);
}
const ts = Date.now();
const mut: DBOperation =
req.type === 'delete'
? {
type: 'delete',
ts,
keys,
criteria: req.criteria,
txid,
userId
}
: req.type === 'add'
? {
type: 'insert',
ts,
keys,
txid,
userId,
values
}
: req.criteria && req.changeSpec
? {
// Common changeSpec for all keys
type: 'modify',
ts,
keys,
criteria: req.criteria,
changeSpec: req.changeSpec,
txid,
userId
}
: req.changeSpecs
? {
// One changeSpec per key
type: 'update',
ts,
keys,
changeSpecs,
txid,
userId
}
: {
type: 'upsert',
ts,
keys,
values,
txid,
userId
};
return keys.length > 0 || ('criteria' in req && req.criteria)
? mutsTable
.mutate({ type: 'add', trans, values: [mut] }) // Log entry
.then(() => res) // Return original response
: res;
});
}
}
};
}
};
} | the_stack |
import * as State from "../state";
import * as Core from "./core";
import config from "../config";
import { regDescriptor } from "@effectful/serialization";
import {
regOpaqueObject,
opaqueWeakMap,
opaqueWeakSet,
setObjectDescriptor
} from "../persist";
import * as Binds from "./binds";
import { ForInIterator, patchNative as patch } from "../state";
import * as Instr from "../instr/rt";
import * as Engine from "../engine";
const { record } = Core;
const { journal, context, native, token, CLOSURE_META, CLOSURE_PARENT } = State;
const { record1, record2, record3, record4 } = Binds;
const __effectful__nativeCall = native.FunctionMethods.call;
const __effectful__nativeApply = native.Reflect.apply;
function isInt(str: string): boolean {
return String(Math.ceil(Math.abs(<any>str))) === str;
}
/** object's keys insertion order list */
export interface KeysOrder {
name: string;
next: KeysOrder;
prev: KeysOrder;
enumerable: boolean;
}
export const objectKeysDict = new WeakMap<any, KeysDescr>();
opaqueWeakMap(objectKeysDict, "@effectful/debugger/keys");
/** object's keys orders description */
export interface KeysDescr {
strKeys: KeysOrder;
strMap: { [name: string]: KeysOrder };
symKeys: KeysOrder;
symMap: { [name: string]: KeysOrder };
}
export enum ProxyTrapFlags {
Set = 1 << 0,
SetPrototypeOf = 1 << 1,
DefineProperty = 1 << 2,
OwnKeys = 1 << 3,
Delete = 1 << 4,
IsExtensible = 1 << 5,
PreventExtension = 1 << 6
}
function proxyTrapFlags(v: ProxyHandler<any>): number {
return (
(v.set ? ProxyTrapFlags.Set : 0) |
(v.setPrototypeOf ? ProxyTrapFlags.SetPrototypeOf : 0) |
(v.defineProperty ? ProxyTrapFlags.DefineProperty : 0) |
(v.ownKeys ? ProxyTrapFlags.OwnKeys : 0) |
(v.deleteProperty ? ProxyTrapFlags.Delete : 0) |
(v.isExtensible ? ProxyTrapFlags.IsExtensible : 0) |
(v.preventExtensions ? ProxyTrapFlags.PreventExtension : 0)
);
}
interface ProxyData {
obj: any;
flags: number;
target: any;
traps: ProxyHandler<any>;
proxy: any;
revoked?: boolean;
}
interface DataBreakpointInfo {
hits: number;
hitCondition?: (top: State.Frame) => number;
condition?: (top: State.Frame) => boolean;
}
const proxies: WeakMap<any, ProxyData> | null = config.implicitCalls
? new WeakMap()
: null;
interface DataBreakpointsDict {
[name: string]: DataBreakpointInfo;
}
let dataBreakpoints: WeakMap<any, DataBreakpointsDict> | null = null;
export { proxies, dataBreakpoints };
export function resetDataBreakpoints() {
dataBreakpoints = null;
}
function checkDataBreakpointActive(bp?: DataBreakpointInfo) {
const top = <State.Frame>context.top;
if (
!bp ||
(bp.condition && !bp.condition(top)) ||
(bp.hitCondition && bp.hitCondition(top) !== bp.hits++)
)
return false;
context.stopNext = "data breakpoint";
return true;
}
function checkDataBreakpointFromTo(
arr: any[],
from: number,
lengthChanged: boolean,
to: number = arr.length
) {
const dict = dataBreakpoints?.get(arr);
if (!dict) return;
if (lengthChanged && checkDataBreakpointActive(dict["length"])) return;
for (let i = from; i < to; ++i)
if (checkDataBreakpointActive(dict[i])) return;
}
function checkDataBreakpoint(target: any, prop: any) {
if (!dataBreakpoints) return;
const dict = dataBreakpoints.get(target);
if (!dict) return;
checkDataBreakpointActive(dict[prop]);
}
export function setDataBreakpoint(
target: any,
prop: any,
condition?: (f: State.Frame) => boolean,
hitCondition?: (f: State.Frame) => number
): boolean {
if (!proxies) return false;
if (!dataBreakpoints) dataBreakpoints = new WeakMap();
let bps = dataBreakpoints.get(target);
if (!bps) {
bps = {};
weakMapSet.call(dataBreakpoints, target, bps);
}
const bp: DataBreakpointInfo = {
hits: 0,
condition,
hitCondition
};
bps[prop] = bp;
return true;
}
if (proxies) opaqueWeakMap(proxies, "@effectful/debugger/proxies");
const weakMapSet = native.WeakMap.set;
const NativeSet = Set;
const nativeObject = native.Object;
export const DisableKeysHistorySymbol = Symbol.for("@effectful/no-keys");
function getObjKeys(obj: any): KeysDescr | false | undefined {
if (!obj) return void 0;
const disabled = obj[DisableKeysHistorySymbol];
if (disabled) return false;
return objectKeysDict.get(obj);
}
function getOrCreateObjKeys(
obj: any,
optional: boolean
): KeysDescr | undefined | false {
let descr = getObjKeys(obj);
if (descr != null || optional) return descr;
let strKeys: KeysOrder = <any>{ name: null };
strKeys.next = strKeys;
strKeys.prev = strKeys;
const strMap: { [name: string]: KeysOrder } = {};
let symKeys: KeysOrder = <any>{ name: null };
symKeys.next = symKeys;
symKeys.prev = symKeys;
const symMap: { [name: string]: KeysOrder } = {};
for (const i of nativeObject.getOwnPropertyNames(obj)) {
if (isInt(i)) continue;
const { next } = strKeys;
strMap[i] = strKeys.next = next.prev = {
name: i,
enumerable:
(<any>nativeObject.getOwnPropertyDescriptor(obj, i)).enumerable ===
true,
next,
prev: strKeys
};
}
for (const i of nativeObject.getOwnPropertySymbols(obj)) {
const { next } = symKeys;
symMap[<any>i] = symKeys.next = next.prev = {
name: <any>i,
enumerable:
(<any>nativeObject.getOwnPropertyDescriptor(obj, i)).enumerable ===
true,
next,
prev: symKeys
};
}
weakMapSet.__effectful__nativeCall(
objectKeysDict,
obj,
(descr = {
strKeys,
strMap,
symKeys,
symMap
})
);
return descr;
}
function delKeyImpl(
name: string,
map: { [name: string]: KeysOrder },
value: KeysOrder
) {
delete map[name];
const { prev, next } = value;
prev.next = next;
next.prev = prev;
record4(insertKeyOp, name, map, prev, value);
}
function delKeyOp(this: any) {
const { a: name, b: map, c: value } = this;
delete map[name];
const { prev, next } = value;
prev.next = next;
next.prev = prev;
this.call = insertKeyOp;
this.c = prev;
this.d = value;
record(this);
}
regOpaqueObject(delKeyOp, "#delk");
function delKey(obj: any, name: string, optional: boolean) {
const ty = typeof name;
if (ty !== "number") {
if (ty === "string") {
if (!isInt(name)) {
const descr = getOrCreateObjKeys(obj, optional);
if (descr) {
const prev = descr.strMap[name];
if (prev) delKeyImpl(name, descr.strMap, prev);
}
}
} else {
const descr = getOrCreateObjKeys(obj, optional);
if (descr) {
const prev = descr.symMap[name];
if (prev) delKeyImpl(name, descr.symMap, prev);
}
}
}
}
function insertKeyOp(this: any) {
const { a: name, b: map, c: pos, d: cur } = this;
this.c = cur;
this.d = null;
this.call = delKeyOp;
record(this);
const { next } = pos;
cur.next = next;
cur.prev = pos;
map[name] = pos.next = next.prev = cur;
}
function insertKey(
name: string,
map: { [name: string]: KeysOrder },
pos: KeysOrder,
cur: KeysOrder
) {
const { next } = pos;
cur.next = next;
cur.prev = pos;
map[name] = pos.next = next.prev = cur;
record4(delKeyOp, name, map, cur, null);
}
regOpaqueObject(insertKeyOp, "#insk");
function addKeyImpl(
name: string,
map: { [name: string]: KeysOrder },
list: KeysOrder,
value: KeysOrder
) {
if (map[name]) return;
insertKey(name, map, list, value);
}
regOpaqueObject(addKeyImpl, "#addk");
function addKey(
obj: any,
name: string,
enumerable: boolean,
optional: boolean
): boolean {
const ty = typeof name;
if (ty !== "number") {
if (ty === "string") {
if (!isInt(name)) {
const descr = getOrCreateObjKeys(obj, optional);
if (!descr) return false;
addKeyImpl(name, descr.strMap, descr.strKeys, <any>{
name,
enumerable
});
}
} else {
const descr = getOrCreateObjKeys(obj, optional);
if (!descr) return false;
addKeyImpl(name, descr.symMap, descr.symKeys, <any>{
name,
enumerable
});
}
}
return true;
}
function addNotIntKey(
obj: any,
name: string,
enumerable: boolean,
optional: boolean
): boolean {
if (typeof name === "symbol") {
const descr = getOrCreateObjKeys(obj, optional);
if (!descr) return false;
addKeyImpl(name, descr.symMap, descr.symKeys, <any>{
name,
enumerable
});
} else {
const descr = getOrCreateObjKeys(obj, optional);
if (!descr) return false;
addKeyImpl(name, descr.strMap, descr.strKeys, <any>{
name,
enumerable
});
}
return true;
}
const nativeReflect = native.Reflect;
const nativeReflectSet = nativeReflect.set;
function setImpl(target: any, name: string, value: any, receiver: any) {
if (journal.enabled) {
if (Array.isArray(target)) return arraySet(target, name, value);
let descr: PropertyDescriptor | undefined = void 0;
let descrObj: any;
descrObj = target;
while (descrObj && descrObj !== Object.prototype) {
if (proxies) {
const unwrapped = proxies.get(descrObj);
if (unwrapped) {
if (unwrapped.flags & ProxyTrapFlags.Set) {
context.call = set;
return nativeReflectSet(target, name, value);
}
descrObj = unwrapped.obj;
}
}
descr = Object.getOwnPropertyDescriptor(descrObj, name);
if (descr) break;
descrObj = Object.getPrototypeOf(descrObj);
}
if (dataBreakpoints) checkDataBreakpoint(descrObj, name);
if (descr && (descr.set || !descr.writable)) {
context.call = set;
return nativeReflectSet(target, name, value, receiver);
}
const isIntIndex = typeof name !== "symbol" && isInt(String(<any>name));
if (descrObj === target) {
record3(propSetOp, target, name, target[name]);
} else {
record2(propDelOp, target, name);
if (!isIntIndex) addNotIntKey(target, name, true, !context.enabled);
}
}
context.call = set;
return nativeReflectSet(target, name, value, receiver);
}
export const set: (
obj: any,
name: string /* | symbol | number */,
value: any
) => any = config.timeTravel
? function set(obj: any, name: string, value: any) {
setImpl(obj, name, value, obj);
return value;
}
: function set(obj: any, name: string, value: any) {
context.call = set;
return (obj[name] = value);
};
function continueMCall(args: [any, ...any[]], prop: string, func: any) {
if (!func) throw new TypeError(`${prop} isn't a function`);
return __effectful__nativeApply(
__effectful__nativeCall,
(context.call = func),
args
);
}
const mcallContClosure = <State.Closure>State.closures.get(Instr.mcallCont);
export const mcall: (
prop: string,
...args: [any, ...any[]]
) => void = config.implicitCalls
? function mcall(prop: string, ...args: [any, ...any[]]) {
let func: any = null;
const top = <State.Frame>context.top;
try {
context.call = get;
func = args[0][prop];
} catch (e) {
if (e === token) {
const frame = Engine.makeFrame(mcallContClosure, void 0);
let after = <State.Frame>context.top;
while (after.next !== top) after = <State.Frame>after.next;
frame.goto = 1;
after.next = frame;
frame.caller = frame.next = top;
frame.$ = [null, continueMCall, prop, args, void 0, void 0];
}
throw e;
}
if (!func) throw new TypeError(`${prop} isn't a function`);
return __effectful__nativeApply(
__effectful__nativeCall,
(context.call = func),
args
);
}
: function mcall(prop: string, ...args: [any, ...any[]]) {
const func = args[0][prop];
if (!func) throw new TypeError(`${prop} isn't a function`);
return __effectful__nativeApply(
__effectful__nativeCall,
(context.call = func),
args
);
};
export function get(value: any, property: string): any {
context.call = get;
return value[property];
}
export function has(property: string, value: any): any {
context.call = has;
return property in value;
}
function objectGetOwnPropertyNames(obj: any): string[] {
const unwrapped = proxies?.get(obj);
if (unwrapped) {
if (unwrapped.flags & ProxyTrapFlags.OwnKeys) {
context.call = Instr.getOwnPropertyNames;
return Instr.getOwnPropertyNames(obj);
}
obj = unwrapped.obj;
}
let descr = getObjKeys(obj);
if (!descr) return nativeObject.getOwnPropertyNames(obj);
const res = nativeObject.getOwnPropertyNames(obj).filter(isInt);
const keys = descr.strKeys;
for (let i = keys.prev; i !== keys; i = i.prev) res.push(i.name);
return res;
}
function objectGetOwnPropertySymbols(obj: any): symbol[] {
if (context.call === objectGetOwnPropertySymbols) context.call = objectKeys;
const unwrapped = proxies?.get(obj);
if (unwrapped) {
if (unwrapped.flags & ProxyTrapFlags.OwnKeys) {
context.call = Instr.getOwnPropertySymbols;
return Instr.getOwnPropertySymbols(obj);
}
obj = unwrapped.obj;
}
let descr = getObjKeys(obj);
if (!descr) return nativeObject.getOwnPropertySymbols(obj);
const res: symbol[] = [];
const keys = descr.symKeys;
for (let i = keys.prev; i !== keys; i = i.prev) res.push(<any>i.name);
return res;
}
function objectGetOwnPropertyDescriptor(
obj: object,
name: string | symbol | number
): PropertyDescriptor | undefined {
const unwrapped = proxies?.get(obj);
if (unwrapped && wrappers) {
if (context.call === objectGetOwnPropertyDescriptor)
context.call = Instr.objectGetOwnPropertyDescriptor;
return Instr.objectGetOwnPropertyDescriptor(wrappers, obj, name);
}
const res = nativeObject.getOwnPropertyDescriptor(obj, name);
if (wrappers && res) {
let { set, get } = res;
if (set && (set = wrappers.get(set))) res.set = set;
if (get && (get = wrappers.get(get))) res.get = get;
}
return res;
}
const objectGetOwnPropertyDescriptors = config.implicitCalls
? Instr.objectGetOwnPropertyDescriptors
: function objectGetOwnPropertyDescriptors(
obj: any
): { [name: string]: PropertyDescriptor } {
let descr = getObjKeys(obj);
if (!descr) return nativeObject.getOwnPropertyDescriptors(obj);
const res: { [name: string]: PropertyDescriptor } = {};
const descrs = nativeObject.getOwnPropertyDescriptors(obj);
for (const i of native.Reflect.ownKeys(descrs)) {
if (!isInt(<any>i)) break;
res[<any>i] = descrs[<any>i];
}
const { strKeys, symKeys } = descr;
for (let i = strKeys.prev; i !== strKeys; i = i.prev)
res[i.name] = descrs[i.name];
for (let i = symKeys.prev; i !== symKeys; i = i.prev)
res[i.name] = descrs[i.name];
return res;
};
function objectGetKeysImpl(obj: any): string[] {
const descr = getObjKeys(obj);
if (!descr) return nativeObject.keys(obj);
const keys = nativeObject.keys(obj);
const len = keys.length;
let pos = 0;
for (let i = 0; i < len; ++i, ++pos) if (!isInt(keys[i])) break;
const { strKeys } = descr;
for (let i = strKeys.prev; i !== strKeys; i = i.prev)
if (i.enumerable && i.name in obj) keys[pos++] = i.name;
return keys;
}
function objectKeys(obj: any): string[] {
const unwrap = proxies?.get(obj);
if (unwrap) {
if (unwrap.flags & ProxyTrapFlags.OwnKeys) {
if (context.call === objectKeys) context.call = Instr.objectKeys;
return Instr.objectKeys(obj);
}
obj = unwrap.obj;
}
return objectGetKeysImpl(obj);
}
export function forInIterator(obj: any): Iterable<string> {
const seen = new NativeSet();
const keys: string[] = [];
_forInIterator(obj);
return new ForInIterator(obj, keys);
function _forInIterator(obj: any) {
const descr = getObjKeys(obj);
// tslint:disable-next-line:forin
for (const i in obj) {
if (
descr &&
(!isInt(i) ||
!Object.prototype.hasOwnProperty.__effectful__nativeCall(obj, i))
)
break;
if (!seen.has(i)) {
seen.add(i);
keys.push(i);
}
}
if (!descr) return;
const { strKeys } = <any>descr;
for (let i = strKeys.prev; i !== strKeys; i = i.prev)
if (i.enumerable) {
if (!seen.has(i.name)) {
seen.add(i.name);
keys.push(i.name);
}
}
const proto = nativeObject.getPrototypeOf(obj);
if (proto) _forInIterator(proto);
}
}
export function objectEntries(obj: any): [string, any][] {
const ks = objectGetKeysImpl(obj);
const len = ks.length;
const res = new Array(len);
for (let i = 0; i < len; ++i) {
const key = ks[i];
res[i] = [key, obj[key]];
}
return res;
}
export function objectValues(obj: any): any[] {
const ks = objectGetKeysImpl(obj);
const len = ks.length;
const res = new Array(len);
for (let i = 0; i < len; ++i) {
const key = ks[i];
res[i] = obj[key];
}
return res;
}
function forceConfigurable(props: {
[name: string]: PropertyDescriptor;
}): { [name: string]: PropertyDescriptor } {
const res: { [name: string]: PropertyDescriptor } = {};
for (const i of nativeReflect.ownKeys(props)) {
let p = props[<any>i];
if (!p.configurable) p = nativeObject.assign({}, p, { configurable: true });
res[<any>i] = p;
}
return res;
}
function objectCreate(
obj: any,
props?: { [name: string]: PropertyDescriptor }
) {
if (props) props = forceConfigurable(props);
return nativeObject.create(obj, <any>props);
}
/** API call replacing `delete` */
export const del: (
obj: any,
name: string /* | symbol | number */
) => any = config.timeTravel
? function del(obj: any, name: string) {
if (dataBreakpoints) checkDataBreakpoint(obj, name);
if (journal.enabled) {
const unwrapped = proxies?.get(obj);
if (unwrapped) {
if (unwrapped.flags & ProxyTrapFlags.Delete) {
context.call = del;
return delete obj[name];
}
obj = unwrapped.obj;
}
const cur = defaultGetOwnPropertyDescriptor(obj, name);
if (cur) {
delKey(obj, name, false);
record3(objectDefinePropertyOp, obj, name, cur);
}
}
context.call = del;
return delete obj[name];
}
: function del(obj: any, name: string) {
context.call = del;
return delete obj[name];
};
function propSetOp(this: any) {
const { a: target, b: name, c: value } = this;
if (dataBreakpoints) checkDataBreakpoint(target, name);
if (Object.prototype.hasOwnProperty.__effectful__nativeCall(target, name)) {
this.c = target[name];
} else {
this.call = propDelOp;
this.c = null;
}
record(this);
target[name] = value;
}
regOpaqueObject(propSetOp, "#pset");
function propDelOp(this: any) {
const { a: obj, b: name } = this;
if (dataBreakpoints) checkDataBreakpoint(obj, name);
if (Object.prototype.hasOwnProperty.__effectful__nativeCall(obj, name)) {
this.call = propSetOp;
this.c = obj[name];
record(this);
}
delete obj[name];
}
regOpaqueObject(propDelOp, "#pdel");
function delOp(this: any) {
const { a: obj, b: name } = this;
if (dataBreakpoints) checkDataBreakpoint(obj, name);
const cur = defaultGetOwnPropertyDescriptor(obj, name);
if (cur) {
this.call = objectDefinePropertyOp;
this.c = cur;
record(this);
}
delete obj[name];
}
regOpaqueObject(delOp, "#del");
// TODO: this is not yet close to be ES compatible
export const frozen = new WeakSet();
export const sealed = new WeakSet();
export const notExtensible = new WeakSet();
opaqueWeakSet(frozen, "@effectful/debugger/frozen");
opaqueWeakSet(sealed, "@effectful/debugger/sealed");
opaqueWeakSet(notExtensible, "@effectful/debugger/notExtensible");
const weakAdd = WeakSet.prototype.add;
function objectFreeze(obj: any) {
weakAdd.__effectful__nativeCall(frozen, obj);
return obj;
}
function objectIsFrozen(obj: any) {
// TODO: this is still visible to the program,
// another checks must be added into setters
return frozen.has(obj);
}
function objectSeal(obj: any) {
weakAdd.__effectful__nativeCall(sealed, obj);
return obj;
}
function objectIsSealed(obj: any) {
return sealed.has(obj);
}
let extWarned = false;
function objectPreventExtensions(obj: any) {
const unwrap = proxies?.get(obj);
if (unwrap) {
if (unwrap.flags & ProxyTrapFlags.PreventExtension)
return nativeObject.preventExtensions(obj);
return;
}
// weakAdd.call(notExtensible, obj);
if (!extWarned) {
extWarned = true;
// tslint:disable-next-line:no-console
console.warn(
"DEBUGGER: Object.preventExtensions is ignored (not implemented yet)"
);
}
weakAdd.__effectful__nativeCall(notExtensible, obj);
return obj;
}
function objectIsExtensible(obj: any) {
const unwrap = proxies?.get(obj);
if (unwrap) {
if (unwrap.flags & ProxyTrapFlags.IsExtensible)
return nativeObject.isExtensible(obj);
obj = unwrap.obj;
}
return !notExtensible.has(obj);
}
function objectSetPrototypeOfOp(this: any) {
const { a: obj, b: proto } = this;
if (dataBreakpoints) checkDataBreakpoint(obj, "__proto__");
this.b = nativeObject.getPrototypeOf(obj);
record(this);
nativeObject.setPrototypeOf(obj, proto);
}
regOpaqueObject(objectSetPrototypeOfOp, "#setp");
function objectSetPrototypeOf(obj: any, prototype: any) {
if (dataBreakpoints) checkDataBreakpoint(obj, "__proto__");
if (journal.enabled && context.call === objectSetPrototypeOf) {
const unwrapped = proxies?.get(obj);
if (unwrapped) {
if (unwrapped.flags & ProxyTrapFlags.SetPrototypeOf) {
return nativeObject.setPrototypeOf(obj, prototype);
}
}
const cur = nativeObject.getPrototypeOf(obj);
if (cur !== prototype) record2(objectSetPrototypeOfOp, obj, cur);
}
return nativeObject.setPrototypeOf(obj, prototype);
}
const defaultGetOwnPropertyDescriptor = nativeObject.getOwnPropertyDescriptor;
function objectDefinePropertyNoRec(
obj: any,
name: string,
descr: PropertyDescriptor,
cur: PropertyDescriptor | undefined
) {
if (!descr.configurable)
descr = nativeObject.assign({}, descr, { configurable: true });
try {
if (!cur || cur.configurable)
return nativeReflect.defineProperty(obj, name, descr);
if (cur.writable && "value" in descr) {
obj[name] = descr.value;
return true;
}
} catch (e) {
if (config.verbose)
// tslint:disable-next-line:no-console
console.log("error while defining property", name, descr, e);
throw e;
}
return false;
}
function objectDefinePropertyImpl(
obj: any,
name: string,
descr: PropertyDescriptor,
enabled: boolean
): boolean {
const cur = defaultGetOwnPropertyDescriptor(obj, name);
if (enabled) {
if (cur) record3(objectDefinePropertyOp, obj, name, cur);
else {
record2(delOp, obj, name);
}
}
return objectDefinePropertyNoRec(obj, name, descr, cur);
}
const wrappers: WeakMap<any, any> | null = config.implicitCalls
? new WeakMap()
: null;
export { wrappers };
if (wrappers) opaqueWeakMap(wrappers, "@effectful/debugger/wrappers");
/** `Reflect.defineProperty` wrapper */
function reflectDefineProperty(
obj: any,
name: string,
descr: PropertyDescriptor
): boolean {
if (dataBreakpoints) checkDataBreakpoint(obj, name);
const unwrapped = proxies?.get(obj);
if (unwrapped) {
if (unwrapped.flags & ProxyTrapFlags.DefineProperty)
return nativeReflect.defineProperty(obj, name, descr);
obj = unwrapped.obj;
}
const enabled = journal.enabled && context.call === reflectDefineProperty;
addKey(obj, name, descr.enumerable === true, !enabled);
if (wrappers) {
if (descr.set) {
const set = setterWrap.bind(State.undef, descr.set);
wrappers.set(set, descr.set);
descr.set = set;
}
if (descr.get) {
const get = getterWrap.bind(State.undef, descr.get);
wrappers.set(get, descr.get);
descr.get = get;
}
}
return objectDefinePropertyImpl(obj, name, descr, enabled);
}
function setterWrap(this: any, method: any, value: any) {
if (context.enabled && context.call === set) context.call = method;
return method.call(this, value);
}
regOpaqueObject(setterWrap, "@effectful/debugger/setter");
function getterWrap(this: any, method: any) {
if (context.enabled && context.call === get) context.call = method;
return method.call(this);
}
regOpaqueObject(getterWrap, "@effectful/debugger/getter");
/** `Reflect.defineProperty` wrapper */
function objectDefineProperty(
obj: any,
name: string,
descr: PropertyDescriptor
): PropertyDescriptor {
if (context.call === objectDefineProperty)
context.call = reflectDefineProperty;
reflectDefineProperty(obj, name, descr);
return obj;
}
function objectDefinePropertyOp(this: any) {
const { a: obj, b: name, c: descr } = this;
if (dataBreakpoints) checkDataBreakpoint(obj, name);
const cur = defaultGetOwnPropertyDescriptor(obj, name);
if (cur) {
this.c = cur;
} else {
this.c = null;
this.call = delOp;
}
record(this);
objectDefinePropertyNoRec(obj, name, descr, cur);
}
regOpaqueObject(objectDefinePropertyOp, "#prop");
const objectDefineProperties = config.implicitCalls
? Instr.objectDefineProperties
: function defineProperties(
obj: any,
descrs: { [name: string]: PropertyDescriptor }
) {
descrs = forceConfigurable(descrs);
if (context.call !== objectDefineProperties)
return nativeObject.defineProperties(obj, descrs);
context.call = objectDefineProperty;
for (const i of nativeReflect.ownKeys(obj))
(context.call = objectDefineProperty)(obj, <any>i, descrs[<any>i]);
return obj;
};
export function objectAssign(dest: any, ...args: any[]) {
if (context.call !== objectAssign) return nativeObject.assign(dest, ...args);
for (const value of args) {
if (!value) continue;
for (const name of nativeReflect.ownKeys(value)) {
const descr = <any>(
(context.call = Object.getOwnPropertyDescriptor)(value, name)
);
if (descr.enumerable)
set(dest, <any>name, descr.get ? descr.get.call(value) : descr.value);
}
}
return dest;
}
/** records current property value but don't try to keep insertion order */
export function recordProp(target: any, name: any) {
const cur = defaultGetOwnPropertyDescriptor(target, name);
if (cur) record3(objectDefinePropertyOp, target, name, cur);
else record2(delOp, target, name);
}
function simpleSetOp(this: any) {
const { a: target, b: name, c: value } = this;
if (dataBreakpoints) checkDataBreakpoint(target, name);
this.c = target[name];
record(this);
target[name] = value;
}
regOpaqueObject(simpleSetOp, "#set$obj");
/**
* Same as `set` but simpler:
* - don't use property descriptors
* - don't delete
*/
export function simpleSet(target: any, name: any, value: any) {
if (dataBreakpoints) checkDataBreakpoint(target, name);
if (journal.enabled) record3(simpleSetOp, target, name, target[name]);
return (target[name] = value);
}
export function simpleDel(target: any, name: any) {
if (journal.enabled) record3(simpleSetOp, target, name, target[name]);
target[name] = void 0;
return true;
}
export const gset = simpleSet;
export const gdel = simpleDel;
export const lset = simpleSet;
export const ldel = simpleDel;
/** records the property value in a trace */
export function recp(target: any, name: any, value: any) {
if (journal.enabled) record3(simpleSetOp, target, name, value);
}
/**
* a setter implementation which doesn't respect insertion order,
* but doesn't take the whole object snapshot
*/
export function noOrderSet(obj: any, name: any, value: any): any {
if (journal.enabled) recordProp(obj, name);
return (obj[name] = value);
}
/**
* a deleter implementation which doesn't respect insertion order
*/
export function noOrderDelete(obj: any, name: any): boolean {
if (journal.enabled) recordProp(obj, name);
return delete obj[name];
}
const trapsWrapper: ProxyHandler<any> = {
apply(this: ProxyData, target: any, self: any, args: any[]) {
const method = this.traps.apply;
if (method) {
if (context.enabled && context.call === this.proxy) context.call = method;
return method.__effectful__nativeCall(this.traps, target, self, args);
}
if (context.enabled && context.call === this.proxy) context.call = target;
return nativeReflect.apply(target, self, args);
},
construct(this: ProxyData, target: any, args: any[], newTarget?: any) {
const method = this.traps.construct;
if (method) {
if (context.enabled && context.call === this.proxy) context.call = method;
return method.__effectful__nativeCall(
this.traps,
target,
args,
newTarget
);
}
if (context.enabled && context.call === this.proxy) context.call = target;
return nativeReflect.construct(target, args, newTarget);
}
};
wrapProxyTrapMethod("set", set);
wrapProxyTrapMethod("get", get);
wrapProxyTrapMethod("has", has);
wrapProxyTrapMethod("deleteProperty", del);
wrapProxyTrapMethod("defineProperty", reflectDefineProperty);
wrapProxyTrapMethod(
"getOwnPropertyDescriptor",
Object.getOwnPropertyDescriptor
);
wrapProxyTrapMethod("deleteProperty", del);
wrapProxyTrapMethod("isExtensible", objectIsExtensible);
wrapProxyTrapMethod("preventExtensions", objectPreventExtensions);
wrapProxyTrapMethod("ownKeys", objectKeys);
wrapProxyTrapMethod("setPrototypeOf", objectSetPrototypeOf);
wrapProxyTrapMethod("getPrototypeOf", Object.getPrototypeOf);
regOpaqueObject(wrapProxy, "@effectful/debugger/proxyWrap");
regOpaqueObject(trapsWrapper.apply, "@effectful/debugger/trap#apply");
regOpaqueObject(trapsWrapper.construct, "@effectful/debugger/trap#construct");
regOpaqueObject(trapsWrapper, "@effectful/debugger/traps");
function wrapProxyTrapMethod(name: string, defaultImpl: any) {
regOpaqueObject(
((<any>trapsWrapper)[name] = function(this: ProxyData, ...args: any[]) {
const method = (<any>this.traps)[name];
if (!method)
return __effectful__nativeApply(
(<any>nativeReflect)[name],
nativeReflect,
args
);
if (context.enabled && context.call === defaultImpl)
context.call = method;
return __effectful__nativeApply(method, this.traps, args);
}),
`@effectful/debugger/trap#${name}`
);
}
function wrapProxy<T extends object>(
data: ProxyData,
proxy: T,
target: T,
traps: ProxyHandler<T>
) {
let obj = target;
const unwrapped = (<any>proxies).get(obj);
let flags = proxyTrapFlags(traps);
if (unwrapped) {
obj = unwrapped.obj;
flags |= unwrapped.flags;
}
data.obj = obj;
data.flags = flags;
data.target = target;
data.traps = traps;
data.proxy = proxy;
setObjectDescriptor(proxy, ProxyDescriptor);
(<any>proxies).set(proxy, data);
}
function wrapRevoke(
this: any,
descr: { revoked: boolean },
func: (this: any) => any
) {
descr.revoked = false;
return func.__effectful__nativeCall(this);
}
regOpaqueObject(wrapRevoke, "@effectful/debugger/proxy#revoke");
export class PatchedProxy<T extends object> {
constructor(obj: T, traps: ProxyHandler<T>) {
const wtraps = Object.create(trapsWrapper);
const proxy = new native.Proxy(obj, wtraps);
wrapProxy(wtraps, proxy, obj, traps);
return proxy;
}
static revocable<T extends object>(
obj: T,
traps: ProxyHandler<T>
): { proxy: T; revoke: () => void } {
const wtraps = Object.create(trapsWrapper);
const res = native.Proxy.revocable(obj, wtraps);
wrapProxy(wtraps, res.proxy, obj, traps);
wtraps.revoked = false;
res.revoke = wrapRevoke.bind(res, wtraps, res.revoke);
return res;
}
}
export const ProxyDescriptor = regDescriptor<any>({
name: "#Proxy",
props: false,
create(ctx, json) {
const target = ctx.createStep((<any>json).t);
const traps = ctx.createStep((<any>json).h);
const revoked = (<any>json).r;
if (revoked != null) {
const proxy = PatchedProxy.revocable(target, traps);
if (revoked) proxy.revoke();
return proxy;
}
return new PatchedProxy(target, traps);
},
write(ctx, value) {
const json: any = {};
const unwrapped = proxies?.get(value);
if (!unwrapped)
throw new TypeError("trying to write an unregistered proxy");
json.t = ctx.step(unwrapped.target, json, "t");
json.h = ctx.step(unwrapped.traps, json, "h");
if (unwrapped.revoked != null) json.r = unwrapped.revoked;
return json;
}
});
export { isInt, addKey };
if ((config.timeTravel || config.persistState) && config.patchRT) {
patch(Object, "seal", objectSeal);
patch(Object, "isSealed", objectIsSealed);
patch(Object, "preventExtensions", objectPreventExtensions);
patch(Object, "isExtensible", objectIsExtensible);
patch(Object, "freeze", objectFreeze);
patch(Object, "isFrozen", objectIsFrozen);
}
if (config.timeTravel && config.patchRT) {
patch(Object, "setPrototypeOf", objectSetPrototypeOf);
patch(Object, "defineProperty", objectDefineProperty);
patch(Object, "defineProperties", objectDefineProperties);
patch(Object, "getOwnPropertyDescriptors", objectGetOwnPropertyDescriptors);
patch(Object, "getOwnPropertyDescriptor", objectGetOwnPropertyDescriptor);
patch(Object, "getOwnPropertyNames", objectGetOwnPropertyNames);
patch(Object, "getOwnPropertySymbols", objectGetOwnPropertySymbols);
patch(Object, "keys", objectKeys);
patch(Object, "create", objectCreate);
}
const TAp = Object.getPrototypeOf(Int8Array.prototype);
export const nativeArray = native.Array;
export const nativeTypedArray = {
sort: TAp.sort,
set: TAp.set,
fill: TAp.fill,
reverse: TAp.reverse
};
function spliceOp(this: any) {
let { a: arr, b: start, c: del, d: ins } = this;
const insNum = (this.c = ins.length);
nativeArray.unshift.__effectful__nativeCall(ins, start, del);
const res = __effectful__nativeApply(nativeArray.splice, arr, ins);
this.d = Array.from(res);
if (dataBreakpoints) {
const diff = insNum - del;
const len = arr.length;
checkDataBreakpointFromTo(
arr,
start,
diff !== 0,
diff === 0 ? start + del : diff < 0 ? len : len + diff
);
}
record(this);
}
regOpaqueObject(spliceOp, "#splice");
function spliceImpl(arr: any[], start: number, del: number, ins: any[]) {
const nextDel = ins.length;
if (start < 0) start = arr.length + start;
if (del == null) del = arr.length - start;
nativeArray.unshift.__effectful__nativeCall(ins, start, del);
const res = __effectful__nativeApply(nativeArray.splice, arr, ins);
record4(spliceOp, arr, start, nextDel, Array.from(res));
return res;
}
function arraySet(arr: any[], name: string, value: any) {
if (dataBreakpoints) checkDataBreakpoint(arr, name);
const unwrapped = proxies?.get(arr);
if (unwrapped) {
if (unwrapped.flags & ProxyTrapFlags.Set) {
context.call = set;
return nativeReflect.set(arr, name, value);
}
arr = unwrapped.obj;
}
if (name === "length") {
const len = arr.length;
if (len === value) return len;
const ins: any[] = [];
let start;
let del;
let end;
if (len < value) {
del = 0;
start = len;
ins.length = value - len;
end = value;
} else {
del = len - value;
start = value;
end = len;
}
if (dataBreakpoints) checkDataBreakpointFromTo(arr, start, true, end);
spliceImpl(arr, start, del, ins);
return value;
}
if (typeof name !== "symbol" && isInt(String(<any>name))) {
const index = +name;
const len = arr.length;
const diff = index - len;
if (diff >= 0) {
if (dataBreakpoints) checkDataBreakpoint(arr, "length");
if (diff === 0) {
record1(arrayPopOp, arr);
arr[index] = value;
return value;
}
const ins = [];
ins[diff] = value;
spliceImpl(arr, len, 0, ins);
if (dataBreakpoints) checkDataBreakpointFromTo(arr, len, true);
return value;
}
record3(simpleSetOp, arr, name, arr[index]);
return (arr[index] = value);
}
addKey(arr, name, true, false);
const cur = defaultGetOwnPropertyDescriptor(arr, name);
if (cur) record3(objectDefinePropertyOp, arr, name, cur);
else {
record2(delOp, arr, name);
}
return (arr[<any>name] = value);
}
function arrayPopOp(this: any) {
this.b = nativeArray.pop.__effectful__nativeCall(this.a);
if (dataBreakpoints) {
const len = this.a.length;
checkDataBreakpointFromTo(this.a, len, true, len + 1);
}
this.call = arrayPush1Op;
record(this);
}
regOpaqueObject(arrayPopOp, "#arr$pop");
export function arrayPop(this: any[]): any {
if (this.length) {
const res = nativeArray.pop.__effectful__nativeCall(this);
if (dataBreakpoints) {
const len = this.length;
checkDataBreakpointFromTo(this, len, true, len + 1);
}
if (journal.enabled && context.call === arrayPop) {
context.call = null;
record2(arrayPush1Op, this, res);
}
return res;
}
return undefined;
}
function arrayPush1Op(this: any) {
const { a: arr, b: value } = this;
this.b = null;
this.call = arrayPopOp;
record(this);
const len = arr.length;
arr[len] = value;
if (dataBreakpoints) checkDataBreakpointFromTo(arr, len, true, len + 1);
}
regOpaqueObject(arrayPush1Op, "#arr$push1");
export function arrayPush(this: any[]): number {
const fromLen = this.length;
const argLen = arguments.length;
const res = __effectful__nativeApply(nativeArray.push, this, arguments);
if (dataBreakpoints) checkDataBreakpointFromTo(this, fromLen, argLen !== 0);
if (journal.enabled && context.call === arrayPush) {
context.call = null;
if (argLen === 1) record1(arrayPopOp, this);
else record4(spliceOp, this, fromLen, argLen, []);
}
return res;
}
regOpaqueObject(arrayPush, "#arr$push");
function arrayShiftOp(this: any) {
if (dataBreakpoints) checkDataBreakpointFromTo(this.a, 0, true);
const res = nativeArray.shift.__effectful__nativeCall(this.a);
this.b = res;
this.call = arrayUnshift1Op;
record(this);
}
regOpaqueObject(arrayShiftOp, "#arr$shift");
export function arrayShift(this: any[]): any {
const len = this.length;
if (len) {
if (dataBreakpoints) checkDataBreakpointFromTo(this, 0, true, len);
const res = nativeArray.shift.__effectful__nativeCall(this);
if (journal.enabled && context.call === arrayShift) {
context.call = null;
record2(arrayUnshift1Op, this, res);
}
return res;
}
return undefined;
}
function arrayUnshift1Op(this: any) {
const { a: arr, b: value } = this;
(<any>nativeArray.unshift).__effectful__nativeCall(arr, value);
this.call = arrayShiftOp;
this.b = null;
if (dataBreakpoints) checkDataBreakpointFromTo(arr, 0, true);
record(this);
}
regOpaqueObject(arrayUnshift1Op, "#arr$unshift");
export function arrayUnshift(this: any[]): number {
if (journal.enabled && context.call === arrayUnshift) {
context.call = null;
const alen = arguments.length;
if (alen === 1) record1(arrayShiftOp, this);
else record4(spliceOp, this, 0, alen, []);
}
const res = __effectful__nativeApply(nativeArray.unshift, this, arguments);
if (dataBreakpoints) checkDataBreakpointFromTo(this, 0, true);
return res;
}
function arrayReverseOp(this: any) {
record(this);
if (dataBreakpoints) checkDataBreakpointFromTo(this.a, 0, false);
nativeArray.reverse.__effectful__nativeCall(this.a);
}
export function arrayReverse(this: any[]): any[] {
if (journal.enabled && context.call === arrayReverse) {
context.call = null;
record1(arrayReverseOp, this);
}
if (dataBreakpoints) checkDataBreakpointFromTo(this, 0, false);
return nativeArray.reverse.__effectful__nativeCall(this);
}
regOpaqueObject(arrayReverseOp, "#arr$reverse");
export function arraySort(this: any[], pred: any): any[] {
if (journal.enabled && context.call === arraySort) {
context.call = null;
record4(spliceOp, this, 0, this.length, Array.from(this));
}
if (dataBreakpoints) checkDataBreakpointFromTo(this, 0, false);
return nativeArray.sort.__effectful__nativeCall(this, pred);
}
export function arraySplice(
this: any[],
from: number,
del: number,
...ins: any[]
) {
if (dataBreakpoints) {
const diff = ins.length - (del || 0);
const changed = diff !== 0;
const start = from < 0 ? this.length + from : from;
checkDataBreakpointFromTo(
this,
start,
changed,
changed
? diff < 0
? this.length
: this.length + diff
: start + (del || 0)
);
}
if (journal.enabled && context.call === arraySplice) {
context.call = null;
return spliceImpl(this, from, del, ins);
}
return __effectful__nativeApply(nativeArray.splice, this, arguments);
}
function typedArraySetOp(this: any) {
const { a: arr, b: value, c: offset } = this;
this.b = arr.slice(offset, offset + value.length);
record(this);
nativeTypedArray.set.call(arr, value, offset);
}
regOpaqueObject(typedArraySetOp, "#tarr$set");
export function typedArraySort(this: any[], pred: any): any[] {
if (journal.enabled && context.call === typedArraySort) {
context.call = null;
record3(typedArraySetOp, this, this.slice(0), 0);
}
return nativeTypedArray.sort.call(this, pred);
}
export function typedArrayReverse(this: any[], pred: any): any[] {
if (journal.enabled && context.call === typedArrayReverse) {
context.call = null;
record3(typedArraySetOp, this, this.slice(0), 0);
}
return nativeTypedArray.reverse.call(this, pred);
}
export function typedArraySet(this: any, value: any, offset: number = 0) {
if (journal.enabled && context.call === typedArraySet) {
context.call = null;
record3(
typedArraySetOp,
this,
this.slice(offset, value.length + offset),
offset
);
}
return nativeTypedArray.set.call(this, value, offset);
}
export function typedArrayFill(
this: any,
value: any,
offset: number = 0,
end: number = this.length
) {
if (journal.enabled && context.call === typedArrayFill) {
context.call = null;
record3(typedArraySetOp, this, this.slice(offset, end), offset);
}
return nativeTypedArray.fill.call(this, value, offset);
}
function __effectful__reflectApply(target: any, self: any, args: any[]) {
if (context.call === __effectful__reflectApply) context.call = target;
return nativeReflect.apply(target, self, args);
}
function __effectful__reflectConstruct(
target: any,
args: any[],
newTarget: any
) {
if (context.call === __effectful__reflectConstruct) context.call = target;
return arguments.length < 3
? nativeReflect.construct(target, args)
: nativeReflect.construct(target, args, newTarget);
}
function reflectGetOwnPropertyDescriptor(obj: any, prop: string) {
if (context.call === reflectGetOwnPropertyDescriptor)
context.call = Object.getOwnPropertyDescriptor;
return nativeReflect.getOwnPropertyDescriptor(obj, prop);
}
function reflectGetPrototypeOf(obj: any) {
if (context.call === reflectGetPrototypeOf)
context.call = Object.getPrototypeOf;
return nativeReflect.getPrototypeOf(obj);
}
function reflectSetPrototypeOf(obj: any, prot: object | null) {
if (context.call === reflectSetPrototypeOf)
context.call = Object.setPrototypeOf;
return nativeReflect.setPrototypeOf(obj, prot);
}
function reflectHas(obj: any, prop: string | number | symbol) {
if (context.call === reflectHas) context.call = has;
return nativeReflect.has(obj, prop);
}
function reflectGet(obj: any, prop: string | number | symbol, receiver?: any) {
if (context.call === reflectGet) context.call = get;
return arguments.length < 3
? nativeReflect.get(obj, prop)
: nativeReflect.get(obj, prop, receiver);
}
function reflectPreventExtension(obj: any) {
if (context.call === reflectPreventExtension)
context.call = objectPreventExtensions;
switch (typeof obj) {
case "function":
case "object":
return objectPreventExtensions(obj);
default:
throw new TypeError(`${obj} is not an object`);
}
}
function reflectOwnKeys(value: any) {
const unwrap = proxies?.get(value);
if (unwrap) {
if (unwrap.flags & ProxyTrapFlags.OwnKeys) {
context.call = objectKeys;
return <any>nativeReflect.ownKeys(value);
}
value = unwrap.obj;
}
let descr = getObjKeys(value);
if (!descr) return nativeReflect.ownKeys(value);
const res = nativeObject.getOwnPropertyNames(value).filter(isInt);
const keys = descr.strKeys;
for (let i = keys.prev; i !== keys; i = i.prev) res.push(i.name);
const symKeys = descr.symKeys;
for (let i = symKeys.prev; i !== symKeys; i = i.prev) res.push(i.name);
return res;
}
function reflectSet(target: any, name: string, value: any, receiver?: any) {
if (arguments.length < 4) receiver = target;
return setImpl(target, name, value, receiver);
}
regOpaqueObject(reflectSet, "@effectful/debugger/reflectSet");
if (config.timeTravel && config.patchRT) {
patch(Reflect, "apply", __effectful__reflectApply);
patch(Reflect, "construct", __effectful__reflectConstruct);
patch(Reflect, "defineProperty", reflectDefineProperty);
patch(Reflect, "set", reflectSet);
patch(Reflect, "deleteProperty", del);
patch(Reflect, "getOwnPropertyDescriptor", reflectGetOwnPropertyDescriptor);
patch(Reflect, "getPrototypeOf", reflectGetPrototypeOf);
patch(Reflect, "setPrototypeOf", reflectSetPrototypeOf);
patch(Reflect, "has", reflectHas);
patch(Reflect, "get", reflectGet);
patch(Reflect, "isExtensible", objectIsExtensible);
patch(Reflect, "preventExtension", reflectPreventExtension);
patch(Reflect, "ownKeys", reflectOwnKeys);
}
export function patchWithPolifil(
proto: any,
name: string,
defaultImpl: (this: any, ...vals: any[]) => any,
polyfillImpl: (this: any, ...vals: any[]) => any
) {
function impl(this: any) {
const method: any = proxies?.has(this) ? polyfillImpl : defaultImpl;
if (context.call === impl) context.call = method;
return __effectful__nativeApply(method, this, arguments);
}
regOpaqueObject(
impl,
`@effectful/debugger/${proto.constructor.name}#${name}`
);
patch(proto, name, impl);
}
export function patchWithCopy(proto: any, name: string) {
const orig = proto[name];
return patchWithPolifil(
proto,
name,
orig,
Instr.useArrCopy(proto.slice, orig, arraySet)
);
} | the_stack |
import React, {Component, createRef, Dispatch} from 'react';
import Console from 'global/console';
import {bindActionCreators} from 'redux';
import styled, {ThemeProvider, withTheme} from 'styled-components';
import {createSelector} from 'reselect';
import {connect as keplerGlConnect} from 'connect/keplergl-connect';
import {IntlProvider} from 'react-intl';
import {messages} from '../localization';
import {RootContext} from 'components/context';
import {OnErrorCallBack, OnSuccessCallBack} from 'actions/provider-actions';
import * as VisStateActions from 'actions/vis-state-actions';
import * as MapStateActions from 'actions/map-state-actions';
import * as MapStyleActions from 'actions/map-style-actions';
import * as UIStateActions from 'actions/ui-state-actions';
import * as ProviderActions from 'actions/provider-actions';
type KeplerGlActions = {
visStateActions: typeof VisStateActions;
mapStateActions: typeof MapStateActions;
mapStyleActions: typeof MapStyleActions;
uiStateActions: typeof UIStateActions;
providerActions: typeof ProviderActions;
};
import {
DIMENSIONS,
KEPLER_GL_NAME,
KEPLER_GL_VERSION,
THEME,
DEFAULT_MAPBOX_API_URL,
GEOCODER_DATASET_NAME
} from 'constants/default-settings';
import {MISSING_MAPBOX_TOKEN} from 'constants/user-feedbacks';
import SidePanelFactory from './side-panel';
import MapContainerFactory from './map-container';
import MapsLayoutFactory from './maps-layout';
import BottomWidgetFactory from './bottom-widget';
import ModalContainerFactory from './modal-container';
import PlotContainerFactory from './plot-container';
import NotificationPanelFactory from './notification-panel';
import GeoCoderPanelFactory from './geocoder-panel';
import {filterObjectByPredicate, generateHashId} from 'utils/utils';
import {validateToken} from 'utils/mapbox-utils';
import {mergeMessages} from 'utils/locale-utils';
import {theme as basicTheme, themeLT, themeBS} from 'styles/base';
import {observeDimensions, unobserveDimensions} from '../utils/observe-dimensions';
import {KeplerGlState} from 'reducers/core';
import {Provider} from 'cloud-providers';
// Maybe we should think about exporting this or creating a variable
// as part of the base.js theme
const GlobalStyle = styled.div`
font-family: ${props => props.theme.fontFamily};
font-weight: ${props => props.theme.fontWeight};
font-size: ${props => props.theme.fontSize};
line-height: ${props => props.theme.lineHeight};
*,
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
ul {
margin: 0;
padding: 0;
}
li {
margin: 0;
}
a {
text-decoration: none;
color: ${props => props.theme.labelColor};
}
.mapboxgl-ctrl .mapboxgl-ctrl-logo {
display: none;
}
`;
interface BottomWidgetOuterProps {
absolute?: boolean;
}
const BottomWidgetOuter = styled.div<BottomWidgetOuterProps>(
({absolute}) => `
${absolute ? 'position: absolute; bottom: 0; right: 0;' : ''}
pointer-events: none; /* prevent padding from blocking input */
& > * {
/* all children should allow input */
pointer-events: all;
}`
);
export const mapFieldsSelector = (props: KeplerGLProps) => ({
getMapboxRef: props.getMapboxRef,
mapboxApiAccessToken: props.mapboxApiAccessToken,
mapboxApiUrl: props.mapboxApiUrl ? props.mapboxApiUrl : DEFAULT_KEPLER_GL_PROPS.mapboxApiUrl,
mapState: props.mapState,
mapStyle: props.mapStyle,
onDeckInitialized: props.onDeckInitialized,
onViewStateChange: props.onViewStateChange,
deckGlProps: props.deckGlProps,
uiStateActions: props.uiStateActions,
visStateActions: props.visStateActions,
mapStateActions: props.mapStateActions,
// visState
editor: props.visState.editor,
datasets: props.visState.datasets,
layers: props.visState.layers,
layerOrder: props.visState.layerOrder,
layerData: props.visState.layerData,
layerBlending: props.visState.layerBlending,
filters: props.visState.filters,
interactionConfig: props.visState.interactionConfig,
hoverInfo: props.visState.hoverInfo,
clicked: props.visState.clicked,
mousePos: props.visState.mousePos,
animationConfig: props.visState.animationConfig,
// uiState
activeSidePanel: props.uiState.activeSidePanel,
mapControls: props.uiState.mapControls,
readOnly: props.uiState.readOnly,
locale: props.uiState.locale
});
export function getVisibleDatasets(datasets) {
// We don't want Geocoder dataset to be present in SidePanel dataset list
return filterObjectByPredicate(datasets, (key, value) => key !== GEOCODER_DATASET_NAME);
}
export const sidePanelSelector = (props: KeplerGLProps, availableProviders, filteredDatasets) => ({
appName: props.appName ? props.appName : DEFAULT_KEPLER_GL_PROPS.appName,
version: props.version ? props.version : DEFAULT_KEPLER_GL_PROPS.version,
appWebsite: props.appWebsite,
mapStyle: props.mapStyle,
onSaveMap: props.onSaveMap,
uiState: props.uiState,
mapStyleActions: props.mapStyleActions,
visStateActions: props.visStateActions,
uiStateActions: props.uiStateActions,
mapStateActions: props.mapStateActions,
datasets: filteredDatasets,
filters: props.visState.filters,
layers: props.visState.layers,
layerOrder: props.visState.layerOrder,
layerClasses: props.visState.layerClasses,
interactionConfig: props.visState.interactionConfig,
mapInfo: props.visState.mapInfo,
layerBlending: props.visState.layerBlending,
width: props.sidePanelWidth ? props.sidePanelWidth : DEFAULT_KEPLER_GL_PROPS.width,
availableProviders,
mapSaved: props.providerState.mapSaved
});
export const plotContainerSelector = (props: KeplerGLProps) => ({
width: props.width,
height: props.height,
exportImageSetting: props.uiState.exportImage,
mapFields: mapFieldsSelector(props),
addNotification: props.uiStateActions.addNotification,
setExportImageSetting: props.uiStateActions.setExportImageSetting,
setExportImageDataUri: props.uiStateActions.setExportImageDataUri,
setExportImageError: props.uiStateActions.setExportImageError,
splitMaps: props.visState.splitMaps
});
export const isSplitSelector = (props: KeplerGLProps) =>
props.visState.splitMaps && props.visState.splitMaps.length > 1;
export const bottomWidgetSelector = (props: KeplerGLProps, theme) => ({
filters: props.visState.filters,
datasets: props.visState.datasets,
uiState: props.uiState,
layers: props.visState.layers,
animationConfig: props.visState.animationConfig,
visStateActions: props.visStateActions,
toggleModal: props.uiStateActions.toggleModal,
sidePanelWidth: props.uiState.readOnly ? 0 : props.sidePanelWidth + theme.sidePanel.margin.left
});
export const modalContainerSelector = (props: KeplerGLProps, rootNode) => ({
appName: props.appName ? props.appName : DEFAULT_KEPLER_GL_PROPS.appName,
mapStyle: props.mapStyle,
visState: props.visState,
mapState: props.mapState,
uiState: props.uiState,
providerState: props.providerState,
mapboxApiAccessToken: props.mapboxApiAccessToken,
mapboxApiUrl: props.mapboxApiUrl,
visStateActions: props.visStateActions,
uiStateActions: props.uiStateActions,
mapStyleActions: props.mapStyleActions,
providerActions: props.providerActions,
rootNode,
// User defined cloud provider props
cloudProviders: props.cloudProviders
? props.cloudProviders
: DEFAULT_KEPLER_GL_PROPS.cloudProviders,
onExportToCloudSuccess: props.onExportToCloudSuccess,
onLoadCloudMapSuccess: props.onLoadCloudMapSuccess,
onLoadCloudMapError: props.onLoadCloudMapError,
onExportToCloudError: props.onExportToCloudError
});
export const geoCoderPanelSelector = (props: KeplerGLProps) => ({
isGeocoderEnabled: props.visState.interactionConfig.geocoder.enabled,
mapboxApiAccessToken: props.mapboxApiAccessToken,
mapState: props.mapState,
updateVisData: props.visStateActions.updateVisData,
removeDataset: props.visStateActions.removeDataset,
updateMap: props.mapStateActions.updateMap
});
export const notificationPanelSelector = (props: KeplerGLProps) => ({
removeNotification: props.uiStateActions.removeNotification,
notifications: props.uiState.notifications
});
export const DEFAULT_KEPLER_GL_PROPS = {
mapStyles: [],
mapStylesReplaceDefault: false,
mapboxApiUrl: DEFAULT_MAPBOX_API_URL,
width: 800,
height: 800,
appName: KEPLER_GL_NAME,
version: KEPLER_GL_VERSION,
sidePanelWidth: DIMENSIONS.sidePanel.width,
theme: {},
cloudProviders: [],
readOnly: false
};
type KeplerGLBasicProps = {
mapboxApiAccessToken: string;
mapboxApiUrl?: string;
id: string;
width?: number;
height?: number;
appWebsite?: any;
onSaveMap?: () => void;
onViewStateChange?: () => void;
onDeckInitialized?: () => void;
onKeplerGlInitialized?: () => void;
getMapboxRef?: () => React.RefObject<any>;
mapStyles?: {id: string; style?: object}[];
mapStylesReplaceDefault?: boolean;
appName?: string;
version?: string;
sidePanelWidth?: number;
theme?: object;
cloudProviders?: Provider[];
deckGlProps?: object;
onLoadCloudMapSuccess?: OnSuccessCallBack;
onLoadCloudMapError?: OnErrorCallBack;
onExportToCloudSuccess?: OnSuccessCallBack;
onExportToCloudError?: OnErrorCallBack;
readOnly?: boolean;
localeMessages?: {[key: string]: {[key: string]: string}};
dispatch: Dispatch<any>;
};
type KeplerGLProps = KeplerGlState & KeplerGlActions & KeplerGLBasicProps;
KeplerGlFactory.deps = [
BottomWidgetFactory,
GeoCoderPanelFactory,
MapContainerFactory,
MapsLayoutFactory,
ModalContainerFactory,
SidePanelFactory,
PlotContainerFactory,
NotificationPanelFactory
];
function KeplerGlFactory(
BottomWidget: ReturnType<typeof BottomWidgetFactory>,
GeoCoderPanel: ReturnType<typeof GeoCoderPanelFactory>,
MapContainer: ReturnType<typeof MapContainerFactory>,
MapsLayout: ReturnType<typeof MapsLayoutFactory>,
ModalContainer: ReturnType<typeof ModalContainerFactory>,
SidePanel: ReturnType<typeof SidePanelFactory>,
PlotContainer: ReturnType<typeof PlotContainerFactory>,
NotificationPanel: ReturnType<typeof NotificationPanelFactory>
): React.ComponentType<KeplerGLBasicProps & {selector: (...args: any[]) => KeplerGlState}> {
/** @typedef {import('./kepler-gl').UnconnectedKeplerGlProps} KeplerGlProps */
/** @augments React.Component<KeplerGlProps> */
class KeplerGL extends Component<KeplerGLProps & {selector: (...args: any[]) => KeplerGlState}> {
static defaultProps = DEFAULT_KEPLER_GL_PROPS;
state = {
dimensions: null
};
componentDidMount() {
this._validateMapboxToken();
this._loadMapStyle();
if (typeof this.props.onKeplerGlInitialized === 'function') {
this.props.onKeplerGlInitialized();
}
if (this.root.current instanceof HTMLElement) {
observeDimensions(this.root.current, this._handleResize);
}
}
componentWillUnmount() {
if (this.root.current instanceof HTMLElement) {
unobserveDimensions(this.root.current);
}
}
_handleResize = dimensions => {
this.setState({dimensions});
};
static contextType = RootContext;
root = createRef<HTMLDivElement>();
bottomWidgetRef = createRef();
/* selectors */
themeSelector = props => props.theme;
availableThemeSelector = createSelector(this.themeSelector, theme =>
typeof theme === 'object'
? {
...basicTheme,
...theme
}
: theme === THEME.light
? themeLT
: theme === THEME.base
? themeBS
: theme
);
datasetsSelector = props => props.visState.datasets;
filteredDatasetsSelector = createSelector(this.datasetsSelector, getVisibleDatasets);
availableProviders = createSelector(
(props: KeplerGLProps) => props.cloudProviders,
providers =>
Array.isArray(providers) && providers.length
? {
hasStorage: providers.some(p => p.hasPrivateStorage()),
hasShare: providers.some(p => p.hasSharingUrl())
}
: {}
);
localeMessagesSelector = createSelector(
(props: KeplerGLProps) => props.localeMessages,
customMessages => (customMessages ? mergeMessages(messages, customMessages) : messages)
);
/* private methods */
_validateMapboxToken() {
const {mapboxApiAccessToken} = this.props;
if (!validateToken(mapboxApiAccessToken)) {
Console.warn(MISSING_MAPBOX_TOKEN);
}
}
_loadMapStyle = () => {
const defaultStyles = Object.values(this.props.mapStyle.mapStyles);
// add id to custom map styles if not given
const customStyles = (this.props.mapStyles || []).map(ms => ({
...ms,
id: ms.id || generateHashId()
}));
const allStyles = [...customStyles, ...defaultStyles].reduce(
(accu, style) => {
const hasStyleObject = style.style && typeof style.style === 'object';
accu[hasStyleObject ? 'toLoad' : 'toRequest'][style.id] = style;
return accu;
},
{toLoad: {}, toRequest: {}}
);
this.props.mapStyleActions.loadMapStyles(allStyles.toLoad);
this.props.mapStyleActions.requestMapStyles(allStyles.toRequest);
};
render() {
const {
id = 'map',
width = DEFAULT_KEPLER_GL_PROPS.width,
height = DEFAULT_KEPLER_GL_PROPS.height,
uiState,
visState,
// readOnly override
readOnly
} = this.props;
const dimensions = this.state.dimensions || {width, height};
const {
splitMaps, // this will store support for split map view is necessary
interactionConfig
} = visState;
const isSplit = isSplitSelector(this.props);
const theme = this.availableThemeSelector(this.props);
const localeMessages = this.localeMessagesSelector(this.props);
const isExportingImage = uiState.exportImage.exporting;
const availableProviders = this.availableProviders(this.props);
const mapFields = mapFieldsSelector(this.props);
const filteredDatasets = this.filteredDatasetsSelector(this.props);
const sideFields = sidePanelSelector(this.props, availableProviders, filteredDatasets);
const plotContainerFields = plotContainerSelector(this.props);
const bottomWidgetFields = bottomWidgetSelector(this.props, theme);
const modalContainerFields = modalContainerSelector(this.props, this.root.current);
const geoCoderPanelFields = geoCoderPanelSelector(this.props);
const notificationPanelFields = notificationPanelSelector(this.props);
const mapContainers = !isSplit
? [<MapContainer primary={true} key={0} index={0} {...mapFields} mapLayers={null} />]
: splitMaps.map((settings, index) => (
<MapContainer
key={index}
index={index}
primary={index === 1}
{...mapFields}
mapLayers={splitMaps[index].layers}
/>
));
return (
<RootContext.Provider value={this.root}>
<IntlProvider locale={uiState.locale} messages={localeMessages[uiState.locale]}>
<ThemeProvider theme={theme}>
<GlobalStyle
className="kepler-gl"
id={`kepler-gl__${id}`}
style={{
display: 'flex',
flexDirection: 'column',
position: 'relative',
width: `${width}px`,
height: `${height}px`
}}
ref={this.root}
>
<NotificationPanel {...notificationPanelFields} />
{!uiState.readOnly && !readOnly && <SidePanel {...sideFields} />}
<MapsLayout className="maps">{mapContainers}</MapsLayout>
{isExportingImage && <PlotContainer {...plotContainerFields} />}
{interactionConfig.geocoder.enabled && <GeoCoderPanel {...geoCoderPanelFields} />}
<BottomWidgetOuter absolute>
<BottomWidget
ref={this.bottomWidgetRef}
{...bottomWidgetFields}
containerW={dimensions.width}
/>
</BottomWidgetOuter>
<ModalContainer
{...modalContainerFields}
containerW={dimensions.width}
containerH={dimensions.height}
/>
</GlobalStyle>
</ThemeProvider>
</IntlProvider>
</RootContext.Provider>
);
}
}
return keplerGlConnect(mapStateToProps, makeMapDispatchToProps)(withTheme(KeplerGL));
}
export function mapStateToProps(state: KeplerGlState, props: KeplerGLProps) {
return {
...props,
visState: state.visState,
mapStyle: state.mapStyle,
mapState: state.mapState,
uiState: state.uiState,
providerState: state.providerState
};
}
const defaultUserActions = {};
const getDispatch = (dispatch, props) => dispatch;
const getUserActions = (dispatch, props) => props.actions || defaultUserActions;
/** @type {() => import('reselect').OutputParametricSelector<any, any, any, any>} */
function makeGetActionCreators() {
return createSelector([getDispatch, getUserActions], (dispatch, userActions) => {
const [visStateActions, mapStateActions, mapStyleActions, uiStateActions, providerActions] = [
VisStateActions,
MapStateActions,
MapStyleActions,
UIStateActions,
ProviderActions
].map(actions => bindActionCreators(mergeActions(actions, userActions), dispatch));
return {
visStateActions,
mapStateActions,
mapStyleActions,
uiStateActions,
providerActions,
dispatch
};
});
}
function makeMapDispatchToProps() {
const getActionCreators = makeGetActionCreators();
const mapDispatchToProps = (dispatch, ownProps) => {
const groupedActionCreators = getActionCreators(dispatch, ownProps);
return {
...groupedActionCreators,
dispatch
};
};
return mapDispatchToProps;
}
/**
* Override default kepler.gl actions with user defined actions using the same key
*/
function mergeActions(actions, userActions) {
const overrides = {};
for (const key in userActions) {
if (userActions.hasOwnProperty(key) && actions.hasOwnProperty(key)) {
overrides[key] = userActions[key];
}
}
return {...actions, ...overrides};
}
export default KeplerGlFactory; | the_stack |
'use strict';
// Note: vscode-nls *MUST* be configured before loading any other modules
// to ensure loadMessageBundle is not called before vscode-nls has been
// configured
import * as nls from 'vscode-nls';
nls.config({ messageFormat: nls.MessageFormat.both })();
import * as vscode from 'vscode';
import * as semver from 'semver';
import * as path from 'path';
import { Reporter } from './util/Reporter';
import { ExtensionUtil } from './util/ExtensionUtil';
import { VSCodeBlockchainOutputAdapter } from './logging/VSCodeBlockchainOutputAdapter';
import { DependencyManager } from './dependencies/DependencyManager';
import { TemporaryCommandRegistry } from './dependencies/TemporaryCommandRegistry';
import { ExtensionCommands } from '../ExtensionCommands';
import { version as currentExtensionVersion } from '../package.json';
import { SettingConfigurations } from './configurations';
import { UserInputUtil } from './commands/UserInputUtil';
import { GlobalState, ExtensionData } from './util/GlobalState';
import { FabricWalletRegistry, FabricEnvironmentRegistry, LogType, FabricGatewayRegistry, FileSystemUtil, FabricEnvironmentRegistryEntry, EnvironmentFlags, FabricRuntimeUtil, EnvironmentType } from 'ibm-blockchain-platform-common';
import { RepositoryRegistry } from './registries/RepositoryRegistry';
import { Dependencies } from './dependencies/Dependencies';
import { LocalMicroEnvironmentManager } from './fabric/environments/LocalMicroEnvironmentManager';
export async function activate(context: vscode.ExtensionContext): Promise<void> {
GlobalState.setExtensionContext(context);
const outputAdapter: VSCodeBlockchainOutputAdapter = VSCodeBlockchainOutputAdapter.instance();
const originalExtensionData: ExtensionData = GlobalState.get();
if (originalExtensionData.createOneOrgLocalFabric === undefined) {
originalExtensionData.createOneOrgLocalFabric = true;
}
if (originalExtensionData.deletedOneOrgLocalFabric === undefined) {
originalExtensionData.deletedOneOrgLocalFabric = false;
}
const newExtensionData: ExtensionData = {
activationCount: originalExtensionData.activationCount + 1,
version: currentExtensionVersion,
migrationCheck: 2, // Every time we change the setting configurations we need to change this to any other value
generatorVersion: originalExtensionData.generatorVersion,
preReqPageShown: originalExtensionData.preReqPageShown,
dockerForWindows: originalExtensionData.dockerForWindows,
createOneOrgLocalFabric: originalExtensionData.createOneOrgLocalFabric,
deletedOneOrgLocalFabric: originalExtensionData.deletedOneOrgLocalFabric,
shownFirstSubmissionSurveyURL: originalExtensionData.shownFirstSubmissionSurveyURL,
};
let extDir: string = SettingConfigurations.getExtensionDir();
extDir = FileSystemUtil.getDirPath(extDir);
FabricWalletRegistry.instance().setRegistryPath(extDir);
FabricGatewayRegistry.instance().setRegistryPath(extDir);
FabricEnvironmentRegistry.instance().setRegistryPath(extDir);
RepositoryRegistry.instance().setRegistryPath(extDir);
const isIBMer: boolean = ExtensionUtil.checkIfIBMer();
if (originalExtensionData.migrationCheck !== newExtensionData.migrationCheck) {
// add migration code here
}
const extensionUpdated: boolean = newExtensionData.version !== originalExtensionData.version;
// Determine if this is a major version upgrade
let extensionUpgraded: boolean = false;
if (originalExtensionData.version && newExtensionData.version) {
const semverOriginal: number = semver.major(originalExtensionData.version);
const semverNew: number = semver.major(newExtensionData.version);
extensionUpgraded = semverNew > semverOriginal
}
await GlobalState.update(newExtensionData);
const packageJson: any = ExtensionUtil.getPackageJSON();
if (packageJson.production !== true) {
await Reporter.instance().dispose();
}
// Show the output adapter if the extension has been updated.
if (extensionUpdated) {
outputAdapter.show();
if (!originalExtensionData.version) {
Reporter.instance().sendTelemetryEvent('newInstall', { IBM: isIBMer + '' });
} else {
Reporter.instance().sendTelemetryEvent('updatedInstall', { IBM: isIBMer + '' });
}
}
// At the moment, the 'Open Log File' doesn't display extension log files to open. https://github.com/Microsoft/vscode/issues/43064
outputAdapter.log(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true); // Let users know how to get the log file
outputAdapter.log(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
try {
const dependencyManager: DependencyManager = DependencyManager.instance();
const dependencies: Dependencies = await dependencyManager.getPreReqVersions();
const bypassPreReqs: boolean = vscode.workspace.getConfiguration().get(SettingConfigurations.EXTENSION_BYPASS_PREREQS);
let dependenciesInstalled: boolean;
if (!bypassPreReqs) {
dependenciesInstalled = await dependencyManager.hasPreReqsInstalled(dependencies);
}
const tempCommandRegistry: TemporaryCommandRegistry = TemporaryCommandRegistry.instance();
// Register the 'Open Pre Req' command
context = await ExtensionUtil.registerPreActivationCommands(context);
if (extensionUpgraded) {
// If user upgraded major versions, if old local ansible environmens present ask if they should be teardown
// This needs to happen before rendering pannels, otherwise the user will see the old environments
const v1ExtDir: string = extDir.replace(`${path.sep}v2`, '');
FabricEnvironmentRegistry.instance().setRegistryPath(v1ExtDir);
let v1EnvironmentEntries: FabricEnvironmentRegistryEntry[] = await FabricEnvironmentRegistry.instance().getAll();
if (v1EnvironmentEntries.length > 0) {
v1EnvironmentEntries = v1EnvironmentEntries.filter((entry: FabricEnvironmentRegistryEntry) => entry.environmentType === EnvironmentType.MANAGED );
if (v1EnvironmentEntries.length > 0) {
const teardown: boolean = await UserInputUtil.showConfirmationWarningMessage('Detected old local environments which can not be used with this upgrade. Would you like to teardown these environments?');
if (teardown) {
for (const entry of v1EnvironmentEntries) {
try {
await vscode.commands.executeCommand(ExtensionCommands.TEARDOWN_FABRIC, undefined, true, entry.name, true);
outputAdapter.log(LogType.INFO, undefined, `Successful teardown of ${entry.name} environment.`);
} catch (error) {
outputAdapter.log(LogType.ERROR, undefined, `Unable to teardown ${entry.name} environment: ${error.toString()}.`);
}
}
}
}
}
FabricEnvironmentRegistry.instance().setRegistryPath(extDir);
}
let createLocalEnvironment: boolean = false;
// Get all old local and ansible environments
const oldAnsibleEnvironmentEntries: FabricEnvironmentRegistryEntry[] = await FabricEnvironmentRegistry.instance().getAll([EnvironmentFlags.ANSIBLE]);
if (oldAnsibleEnvironmentEntries.length > 0) {
// Delete any old local environments.
for (const entry of oldAnsibleEnvironmentEntries) {
await vscode.commands.executeCommand(ExtensionCommands.DELETE_ENVIRONMENT, entry, true, true);
if (entry.name === FabricRuntimeUtil.LOCAL_FABRIC) {
createLocalEnvironment = true;
}
}
}
const _settings: any = vscode.workspace.getConfiguration().get(SettingConfigurations.FABRIC_RUNTIME, vscode.ConfigurationTarget.Global);
const localSettings: any = JSON.parse(JSON.stringify(_settings));
let updateSettings: boolean = false;
for (const [key, value] of Object.entries(localSettings)) {
// Delete any settings which don't have number values.
if (typeof value !== 'number') {
delete localSettings[key];
updateSettings = true;
}
}
if (updateSettings) {
await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, localSettings, vscode.ConfigurationTarget.Global);
}
if (createLocalEnvironment) {
await LocalMicroEnvironmentManager.instance().initialize(FabricRuntimeUtil.LOCAL_FABRIC, 1);
}
// Only show the release notes if the extension has updated. This doesn't include the very first install.
if (extensionUpdated && originalExtensionData.version) {
await vscode.commands.executeCommand(ExtensionCommands.OPEN_RELEASE_NOTES);
}
if (dependenciesInstalled || bypassPreReqs) {
tempCommandRegistry.createTempCommands(true);
await ExtensionUtil.setupCommands();
} else {
tempCommandRegistry.createTempCommands(false, ExtensionCommands.OPEN_PRE_REQ_PAGE);
}
// Open the PreReq page if the user hasn't got all the required dependencies OR if the user has never seen the PreReq page before
if (!bypassPreReqs) {
if (!originalExtensionData.preReqPageShown) {
// Show pre req page
await vscode.commands.executeCommand(ExtensionCommands.OPEN_PRE_REQ_PAGE, dependencies);
// Update global state
newExtensionData.preReqPageShown = true;
await GlobalState.update(newExtensionData);
} else if (!dependenciesInstalled) {
// Show prereq page if they don't have everything installed
await vscode.commands.executeCommand(ExtensionCommands.OPEN_PRE_REQ_PAGE, dependencies);
}
}
GlobalState.setExtensionContext(context);
// We only want to do this stuff if the extension has all the required dependencies
if (dependenciesInstalled || bypassPreReqs) {
await ExtensionUtil.completeActivation(extensionUpdated);
if (extensionUpgraded) {
// If user has migrated and installed a new major version
const whatsNewPrompt: string = 'Learn more';
const response: string = await vscode.window.showInformationMessage(`You have successfully updated to version 2 of the IBM Blockchain Platform extension. Lots of changes have happened since version 1, so be sure to check what's new!`, whatsNewPrompt);
if (response === whatsNewPrompt) {
await vscode.commands.executeCommand(ExtensionCommands.OPEN_FABRIC_2_PAGE);
}
}
}
} catch (error) {
outputAdapter.log(LogType.ERROR, undefined, `Failed to activate extension: ${error.toString()}`, error.stack);
Reporter.instance().sendTelemetryEvent('activationFailed', { activationError: error.message });
await UserInputUtil.failedActivationWindow(error.message);
}
}
export async function deactivate(): Promise<void> {
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
await Reporter.instance().dispose();
ExtensionUtil.disposeExtension(context);
} | the_stack |
import React, { useMemo } from 'react';
import { Link } from 'react-router-dom';
import { Form, Select, Tag, Tooltip, Typography } from 'antd';
import styled from 'styled-components';
import { useEntityRegistry } from '../useEntityRegistry';
import { useAppConfig } from '../useAppConfig';
import { useGetSearchResultsForMultipleLazyQuery, useGetSearchResultsLazyQuery } from '../../graphql/search.generated';
import { ResourceFilter, PolicyType, EntityType } from '../../types.generated';
import {
convertLegacyResourceFilter,
createCriterionValue,
createCriterionValueWithEntity,
EMPTY_POLICY,
getFieldValues,
mapResourceTypeToDisplayName,
mapResourceTypeToEntityType,
mapResourceTypeToPrivileges,
setFieldValues,
} from './policyUtils';
type Props = {
policyType: PolicyType;
resources?: ResourceFilter;
setResources: (resources: ResourceFilter) => void;
privileges: Array<string>;
setPrivileges: (newPrivs: Array<string>) => void;
};
const SearchResultContainer = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px;
`;
const PrivilegesForm = styled(Form)`
margin: 12px;
margin-top: 36px;
margin-bottom: 40px;
`;
/**
* Component used to construct the "privileges" and "resources" portion of a DataHub
* access Policy.
*/
export default function PolicyPrivilegeForm({
policyType,
resources: maybeResources,
setResources,
privileges,
setPrivileges,
}: Props) {
const entityRegistry = useEntityRegistry();
// Configuration used for displaying options
const {
config: { policiesConfig },
} = useAppConfig();
const resources: ResourceFilter = convertLegacyResourceFilter(maybeResources) || EMPTY_POLICY.resources;
const resourceTypes = getFieldValues(resources.filter, 'RESOURCE_TYPE') || [];
const resourceEntities = getFieldValues(resources.filter, 'RESOURCE_URN') || [];
const getDisplayName = (entity) => {
if (!entity) {
return null;
}
return entityRegistry.getDisplayName(entity.type, entity);
};
const resourceUrnToDisplayName = new Map();
resourceEntities.forEach((resourceEntity) => {
resourceUrnToDisplayName[resourceEntity.value] = getDisplayName(resourceEntity.entity);
});
// Search for resources
const [searchResources, { data: resourcesSearchData }] = useGetSearchResultsForMultipleLazyQuery();
const resourceSearchResults = resourcesSearchData?.searchAcrossEntities?.searchResults;
// Same for domains
const domains = getFieldValues(resources.filter, 'DOMAIN') || [];
const domainUrnToDisplayName = new Map();
domains.forEach((domainEntity) => {
domainUrnToDisplayName[domainEntity.value] = getDisplayName(domainEntity.entity);
});
// Search for domains
const [searchDomains, { data: domainsSearchData }] = useGetSearchResultsLazyQuery();
const domainSearchResults = domainsSearchData?.search?.searchResults;
// Whether to show the resource filter inputs including "resource type", "resource", and "domain"
const showResourceFilterInput = policyType !== PolicyType.Platform;
// Current Select dropdown values
const resourceTypeSelectValue = resourceTypes.map((criterionValue) => criterionValue.value);
const resourceSelectValue = resourceEntities.map((criterionValue) => criterionValue.value);
const domainSelectValue = getFieldValues(resources.filter, 'DOMAIN').map((criterionValue) => criterionValue.value);
const privilegesSelectValue = privileges;
// Construct privilege options for dropdown
const platformPrivileges = policiesConfig?.platformPrivileges || [];
const resourcePrivileges = useMemo(() => policiesConfig?.resourcePrivileges || [], [policiesConfig]);
const resourcePrivilegesForType = useMemo(
() => mapResourceTypeToPrivileges(resourceTypeSelectValue, resourcePrivileges),
[resourceTypeSelectValue, resourcePrivileges],
);
const privilegeOptions = policyType === PolicyType.Platform ? platformPrivileges : resourcePrivilegesForType;
const getEntityFromSearchResults = (searchResults, urn) =>
searchResults?.map((result) => result.entity).find((entity) => entity.urn === urn);
// When a privilege is selected, add its type to the privileges list
const onSelectPrivilege = (privilege: string) => {
if (privilege === 'All') {
setPrivileges(privilegeOptions.map((priv) => priv.type) as never[]);
} else {
const newPrivs = [...privileges, privilege];
setPrivileges(newPrivs as never[]);
}
};
// When a privilege is selected, remove its type from the privileges list
const onDeselectPrivilege = (privilege: string) => {
let newPrivs;
if (privilege === 'All') {
newPrivs = [];
} else {
newPrivs = privileges.filter((priv) => priv !== privilege);
}
setPrivileges(newPrivs as never[]);
};
// When a resource is selected, add its urn to the list of resources
const onSelectResourceType = (selectedResourceType: string) => {
const filter = resources.filter || {
criteria: [],
};
setResources({
...resources,
filter: setFieldValues(filter, 'RESOURCE_TYPE', [
...resourceTypes,
createCriterionValue(selectedResourceType),
]),
});
};
const onDeselectResourceType = (deselectedResourceType: string) => {
const filter = resources.filter || {
criteria: [],
};
setResources({
...resources,
filter: setFieldValues(
filter,
'RESOURCE_TYPE',
resourceTypes?.filter((criterionValue) => criterionValue.value !== deselectedResourceType),
),
});
};
// When a resource is selected, add its urn to the list of resources
const onSelectResource = (resource) => {
const filter = resources.filter || {
criteria: [],
};
setResources({
...resources,
filter: setFieldValues(filter, 'RESOURCE_URN', [
...resourceEntities,
createCriterionValueWithEntity(
resource,
getEntityFromSearchResults(resourceSearchResults, resource) || null,
),
]),
});
};
// When a resource is deselected, remove its urn from the list of resources
const onDeselectResource = (resource) => {
const filter = resources.filter || {
criteria: [],
};
setResources({
...resources,
filter: setFieldValues(
filter,
'RESOURCE_URN',
resourceEntities?.filter((criterionValue) => criterionValue.value !== resource),
),
});
};
// When a domain is selected, add its urn to the list of domains
const onSelectDomain = (domain) => {
const filter = resources.filter || {
criteria: [],
};
const updatedFilter = setFieldValues(filter, 'DOMAIN', [
...domains,
createCriterionValueWithEntity(domain, getEntityFromSearchResults(domainSearchResults, domain) || null),
]);
setResources({
...resources,
filter: updatedFilter,
});
};
// When a domain is deselected, remove its urn from the list of domains
const onDeselectDomain = (domain) => {
const filter = resources.filter || {
criteria: [],
};
setResources({
...resources,
filter: setFieldValues(
filter,
'DOMAIN',
domains?.filter((criterionValue) => criterionValue.value !== domain),
),
});
};
// Handle resource search, if the resource type has an associated EntityType mapping.
const handleResourceSearch = (text: string) => {
const entityTypes = resourceTypeSelectValue
.map((resourceType) => mapResourceTypeToEntityType(resourceType, resourcePrivileges))
.filter((entityType): entityType is EntityType => !!entityType);
if (text.length > 2) {
searchResources({
variables: {
input: {
types: entityTypes,
query: text,
start: 0,
count: 10,
},
},
});
}
};
// Handle domain search, if the domain type has an associated EntityType mapping.
const handleDomainSearch = (text: string) => {
if (text.length > 2) {
searchDomains({
variables: {
input: {
type: EntityType.Domain,
query: text,
start: 0,
count: 10,
},
},
});
}
};
const renderSearchResult = (result) => {
return (
<SearchResultContainer>
{entityRegistry.getDisplayName(result.entity.type, result.entity)}
<Link
target="_blank"
rel="noopener noreferrer"
to={() => `/${entityRegistry.getPathName(result.entity.type)}/${result.entity.urn}`}
>
View
</Link>
</SearchResultContainer>
);
};
const displayStringWithMaxLength = (displayStr, length) => {
return displayStr.length > length
? `${displayStr.substring(0, Math.min(length, displayStr.length))}...`
: displayStr;
};
return (
<PrivilegesForm layout="vertical">
{showResourceFilterInput && (
<Form.Item label={<Typography.Text strong>Resource Type</Typography.Text>} labelAlign="right">
<Typography.Paragraph>
Select the types of resources this policy should apply to. If <b>none</b> is selected, policy is
applied to <b>all</b> types of resources.
</Typography.Paragraph>
<Select
value={resourceTypeSelectValue}
mode="multiple"
placeholder="Apply to ALL resource types by default. Select types to apply to specific types of entities."
onSelect={onSelectResourceType}
onDeselect={onDeselectResourceType}
tagRender={(tagProps) => (
<Tag closable={tagProps.closable} onClose={tagProps.onClose}>
{mapResourceTypeToDisplayName(tagProps.value.toString(), resourcePrivileges)}
</Tag>
)}
>
{resourcePrivileges
.filter((privs) => privs.resourceType !== 'all')
.map((resPrivs) => {
return (
<Select.Option value={resPrivs.resourceType}>
{resPrivs.resourceTypeDisplayName}
</Select.Option>
);
})}
</Select>
</Form.Item>
)}
{showResourceFilterInput && (
<Form.Item label={<Typography.Text strong>Resource</Typography.Text>}>
<Typography.Paragraph>
Search for specific resources the policy should apply to. If <b>none</b> is selected, policy is
applied to <b>all</b> resources of the given type.
</Typography.Paragraph>
<Select
value={resourceSelectValue}
mode="multiple"
filterOption={false}
placeholder="Apply to ALL resources by default. Select specific resources to apply to."
onSelect={onSelectResource}
onDeselect={onDeselectResource}
onSearch={handleResourceSearch}
tagRender={(tagProps) => (
<Tag closable={tagProps.closable} onClose={tagProps.onClose}>
<Tooltip title={tagProps.value.toString()}>
{displayStringWithMaxLength(
resourceUrnToDisplayName[tagProps.value.toString()] ||
tagProps.value.toString(),
75,
)}
</Tooltip>
</Tag>
)}
>
{resourceSearchResults?.map((result) => (
<Select.Option value={result.entity.urn}>{renderSearchResult(result)}</Select.Option>
))}
</Select>
</Form.Item>
)}
{showResourceFilterInput && (
<Form.Item label={<Typography.Text strong>Domain</Typography.Text>}>
<Typography.Paragraph>
Search for domains the policy should apply to. If <b>none</b> is selected, policy is applied to{' '}
<b>all</b> resources in all domains.
</Typography.Paragraph>
<Select
value={domainSelectValue}
mode="multiple"
filterOption={false}
placeholder="Apply to ALL domains by default. Select domains to apply to specific domains."
onSelect={onSelectDomain}
onDeselect={onDeselectDomain}
onSearch={handleDomainSearch}
tagRender={(tagProps) => (
<Tag closable={tagProps.closable} onClose={tagProps.onClose}>
{displayStringWithMaxLength(
domainUrnToDisplayName[tagProps.value.toString()] || tagProps.value.toString(),
75,
)}
</Tag>
)}
>
{domainSearchResults?.map((result) => (
<Select.Option value={result.entity.urn}>{renderSearchResult(result)}</Select.Option>
))}
</Select>
</Form.Item>
)}
<Form.Item label={<Typography.Text strong>Privileges</Typography.Text>}>
<Typography.Paragraph>Select a set of privileges to permit.</Typography.Paragraph>
<Select
value={privilegesSelectValue}
mode="multiple"
onSelect={(value: string) => onSelectPrivilege(value)}
onDeselect={(value: any) => onDeselectPrivilege(value)}
tagRender={(tagProps) => (
<Tag closable={tagProps.closable} onClose={tagProps.onClose}>
{tagProps.label}
</Tag>
)}
>
{privilegeOptions.map((priv) => (
<Select.Option value={priv.type}>{priv.displayName}</Select.Option>
))}
<Select.Option value="All">All Privileges</Select.Option>
</Select>
</Form.Item>
</PrivilegesForm>
);
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.