text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import {
Component,
OnInit,
Input,
OnDestroy, Output, EventEmitter, ViewChild,
} from "@angular/core";
import { debounceTime, distinctUntilChanged, filter, finalize, switchMap } from "rxjs/operators";
import { MessageHandlerService } from "../../../../shared/services/message-handler.service";
import {
ACTION_RESOURCE_I18N_MAP,
ExpirationType,
FrontAccess, INITIAL_ACCESSES, onlyHasPushPermission, PermissionsKinds
} from "../../../left-side-nav/system-robot-accounts/system-robot-util";
import { Robot } from "../../../../../../ng-swagger-gen/models/robot";
import { NgForm } from "@angular/forms";
import { ClrLoadingState } from "@clr/angular";
import { Subject, Subscription } from "rxjs";
import { RobotService } from "../../../../../../ng-swagger-gen/services/robot.service";
import { OperationService } from "../../../../shared/components/operation/operation.service";
import { clone } from "../../../../shared/units/utils";
import { operateChanges, OperateInfo, OperationState } from "../../../../shared/components/operation/operate";
import { Access } from "../../../../../../ng-swagger-gen/models/access";
import { InlineAlertComponent } from "../../../../shared/components/inline-alert/inline-alert.component";
import { errorHandler } from "../../../../shared/units/shared.utils";
const MINI_SECONDS_ONE_DAY: number = 60 * 24 * 60 * 1000;
@Component({
selector: "add-robot",
templateUrl: "./add-robot.component.html",
styleUrls: ["./add-robot.component.scss"]
})
export class AddRobotComponent implements OnInit, OnDestroy {
@Input() projectId: number;
@Input() projectName: string;
i18nMap = ACTION_RESOURCE_I18N_MAP;
isEditMode: boolean = false;
originalRobotForEdit: Robot;
@Output()
addSuccess: EventEmitter<Robot> = new EventEmitter<Robot>();
addRobotOpened: boolean = false;
systemRobot: Robot = {};
expirationType: string = ExpirationType.DAYS;
isNameExisting: boolean = false;
loading: boolean = false;
checkNameOnGoing: boolean = false;
defaultAccesses: FrontAccess[] = [];
defaultAccessesForEdit: FrontAccess[] = [];
@ViewChild(InlineAlertComponent)
inlineAlertComponent: InlineAlertComponent;
@ViewChild('robotForm', { static: true }) robotForm: NgForm;
saveBtnState: ClrLoadingState = ClrLoadingState.DEFAULT;
private _nameSubject: Subject<string> = new Subject<string>();
private _nameSubscription: Subscription;
constructor(
private robotService: RobotService,
private msgHandler: MessageHandlerService,
private operationService: OperationService
) {}
ngOnInit(): void {
this.subscribeName();
}
ngOnDestroy() {
if (this._nameSubscription) {
this._nameSubscription.unsubscribe();
this._nameSubscription = null;
}
}
subscribeName() {
if (!this._nameSubscription) {
this._nameSubscription = this._nameSubject
.pipe(
debounceTime(500),
distinctUntilChanged(),
filter(name => {
if (this.isEditMode && this.originalRobotForEdit && this.originalRobotForEdit.name === name) {
return false;
}
return name.length > 0;
}),
switchMap((name) => {
this.isNameExisting = false;
this.checkNameOnGoing = true;
return this.robotService.ListRobot({
q: encodeURIComponent(
`Level=${PermissionsKinds.PROJECT},ProjectID=${this.projectId},name=${this.projectName}+${name}`)
}).pipe(finalize(() => this.checkNameOnGoing = false));
}))
.subscribe(res => {
if (res && res.length > 0) {
this.isNameExisting = true;
}
});
}
}
isExpirationInvalid(): boolean {
return this.systemRobot.duration < -1;
}
inputExpiration() {
if (+this.systemRobot.duration === -1) {
this.expirationType = ExpirationType.NEVER;
} else {
this.expirationType = ExpirationType.DAYS;
}
}
changeExpirationType() {
if (this.expirationType === ExpirationType.DAYS) {
this.systemRobot.duration = null;
}
if (this.expirationType === ExpirationType.NEVER) {
this.systemRobot.duration = -1;
}
}
inputName() {
this._nameSubject.next(this.systemRobot.name);
}
cancel() {
this.addRobotOpened = false;
}
getPermissions(): number {
let count: number = 0;
this.defaultAccesses.forEach(item => {
if (item.checked) {
count ++;
}
});
return count;
}
chooseAccess(access: FrontAccess) {
access.checked = !access.checked;
}
reset() {
this.open(false);
this.defaultAccesses = clone(INITIAL_ACCESSES);
this.systemRobot = {};
this.robotForm.reset();
this.expirationType = ExpirationType.DAYS;
}
resetForEdit(robot: Robot) {
this.open(true);
this.defaultAccesses = clone(INITIAL_ACCESSES);
this.defaultAccesses.forEach( item => item.checked = false);
this.originalRobotForEdit = clone(robot);
this.systemRobot = robot;
this.expirationType =
robot.duration === -1 ? ExpirationType.NEVER : ExpirationType.DAYS;
this.defaultAccesses.forEach(item => {
this.systemRobot.permissions[0].access.forEach(item2 => {
if (item.resource === item2.resource && item.action === item2.action) {
item.checked = true;
}
});
});
this.defaultAccessesForEdit = clone(this.defaultAccesses);
this.robotForm.reset({
name: this.systemRobot.name,
expiration: this.systemRobot.duration,
description: this.systemRobot.description,
});
}
open(isEditMode: boolean) {
this.isEditMode = isEditMode;
this.addRobotOpened = true;
this.inlineAlertComponent.close();
this.isNameExisting = false;
this._nameSubject.next('');
}
disabled(): boolean {
if (!this.isEditMode) {
return !this.canAdd();
}
return !this.canEdit();
}
canAdd(): boolean {
let flag = false;
this.defaultAccesses.forEach( item => {
if (item.checked) {
flag = true;
}
});
if (!flag) {
return false;
}
return !this.robotForm.invalid;
}
canEdit() {
if (!this.canAdd()) {
return false;
}
// tslint:disable-next-line:triple-equals
if (this.systemRobot.duration != this.originalRobotForEdit.duration) {
return true;
}
// tslint:disable-next-line:triple-equals
if (this.systemRobot.description != this.originalRobotForEdit.description) {
return true;
}
if (this.getAccessNum(this.defaultAccesses) !== this.getAccessNum(this.defaultAccessesForEdit)) {
return true;
}
let flag = true;
this.defaultAccessesForEdit.forEach(item => {
this.defaultAccesses.forEach(item2 => {
if (item.resource === item2.resource && item.action === item2.action && item.checked !== item2.checked) {
flag = false;
}
});
});
return !flag;
}
save() {
const robot: Robot = clone(this.systemRobot);
robot.disable = false;
robot.level = PermissionsKinds.PROJECT;
robot.duration = +this.systemRobot.duration;
const access: Access[] = [];
this.defaultAccesses.forEach(item => {
if (item.checked) {
access.push({
resource: item.resource,
action: item.action
});
}
});
robot.permissions = [{
namespace: this.projectName,
kind: PermissionsKinds.PROJECT,
access: access
}];
// Push permission must work with pull permission
if (onlyHasPushPermission(access)) {
this.inlineAlertComponent.showInlineError('SYSTEM_ROBOT.PUSH_PERMISSION_TOOLTIP');
return;
}
this.saveBtnState = ClrLoadingState.LOADING;
if (this.isEditMode) {
robot.disable = this.systemRobot.disable;
const opeMessage = new OperateInfo();
opeMessage.name = "SYSTEM_ROBOT.UPDATE_ROBOT";
opeMessage.data.id = robot.id;
opeMessage.state = OperationState.progressing;
opeMessage.data.name = robot.name;
this.operationService.publishInfo(opeMessage);
this.robotService.UpdateRobot({
robotId: this.originalRobotForEdit.id,
robot
}).subscribe( res => {
this.saveBtnState = ClrLoadingState.SUCCESS;
this.addSuccess.emit(null);
this.addRobotOpened = false;
operateChanges(opeMessage, OperationState.success);
this.msgHandler.showSuccess("SYSTEM_ROBOT.UPDATE_ROBOT_SUCCESSFULLY");
}, error => {
this.saveBtnState = ClrLoadingState.ERROR;
operateChanges(opeMessage, OperationState.failure, errorHandler(error));
this.inlineAlertComponent.showInlineError(error);
});
} else {
const opeMessage = new OperateInfo();
opeMessage.name = "SYSTEM_ROBOT.ADD_ROBOT";
opeMessage.data.id = robot.id;
opeMessage.state = OperationState.progressing;
opeMessage.data.name = `${this.projectName}+${robot.name}`;
this.operationService.publishInfo(opeMessage);
this.robotService.CreateRobot({
robot: robot
}).subscribe( res => {
this.saveBtnState = ClrLoadingState.SUCCESS;
this.saveBtnState = ClrLoadingState.SUCCESS;
this.addSuccess.emit(res);
this.addRobotOpened = false;
operateChanges(opeMessage, OperationState.success);
}, error => {
this.saveBtnState = ClrLoadingState.ERROR;
this.inlineAlertComponent.showInlineError(error);
operateChanges(opeMessage, OperationState.failure, errorHandler(error));
});
}
}
getAccessNum(access: FrontAccess[]): number {
let count: number = 0;
access.forEach(item => {
if (item.checked) {
count ++;
}
});
return count;
}
calculateExpiresAt(): Date {
if (this.systemRobot && this.systemRobot.creation_time && this.systemRobot.duration > 0) {
return new Date(new Date(this.systemRobot.creation_time).getTime()
+ this.systemRobot.duration * MINI_SECONDS_ONE_DAY);
}
return null;
}
shouldShowWarning(): boolean {
return new Date() >= this.calculateExpiresAt();
}
} | the_stack |
import { BigNumberish, ethers } from 'ethers';
import { MultiProvider } from '..';
import { xapps, core } from '@optics-xyz/ts-interface';
import { BridgeContracts } from './contracts/BridgeContracts';
import { CoreContracts } from './contracts/CoreContracts';
import { ResolvedTokenInfo, TokenIdentifier } from './tokens';
import { canonizeId, evmId } from '../utils';
import {
devDomains,
mainnetDomains,
mainnetCommunityDomains,
OpticsDomain,
stagingDomains,
stagingCommunityDomains,
} from './domains';
import { TransferMessage } from './messages';
import { hexlify } from '@ethersproject/bytes';
type Address = string;
/**
* The OpticsContext managers connections to Optics core and Bridge contracts.
* It inherits from the {@link MultiProvider}, and ensures that its contracts
* always use the latest registered providers and signers.
*
* For convenience, we've pre-constructed contexts for mainnet and testnet
* deployments. These can be imported directly.
*
* @example
* // Set up mainnet and then access contracts as below:
* let router = mainnet.mustGetBridge('celo').bridgeRouter;
*/
export class OpticsContext extends MultiProvider {
private cores: Map<number, CoreContracts>;
private bridges: Map<number, BridgeContracts>;
constructor(
domains: OpticsDomain[],
cores: CoreContracts[],
bridges: BridgeContracts[],
) {
super();
domains.forEach((domain) => this.registerDomain(domain));
this.cores = new Map();
this.bridges = new Map();
cores.forEach((core) => {
this.cores.set(core.domain, core);
});
bridges.forEach((bridge) => {
this.bridges.set(bridge.domain, bridge);
});
}
/**
* Instantiate an OpticsContext from contract info.
*
* @param domains An array of Domains with attached contract info
* @returns A context object
*/
static fromDomains(domains: OpticsDomain[]): OpticsContext {
const cores = domains.map((domain) => CoreContracts.fromObject(domain));
const bridges = domains.map((domain) => BridgeContracts.fromObject(domain));
return new OpticsContext(domains, cores, bridges);
}
/**
* Ensure that the contracts on a given domain are connected to the
* currently-registered signer or provider.
*
* @param domain the domain to reconnect
*/
private reconnect(domain: number) {
const connection = this.getConnection(domain);
if (!connection) {
throw new Error(`Reconnect failed: no connection for ${domain}`);
}
// re-register contracts
const core = this.cores.get(domain);
if (core) {
core.connect(connection);
}
const bridge = this.bridges.get(domain);
if (bridge) {
bridge.connect(connection);
}
}
/**
* Register an ethers Provider for a specified domain.
*
* @param nameOrDomain A domain name or number.
* @param provider An ethers Provider to be used by requests to that domain.
*/
registerProvider(
nameOrDomain: string | number,
provider: ethers.providers.Provider,
): void {
const domain = this.resolveDomain(nameOrDomain);
super.registerProvider(domain, provider);
this.reconnect(domain);
}
/**
* Register an ethers Signer for a specified domain.
*
* @param nameOrDomain A domain name or number.
* @param signer An ethers Signer to be used by requests to that domain.
*/
registerSigner(nameOrDomain: string | number, signer: ethers.Signer): void {
const domain = this.resolveDomain(nameOrDomain);
super.registerSigner(domain, signer);
this.reconnect(domain);
}
/**
* Remove the registered ethers Signer from a domain. This function will
* attempt to preserve any Provider that was previously connected to this
* domain.
*
* @param nameOrDomain A domain name or number.
*/
unregisterSigner(nameOrDomain: string | number): void {
const domain = this.resolveDomain(nameOrDomain);
super.unregisterSigner(domain);
this.reconnect(domain);
}
/**
* Clear all signers from all registered domains.
*/
clearSigners(): void {
super.clearSigners();
this.domainNumbers.forEach((domain) => this.reconnect(domain));
}
/**
* Get the {@link CoreContracts} for a given domain (or undefined)
*
* @param nameOrDomain A domain name or number.
* @returns a {@link CoreContracts} object (or undefined)
*/
getCore(nameOrDomain: string | number): CoreContracts | undefined {
const domain = this.resolveDomain(nameOrDomain);
return this.cores.get(domain);
}
/**
* Get the {@link CoreContracts} for a given domain (or throw an error)
*
* @param nameOrDomain A domain name or number.
* @returns a {@link CoreContracts} object
* @throws if no {@link CoreContracts} object exists on that domain.
*/
mustGetCore(nameOrDomain: string | number): CoreContracts {
const core = this.getCore(nameOrDomain);
if (!core) {
throw new Error(`Missing core for domain: ${nameOrDomain}`);
}
return core;
}
/**
* Get the {@link BridgeContracts} for a given domain (or undefined)
*
* @param nameOrDomain A domain name or number.
* @returns a {@link BridgeContracts} object (or undefined)
*/
getBridge(nameOrDomain: string | number): BridgeContracts | undefined {
const domain = this.resolveDomain(nameOrDomain);
return this.bridges.get(domain);
}
/**
* Get the {@link BridgeContracts} for a given domain (or throw an error)
*
* @param nameOrDomain A domain name or number.
* @returns a {@link BridgeContracts} object
* @throws if no {@link BridgeContracts} object exists on that domain.
*/
mustGetBridge(nameOrDomain: string | number): BridgeContracts {
const bridge = this.getBridge(nameOrDomain);
if (!bridge) {
throw new Error(`Missing bridge for domain: ${nameOrDomain}`);
}
return bridge;
}
/**
* Resolve the replica for the Home domain on the Remote domain (if any).
*
* WARNING: do not hold references to this contract, as it will not be
* reconnected in the event the chain connection changes.
*
* @param home the sending domain
* @param remote the receiving domain
* @returns An interface for the Replica (if any)
*/
getReplicaFor(
home: string | number,
remote: string | number,
): core.Replica | undefined {
return this.getCore(remote)?.replicas.get(this.resolveDomain(home))
?.contract;
}
/**
* Resolve the replica for the Home domain on the Remote domain (or throws).
*
* WARNING: do not hold references to this contract, as it will not be
* reconnected in the event the chain connection changes.
*
* @param home the sending domain
* @param remote the receiving domain
* @returns An interface for the Replica
* @throws If no replica is found.
*/
mustGetReplicaFor(
home: string | number,
remote: string | number,
): core.Replica {
const replica = this.getReplicaFor(home, remote);
if (!replica) {
throw new Error(`Missing replica for home ${home} & remote ${remote}`);
}
return replica;
}
/**
* Resolve the local representation of a token on some domain. E.g. find the
* deployed Celo address of Ethereum's Sushi Token.
*
* WARNING: do not hold references to this contract, as it will not be
* reconnected in the event the chain connection changes.
*
* @param nameOrDomain the target domain, which hosts the representation
* @param token The token to locate on that domain
* @returns An interface for that token (if it has been deployed on that
* domain)
*/
async resolveRepresentation(
nameOrDomain: string | number,
token: TokenIdentifier,
): Promise<xapps.BridgeToken | undefined> {
const domain = this.resolveDomain(nameOrDomain);
const bridge = this.getBridge(domain);
const tokenDomain = this.resolveDomain(token.domain);
const tokenId = canonizeId(token.id);
const address = await bridge?.bridgeRouter[
'getLocalAddress(uint32,bytes32)'
](tokenDomain, tokenId);
if (!address) {
return;
}
let contract = new xapps.BridgeToken__factory().attach(evmId(address));
const connection = this.getConnection(domain);
if (connection) {
contract = contract.connect(connection);
}
return contract;
}
/**
* Resolve the local representation of a token on ALL known domain. E.g.
* find ALL deployed addresses of Ethereum's Sushi Token, on all registered
* domains.
*
* WARNING: do not hold references to these contracts, as they will not be
* reconnected in the event the chain connection changes.
*
* @param token The token to locate on ALL domains
* @returns A {@link ResolvedTokenInfo} object with representation addresses
*/
async resolveRepresentations(
token: TokenIdentifier,
): Promise<ResolvedTokenInfo> {
const tokens: Map<number, xapps.BridgeToken> = new Map();
await Promise.all(
this.domainNumbers.map(async (domain) => {
const tok = await this.resolveRepresentation(domain, token);
if (tok) {
tokens.set(domain, tok);
}
}),
);
return {
domain: this.resolveDomain(token.domain),
id: token.id,
tokens,
};
}
/**
* Resolve the canonical domain and identifier for a representation on some
* domain.
*
* @param nameOrDomain The domain hosting the representation
* @param representation The address of the representation on that domain
* @returns The domain and ID for the canonical token
* @throws If the token is unknown to the bridge router on its domain.
*/
async resolveCanonicalIdentifier(
nameOrDomain: string | number,
representation: Address,
): Promise<TokenIdentifier> {
const domain = this.resolveDomain(nameOrDomain);
const bridge = this.mustGetBridge(nameOrDomain);
const repr = hexlify(canonizeId(representation));
const canonical = await bridge.bridgeRouter.representationToCanonical(
representation,
);
if (canonical[0] !== 0) {
return {
domain: canonical[0],
id: canonical[1],
};
}
// check if it's a local token
const local = await bridge.bridgeRouter['getLocalAddress(uint32,bytes32)'](
domain,
repr,
);
if (local !== ethers.constants.AddressZero) {
return {
domain,
id: hexlify(canonizeId(local)),
};
}
// throw
throw new Error('Token not known to the bridge');
}
/**
* Resolve an interface for the canonical token corresponding to a
* representation on some domain.
*
* @param nameOrDomain The domain hosting the representation
* @param representation The address of the representation on that domain
* @returns An interface for that token
* @throws If the token is unknown to the bridge router on its domain.
*/
async resolveCanonicalToken(
nameOrDomain: string | number,
representation: Address,
): Promise<xapps.BridgeToken> {
const canonicalId = await this.resolveCanonicalIdentifier(
nameOrDomain,
representation,
);
if (!canonicalId) {
throw new Error('Token seems to not exist');
}
const token = await this.resolveRepresentation(
canonicalId.domain,
canonicalId,
);
if (!token) {
throw new Error(
'Cannot resolve canonical on its own domain. how did this happen?',
);
}
return token;
}
/**
* Send tokens from one domain to another. Approves the bridge if necessary.
*
* @param from The domain to send from
* @param to The domain to send to
* @param token The token to send
* @param amount The amount (in smallest unit) to send
* @param recipient The identifier to send to on the `to` domain
* @param overrides Any tx overrides (e.g. gas price)
* @returns a {@link TransferMessage} object representing the in-flight
* transfer
* @throws On missing signers, missing tokens, tx issues, etc.
*/
async send(
from: string | number,
to: string | number,
token: TokenIdentifier,
amount: BigNumberish,
recipient: Address,
overrides: ethers.Overrides = {},
): Promise<TransferMessage> {
const fromBridge = this.mustGetBridge(from);
const bridgeAddress = fromBridge.bridgeRouter.address;
const fromToken = await this.resolveRepresentation(from, token);
if (!fromToken) {
throw new Error(`Token not available on ${from}`);
}
const sender = this.getSigner(from);
if (!sender) {
throw new Error(`No signer for ${from}`);
}
const senderAddress = await sender.getAddress();
const approved = await fromToken.allowance(senderAddress, bridgeAddress);
// Approve if necessary
if (approved.lt(amount)) {
const tx = await fromToken.approve(bridgeAddress, amount, overrides);
await tx.wait();
}
const tx = await fromBridge.bridgeRouter.send(
fromToken.address,
amount,
this.resolveDomain(to),
canonizeId(recipient),
overrides,
);
const receipt = await tx.wait();
const message = TransferMessage.singleFromReceipt(this, from, receipt);
if (!message) {
throw new Error();
}
return message as TransferMessage;
}
/**
* Send a chain's native asset from one chain to another using the
* `EthHelper` contract.
*
* @param from The domain to send from
* @param to The domain to send to
* @param amount The amount (in smallest unit) to send
* @param recipient The identifier to send to on the `to` domain
* @param overrides Any tx overrides (e.g. gas price)
* @returns a {@link TransferMessage} object representing the in-flight
* transfer
* @throws On missing signers, tx issues, etc.
*/
async sendNative(
from: string | number,
to: string | number,
amount: BigNumberish,
recipient: Address,
overrides: ethers.PayableOverrides = {},
): Promise<TransferMessage> {
const ethHelper = this.mustGetBridge(from).ethHelper;
if (!ethHelper) {
throw new Error(`No ethHelper for ${from}`);
}
const toDomain = this.resolveDomain(to);
overrides.value = amount;
const tx = await ethHelper.sendToEVMLike(toDomain, recipient, overrides);
const receipt = await tx.wait();
const message = TransferMessage.singleFromReceipt(this, from, receipt);
if (!message) {
throw new Error();
}
return message as TransferMessage;
}
}
export const mainnet = OpticsContext.fromDomains(mainnetDomains);
export const mainnetCommunity = OpticsContext.fromDomains(mainnetCommunityDomains);
export const dev = OpticsContext.fromDomains(devDomains);
export const staging = OpticsContext.fromDomains(stagingDomains);
export const stagingCommunity = OpticsContext.fromDomains(stagingCommunityDomains); | the_stack |
import {
Attribute,
Identifier,
Message,
Pattern,
Placeable,
Resource,
TextElement,
VariableReference,
} from '@fluent/syntax';
import { serializePattern } from '../src';
import { Resources } from '../src/resources';
import { serializeEntry } from '../src/utils/serializeEntry';
let resources: Resources;
beforeEach(() => {
resources = new Resources({
resources: {
en: new Resource([
new Message(new Identifier('test'), new Pattern([new TextElement('this is my test')])),
new Message(new Identifier('hello'), new Pattern([new TextElement('hello there')])),
new Message(
new Identifier('complex'),
new Pattern([
new TextElement('Hello '),
new Placeable(new VariableReference(new Identifier('name'))),
])
),
new Message(new Identifier('extra'), new Pattern([new TextElement('a key without translations ')])),
]),
da: new Resource([
new Message(new Identifier('test'), new Pattern([new TextElement('dette er min test')])),
new Message(new Identifier('hello'), new Pattern([new TextElement('hej med dig')])),
new Message(
new Identifier('complex'),
new Pattern([new TextElement('Hej '), new Placeable(new VariableReference(new Identifier('name')))])
),
]),
de: new Resource([
new Message(new Identifier('test'), new Pattern([new TextElement('dis ist ein test')])),
new Message(new Identifier('hello'), new Pattern([new TextElement('hallo mit dich')])),
new Message(
new Identifier('complex'),
new Pattern([
new TextElement('Hallo '),
new Placeable(new VariableReference(new Identifier('name'))),
])
),
]),
},
});
});
describe('messageExist()', () => {
it('should be truthy when a message exists', () => {
expect(resources.messageExist({ id: 'test', languageCode: 'en' })).toBeTruthy();
});
it('should be falsy when a message not exists', () => {
expect(resources.messageExist({ id: 'extra', languageCode: 'de' })).toBeFalsy();
});
});
describe('getMessage()', () => {
it('simple: should not be undefined and match the expected result', () => {
const result = resources.getMessage({ id: 'test', languageCode: 'en' });
if (result === undefined) {
fail();
}
expect(serializeEntry(result)).toMatch('this is my test');
});
it('complex(er): should not be undefined and match the expected result', () => {
const result = resources.getMessage({ id: 'complex', languageCode: 'en' });
if (result === undefined) {
fail();
}
expect(serializeEntry(result)).toMatch('complex = Hello { $name }');
});
it('should return undefined if a message does not exist', () => {
const result = resources.getMessage({ id: 'undefined-key', languageCode: 'en' });
expect(result).toBeUndefined();
});
});
describe('getMessageForAllResources()', () => {
it('should return all messages', () => {
const messages = resources.getMessageForAllResources({ id: 'test' });
const result: Record<string, string> = {};
for (const languageCode in messages) {
const message = messages[languageCode];
if (message) {
result[languageCode] = serializeEntry(message);
}
}
const match = {
en: 'test = this is my test',
da: 'test = dette er min test',
de: 'test = dis ist ein test',
};
expect(result).toEqual(match);
});
it('should return an empty object if no messages exist', () => {
const result = resources.getMessageForAllResources({ id: 'undefined-key' });
expect(result).toEqual({});
});
});
describe('deleteMessage()', () => {
it('retrieving a message should result in undefined after deletion', () => {
const deletion = resources.deleteMessage({ id: 'test', languageCode: 'en' });
if (deletion.isErr) {
fail();
}
const result = resources.getMessage({ id: 'test', languageCode: 'en' });
expect(result).toBeUndefined();
});
it('should fail when key is not found', () => {
const result = resources.deleteMessage({ id: 'asdf', languageCode: 'en' });
expect(result.isErr).toBeTruthy();
});
});
describe('deleteMessageForAllResources()', () => {
it('should delete the message for all resources', () => {
const result = resources.deleteMessageForAllResources({ id: 'test' });
if (result.isErr) {
fail();
}
for (const languageCode of resources.containedLanguageCodes()) {
expect(resources.getMessage({ id: 'test', languageCode })).toBeUndefined();
}
});
// hmmm bad. Since resources is not an immutable class and all actions are mutable
// sub deletions might succeed and are not reversed.
it('should return Result.ok if the message does not exist for one or more languages', () => {
const result = resources.deleteMessageForAllResources({ id: 'dasdsa' });
expect(result.isOk).toBeTruthy();
});
});
describe('getMessageIdsForAllResources()', () => {
it('should get all ids', () => {
const result = resources.getMessageIdsForAllResources();
expect(result).toEqual(new Set(['test', 'hello', 'complex', 'extra']));
});
});
describe('updateMessage()', () => {
it('should update a message', () => {
const mockMessage = new Message(new Identifier('test'), new Pattern([new TextElement('why not this instead')]));
const update = resources.updateMessage({ id: 'test', languageCode: 'en', with: mockMessage });
if (update.isErr) {
fail();
}
const result = resources.getMessage({ id: 'test', languageCode: 'en' });
if (result === undefined) {
fail();
}
expect(serializeEntry(result)).toMatch('test = why not this instead');
});
it('should fail when the language code does not exist', () => {
const mockMessage = new Message(new Identifier('test'), new Pattern([new TextElement('why not this instead')]));
const result = resources.updateMessage({ id: 'test', languageCode: 'aa', with: mockMessage });
expect(result.isErr).toBeTruthy();
});
it('should fail when the message id is not found', () => {
const mockMessage = new Message(
new Identifier('unknown-id'),
new Pattern([new TextElement('why not this instead')])
);
const result = resources.updateMessage({ id: 'unknown-id', languageCode: 'en', with: mockMessage });
expect(result.isErr).toBeTruthy();
});
it('should fail when the given id does not equal the with.id', () => {
const mockMessage = new Message(new Identifier('test'), new Pattern([new TextElement('why not this instead')]));
const result = resources.updateMessage({ id: 'differnet-id', languageCode: 'en', with: mockMessage });
expect(result.isErr).toBeTruthy();
});
});
describe('createMessage()', () => {
it('should be possible to add a message', () => {
const add = resources.createMessage({ id: 'extra', pattern: 'en nøgle uden oversættelse', languageCode: 'da' });
if (add.isErr) {
fail(add.error);
}
const message = resources.getMessage({ id: 'extra', languageCode: 'da' });
if (message === undefined) {
fail();
}
expect(serializeEntry(message)).toMatch('en nøgle uden oversættelse');
});
it('should not be possible to add an empty message', () => {
const add = resources.createMessage({ id: 'extra', pattern: '', languageCode: 'da' });
expect(add.isErr).toBeTruthy();
});
it('should be return Result.ok when adding a message with an undefined pattern', () => {
const create = resources.createMessage({
id: 'extra',
pattern: undefined,
languageCode: 'da',
attributes: [new Attribute(new Identifier('hi'), new Pattern([]))],
});
expect(create.isOk).toBeTruthy();
const message = resources.getMessage({ id: 'extra', languageCode: 'da' });
// eslint-disable-next-line unicorn/no-null
expect(message?.value).toBe(null);
});
it('should be return Result.err when adding a message with an undefined pattern without attributes', () => {
const create = resources.createMessage({
id: 'extra',
pattern: undefined,
languageCode: 'da',
attributes: [],
});
expect(create.isErr).toBeTruthy();
});
it('should return an error when a message alreaedy exists', () => {
const result = resources.createMessage({ id: 'extra', pattern: 'this should fail', languageCode: 'en' });
expect(result.isErr).toBeTruthy();
});
it('should return an error when language code does not exist', () => {
const result = resources.createMessage({ id: 'extra', pattern: 'this should fail', languageCode: 'aa' });
expect(result.isErr).toBeTruthy();
});
it('should return an error when the message id is invalid', () => {
const result = resources.createMessage({
id: 'extra.something',
pattern: 'this should fail',
languageCode: 'aa',
});
expect(result.isErr).toBeTruthy();
});
});
describe('attributeExists()', () => {
it('should be truthy when an attribute exists', () => {
const create = resources.createAttribute({
messageId: 'test',
id: 'login',
pattern: 'Welcome to this test, please login.',
languageCode: 'en',
});
if (create.isErr) {
fail(create.error);
}
expect(resources.attributeExists({ messageId: 'test', id: 'login', languageCode: 'en' })).toBeTruthy();
});
it('should be falsy when a message not exists', () => {
const create = resources.createAttribute({
messageId: 'test',
id: 'login',
pattern: 'Welcome to this test, please login.',
languageCode: 'en',
});
if (create.isErr) {
fail(create.error);
}
expect(resources.attributeExists({ messageId: 'test', id: 'sfafsafwee', languageCode: 'en' })).toBeFalsy();
});
});
describe('createAttribute()', () => {
it('should create an attribute', () => {
const create = resources.createAttribute({
messageId: 'test',
id: 'login',
pattern: 'Welcome to this test, please login.',
languageCode: 'en',
});
if (create.isErr) {
fail(create.error);
}
const message = resources.getMessage({ id: 'test', languageCode: 'en' });
expect(message?.attributes[0].id.name).toEqual('login');
expect(serializePattern(message?.attributes[0].value ?? new Pattern([]))).toEqual(
'Welcome to this test, please login.'
);
});
it('should return Result.err if the attribute exists already', () => {
const create = resources.createAttribute({
messageId: 'test',
id: 'login',
pattern: 'Welcome to this test, please login.',
languageCode: 'en',
});
expect(create.isOk).toBeTruthy();
const create2 = resources.createAttribute({
messageId: 'test',
id: 'login',
pattern: 'Welcome to this test, please login.',
languageCode: 'en',
});
expect(create2.isOk).toBeFalsy();
});
it('should create the message if the if the message id does not exist', () => {
const create = resources.createAttribute({
messageId: 'balbla-nonexistent',
id: 'login',
pattern: 'Welcome to this test, please login.',
languageCode: 'en',
});
if (create.isErr) {
console.error(create.error);
fail();
}
const message = resources.getMessage({ id: 'balbla-nonexistent', languageCode: 'en' });
if (message === undefined) {
fail();
}
expect(message.attributes.length > 0).toBeTruthy();
// eslint-disable-next-line unicorn/no-null
expect(message.value).toBe(null);
});
it('should return Result.err if the pattern is invalid', () => {
const create = resources.createAttribute({
messageId: 'test',
id: 'login',
pattern: 'Welcome to this {{{}$ test, please login.',
languageCode: 'en',
});
expect(create.isOk).toBeFalsy();
});
});
describe('updateAttribute()', () => {
it('should update an attribute', () => {
const create = resources.createAttribute({
messageId: 'test',
id: 'login',
pattern: 'Welcome to this test, please login.',
languageCode: 'en',
});
if (create.isErr) {
fail(create.error);
}
const update = resources.updateAttribute({
messageId: 'test',
id: 'login',
languageCode: 'en',
with: new Attribute(
new Identifier('login'),
new Pattern([new TextElement('Welcome to this test. Please logout.')])
),
});
if (update.isErr) {
fail(update.error);
}
const message = resources.getMessage({ id: 'test', languageCode: 'en' });
expect(message?.attributes[0].id.name).toEqual('login');
expect(serializePattern(message?.attributes[0].value ?? new Pattern([]))).toEqual(
'Welcome to this test. Please logout.'
);
});
it('should return Result.err if the messageId does not exist', () => {
const update = resources.updateAttribute({
messageId: 'afpihsihg',
id: 'das',
with: new Attribute(new Identifier('hi'), new Pattern([])),
languageCode: 'en',
});
expect(update.isErr).toBeTruthy();
});
it('should return Result.err if the attribute does not exist and options.upsert is undefined', () => {
const update = resources.updateAttribute({
messageId: 'test',
id: 'login',
with: new Attribute(new Identifier('hi'), new Pattern([])),
languageCode: 'en',
});
expect(update.isErr).toBeTruthy();
});
});
describe('getAttribute()', () => {
it('should update an attribute', () => {
const create = resources.createAttribute({
messageId: 'test',
id: 'login',
pattern: 'Welcome to this test, please login.',
languageCode: 'en',
});
if (create.isErr) {
fail(create.error);
}
const attribute = resources.getAttribute({ messageId: 'test', id: 'login', languageCode: 'en' });
expect(serializePattern(attribute?.value ?? new Pattern([]))).toEqual('Welcome to this test, please login.');
});
});
describe('getAttributeForAllResources()', () => {
// hmmm bad. Since resources is not an immutable class and all actions are mutable
// sub deletions might succeed and are not reversed.
it('should retrieve the attribute for all resources', () => {
for (const languageCode of resources.containedLanguageCodes()) {
const create = resources.createAttribute({
messageId: 'test',
id: 'login',
pattern: 'Welcome to this test, please login.',
languageCode: languageCode,
});
if (create.isErr) {
fail(create.error);
}
}
const attributes = resources.getAttributeForAllResources({ messageId: 'test', id: 'login' });
expect(Object.keys(attributes).length).toBe(resources.containedLanguageCodes().length);
});
});
describe('deleteAttribute()', () => {
it('should delete an attribute', () => {
const create = resources.createAttribute({
messageId: 'test',
id: 'login',
pattern: 'Welcome to this test, please login.',
languageCode: 'en',
});
if (create.isErr) {
fail(create.error);
}
const attribute = resources.getAttribute({ messageId: 'test', id: 'login', languageCode: 'en' });
expect(serializePattern(attribute?.value ?? new Pattern([]))).toEqual('Welcome to this test, please login.');
const deletion = resources.deleteAttribute({ messageId: 'test', id: 'login', languageCode: 'en' });
expect(deletion.isOk).toBeTruthy();
const attributeAfterDeletion = resources.getAttribute({ messageId: 'test', id: 'login', languageCode: 'en' });
expect(attributeAfterDeletion).toBeUndefined();
});
it('should return Result.err if the message does not exist', () => {
const deletion = resources.deleteAttribute({ messageId: 'tadsdasdasdadsest', id: 'login', languageCode: 'en' });
expect(deletion.isErr).toBeTruthy();
});
it('should return Result.err if the message exists but the attribute does not', () => {
const deletion = resources.deleteAttribute({ messageId: 'test', id: 'logigassagagsagsa', languageCode: 'en' });
expect(deletion.isErr).toBeTruthy();
});
});
describe('deleteAttributeForAllResources()', () => {
it('should return Result.ok when deleting existing attributes', () => {
for (const languageCode of resources.containedLanguageCodes()) {
const create = resources.createAttribute({
messageId: 'test',
id: 'login',
pattern: 'Welcome to this test, please login.',
languageCode: languageCode,
});
if (create.isErr) {
fail(create.error);
}
}
const deletion = resources.deleteAttributeForAllResources({ messageId: 'test', id: 'login' });
expect(deletion.isOk).toBeTruthy();
});
// hmmm bad. Since resources is not an immutable class and all actions are mutable
// sub deletions might succeed and are not reversed.
it('should return Result.err when deleting an attribute that does not exist for one language', () => {
for (const languageCode of resources.containedLanguageCodes().slice(1)) {
const create = resources.createAttribute({
messageId: 'test',
id: 'login',
pattern: 'Welcome to this test, please login.',
languageCode: languageCode,
});
if (create.isErr) {
fail(create.error);
}
}
const deletion = resources.deleteAttributeForAllResources({ messageId: 'test', id: 'login' });
expect(deletion.isErr).toBeTruthy();
});
}); | the_stack |
/// <reference path="./definitions/nconf.d.ts"/>
/// <reference path="./definitions/Q.d.ts" />
/// <reference path="./definitions/vso-node-api.d.ts" />
import Q = require('q');
import agentifm = require('vso-node-api/interfaces/TaskAgentInterfaces');
import baseifm = require('vso-node-api/interfaces/common/VsoBaseInterfaces');
import cm = require('./common');
import env = require('./environment');
import inputs = require('./inputs');
import agentm = require('vso-node-api/TaskAgentApi');
import webapi = require('vso-node-api/WebApi');
import basicm = require('vso-node-api/handlers/basiccreds');
import utilm = require('./utilities');
var os = require('os');
var nconf = require("nconf");
var async = require("async");
var path = require("path");
var fs = require('fs');
var check = require('validator');
var shell = require('shelljs');
var configPath = path.join(__dirname, '..', '.agent');
var envPath = path.join(__dirname, '..', 'env.agent');
var pkgJsonPath = path.join(__dirname, '..', 'package.json');
export function exists(): boolean {
return fs.existsSync(configPath);
}
//
// creds are not persisted in the file.
// They are tacked on after reading from CL or prompting
//
export function read(): cm.ISettings {
nconf.argv()
.env()
.file({ file: configPath });
var settings: cm.ISettings = {
poolName : nconf.get("poolName"),
serverUrl : nconf.get("serverUrl"),
agentName : nconf.get("agentName"),
workFolder: nconf.get("workFolder"),
logSettings: {
linesPerFile: nconf.get("log.linesPerFile"),
maxFiles: nconf.get("log.maxFiles")
},
basic: nconf.get("basic")
}
return settings;
}
var throwIf = function(condition, message) {
if (condition) {
throw new Error(message);
}
}
export class Configurator {
constructor() {}
//
// ensure configured and return ISettings. That's it
// returns promise
//
public ensureConfigured (creds: baseifm.IBasicCredentials): Q.Promise<cm.IConfiguration> {
var readSettings = exports.read();
if (!readSettings.serverUrl) {
return this.create(creds);
} else {
// update agent to the server
return this.update(creds, readSettings);
}
}
public update(creds: baseifm.IBasicCredentials, settings: cm.ISettings): Q.Promise<cm.IConfiguration> {
return this.writeAgentToPool(creds, settings, true)
.then((config: cm.IConfiguration) => {
return config;
});
}
//
// Gether settings, register with the server and save the settings
//
public create(creds: baseifm.IBasicCredentials): Q.Promise<cm.IConfiguration> {
var settings:cm.ISettings;
var configuration: cm.IConfiguration;
var newAgent: agentifm.TaskAgent;
var agentPoolId = 0;
var cfgInputs = [
{ name: 'serverUrl', description: 'server url', arg: 's', type: 'string', req: true },
{ name: 'agentName', description: 'agent name', arg: 'a', def: os.hostname(), type: 'string', req: true },
{ name: 'poolName', description: 'agent pool name', arg: 'l', def: 'default', type: 'string', req: true },
{ name: 'basic', description: 'force basic', arg: 'b', def: false, type: 'boolean', req: false }
//TODO: consider supporting work folder outside of root - long path not an issue right now for OSX/Linux
//{ name: 'workFolder', description: 'agent work folder', arg: 'f', def: './work', type: 'string', req: true }
];
return inputs.Qget(cfgInputs)
.then((result) => {
settings = <cm.ISettings>{};
settings.poolName = result['poolName'];
settings.serverUrl = result['serverUrl'];
settings.agentName = result['agentName'];
settings.basic = result['basic'];
settings.workFolder = './_work';
settings.logSettings = {
maxFiles: cm.DEFAULT_LOG_MAXFILES,
linesPerFile: cm.DEFAULT_LOG_LINESPERFILE
};
this.validate(settings);
return this.writeAgentToPool(creds, settings, false);
})
.then((config: cm.IConfiguration) => {
configuration = config;
console.log('Creating work folder ' + settings.workFolder + ' ...');
return utilm.ensurePathExists(settings.workFolder);
})
.then(() => {
console.log('Creating env file ' + envPath + '...');
return env.ensureEnvFile(envPath);
})
.then(() => {
console.log('Saving configuration ...');
return utilm.objectToFile(configPath, settings);
})
.then(() => {
return configuration;
})
}
public readConfiguration(creds: baseifm.IBasicCredentials, settings: cm.ISettings): Q.Promise<cm.IConfiguration> {
var agentApi: agentm.IQTaskAgentApi = new webapi.WebApi(settings.serverUrl, cm.basicHandlerFromCreds(creds)).getQTaskAgentApi();
var agentPoolId = 0;
var agent;
return agentApi.connect()
.then((connected: any) => {
console.log('successful connect as ' + connected.authenticatedUser.customDisplayName);
return agentApi.getAgentPools(settings.poolName, null);
})
.then((agentPools: agentifm.TaskAgentPool[]) => {
if (agentPools.length == 0) {
cm.throwAgentError(cm.AgentError.PoolNotExist, settings.poolName + ' pool does not exist.');
return;
}
// we queried by name so should only get 1
agentPoolId = agentPools[0].id;
console.log('Retrieved agent pool: ' + agentPools[0].name + ' (' + agentPoolId + ')');
return agentApi.getAgents(agentPoolId, settings.agentName);
})
.then((agents: agentifm.TaskAgent[]) => {
if (agents.length == 0) {
cm.throwAgentError(cm.AgentError.AgentNotExist, settings.agentName + ' does not exist in pool ' + settings.poolName);
return;
}
// should be exactly one agent by name in a given pool by id
var agent = agents[0];
var config: cm.IConfiguration = <cm.IConfiguration>{};
config.poolId = agentPoolId;
config.settings = settings;
config.agent = agent;
return config;
})
}
//-------------------------------------------------------------
// Private
//-------------------------------------------------------------
private validate(settings: cm.ISettings) {
throwIf(!check.isURL(settings.serverUrl, { protocols:['http', 'https'], require_tld:false, require_protocol:true }), settings.serverUrl + ' is not a valid URL');
}
private getComputerName(): Q.Promise<string> {
// I don't want the DNS resolved name - I want the computer name
// OSX also has: 'scutil --get ComputerName'
// but that returns machinename.local
return utilm.exec('hostname');
}
private constructAgent(settings: cm.ISettings): Q.Promise<agentifm.TaskAgent> {
var caps: cm.IStringDictionary = env.getCapabilities();
caps['Agent.Name'] = settings.agentName;
caps['Agent.OS'] = process.platform;
var version;
var computerName;
return this.getComputerName()
.then((ret: any) => {
computerName = ret.output;
return utilm.objectFromFile(pkgJsonPath);
})
.then((pkg: any) => {
caps['Agent.NpmVersion'] = pkg['version'];
caps['Agent.ComputerName'] = computerName;
var newAgent: agentifm.TaskAgent = <agentifm.TaskAgent>{
maxParallelism: 1,
name: settings.agentName,
version: pkg['vsoAgentInfo']['serviceMilestone'],
systemCapabilities: caps
}
return newAgent;
})
}
private writeAgentToPool(creds: baseifm.IBasicCredentials, settings: cm.ISettings, update: boolean): Q.Promise<cm.IConfiguration> {
var agentApi: agentm.IQTaskAgentApi = new webapi.WebApi(settings.serverUrl, cm.basicHandlerFromCreds(creds)).getQTaskAgentApi();
var agentPoolId = 0;
var agentId = 0;
return agentApi.connect()
.then((connected: any) => {
console.log('successful connect as ' + connected.authenticatedUser.customDisplayName);
return agentApi.getAgentPools(settings.poolName, null);
})
.then((agentPools: agentifm.TaskAgentPool[]) => {
if (agentPools.length == 0) {
throw new Error(settings.poolName + ' pool does not exist.');
}
// we queried by name so should only get 1
agentPoolId = agentPools[0].id;
console.log('Retrieved agent pool: ' + agentPools[0].name + ' (' + agentPoolId + ')');
return agentApi.getAgents(agentPoolId, settings.agentName);
})
.then((agents: agentifm.TaskAgent[]) => {
if (update && agents.length == 1) {
agentId = agents[0].id;
return this.constructAgent(settings);
}
else if (update && agents.length == 0) {
throw new Error('Agent was deleted. Reconfigure');
}
else if (agents.length == 0) {
return this.constructAgent(settings);
}
else {
throw new Error('An agent already exists by the name ' + settings.agentName);
}
})
.then((agent: agentifm.TaskAgent) => {
if (update) {
agent.id = agentId;
return agentApi.updateAgent(agent, agentPoolId, agentId);
}
else {
return agentApi.addAgent(agent, agentPoolId);
}
})
.then((agent: agentifm.TaskAgent) => {
var config: cm.IConfiguration = <cm.IConfiguration>{};
config.poolId = agentPoolId;
config.settings = settings;
config.agent = agent;
return config;
})
}
} | the_stack |
import { expect } from 'chai';
import { IsoBuffer } from '@fluidframework/common-utils';
import { EditHandle, EditLog, separateEditAndId } from '../EditLog';
import { Change } from '../default-edits';
import { EditId } from '../Identifiers';
import { assertNotUndefined } from '../Common';
import { newEdit, Edit, EditWithoutId } from '../generic';
/**
* Creates an edit log with the specified number of chunks, stored as handles instead of edits.
* @param numberOfChunks - The number of chunks to add to the edit log.
* @param editsPerChunk - The number of edits per chunk that gets added to the edit log.
* @param editsPerChunkOnEditLog - The number of edits per chunk that gets set for future edits to the edit log.
* @returns The edit log created with handles.
*/
function createEditLogWithHandles(
numberOfChunks = 2,
editsPerChunk = 5,
editsPerChunkOnEditLog = 100
): EditLog<Change> {
const editIds: EditId[] = [];
const editChunks: EditWithoutId<Change>[][] = [];
let inProgessChunk: EditWithoutId<Change>[] = [];
for (let i = 0; i < numberOfChunks * editsPerChunk; i++) {
const { id, editWithoutId } = separateEditAndId(newEdit([]));
editIds.push(id);
inProgessChunk.push(editWithoutId);
if (inProgessChunk.length === editsPerChunk) {
editChunks.push(inProgessChunk.slice());
inProgessChunk = [];
}
}
const handles: EditHandle[] = editChunks.map((chunk) => {
return {
get: async () => {
return IsoBuffer.from(JSON.stringify({ edits: chunk }));
},
};
});
let startRevision = 0;
const handlesWithKeys = handles.map((chunk) => {
const handle = {
startRevision,
chunk,
};
startRevision = startRevision + 5;
return handle;
});
const editLog = new EditLog<Change>({ editChunks: handlesWithKeys, editIds }, undefined, editsPerChunkOnEditLog);
return editLog;
}
describe('EditLog', () => {
const edit0 = newEdit([]);
const edit1 = newEdit([]);
const { id: id0, editWithoutId: editWithoutId0 } = separateEditAndId(edit0);
const { id: id1, editWithoutId: editWithoutId1 } = separateEditAndId(edit1);
it('can be constructed from sequenced edits', () => {
const editChunks = [{ startRevision: 0, chunk: [editWithoutId0, editWithoutId1] }];
const editIds = [id0, id1];
const log = new EditLog({ editChunks, editIds });
expect(log.numberOfLocalEdits).to.equal(0, 'Newly initialized log should not have local edits.');
expect(log.numberOfSequencedEdits).to.equal(
editChunks[0].chunk.length,
'Log should have as many sequenced edits as it was initialized with.'
);
expect(log.length).to.equal(
editChunks[0].chunk.length,
"Log's total length should match its sequenced edits on construction"
);
expect(log.getIdAtIndex(0)).to.equal(id0, 'Log should have edits in order of construction.');
expect(log.getIdAtIndex(1)).to.equal(id1, 'Log should have edits in order of construction.');
});
it('can get the index from an edit id of sequenced edits', () => {
const editChunks = [{ startRevision: 0, chunk: [editWithoutId0, editWithoutId1] }];
const editIds = [id0, id1];
const log = new EditLog({ editChunks, editIds });
expect(log.getIndexOfId(id0)).to.equal(0);
expect(log.getIndexOfId(id1)).to.equal(1);
});
it('can get the index from an edit id of a local edit', () => {
const editChunks = [{ startRevision: 0, chunk: [editWithoutId0] }];
const editIds = [id0];
const log = new EditLog({ editChunks, editIds });
log.addLocalEdit(edit1);
expect(log.getIndexOfId(id0)).to.equal(0);
expect(log.getIndexOfId(id1)).to.equal(1);
});
describe('tryGetIndexOfId', () => {
it('can get the index from an existing edit', () => {
const editChunks = [{ startRevision: 0, chunk: [editWithoutId0] }];
const editIds = [id0];
const log = new EditLog({ editChunks, editIds });
expect(log.tryGetIndexOfId(id0)).to.equal(0);
});
it('returns undefined when queried with a nonexistent edit', () => {
const editChunks = [{ startRevision: 0, chunk: [editWithoutId0] }];
const editIds = ['f9379af1-6f1a-4f71-8f8c-859359621404' as EditId];
const log = new EditLog({ editChunks, editIds });
expect(log.tryGetIndexOfId('aa203fc3-bc28-437d-b01c-f9398dc859ef' as EditId)).to.equal(undefined);
});
});
it('can get an edit from an index', async () => {
const editChunks = [{ startRevision: 0, chunk: [editWithoutId0, editWithoutId1] }];
const editIds = [id0, id1];
const log = new EditLog({ editChunks, editIds });
expect((await log.getEditAtIndex(0)).id).to.equal(id0);
expect((await log.getEditAtIndex(1)).id).to.equal(id1);
});
it('can get an edit from an edit id', async () => {
const editChunks = [{ startRevision: 0, chunk: [editWithoutId0, editWithoutId1] }];
const editIds = [id0, id1];
const log = new EditLog({ editChunks, editIds });
const editFromId0 = await log.tryGetEdit(id0);
const editFromId1 = await log.tryGetEdit(id1);
expect(editFromId0).to.not.be.undefined;
expect(editFromId1).to.not.be.undefined;
expect(assertNotUndefined(editFromId0).id).to.equal(edit0.id);
expect(assertNotUndefined(editFromId1).id).to.equal(edit1.id);
});
it('can be iterated', () => {
const log = new EditLog();
log.addLocalEdit(edit1);
log.addSequencedEdit(edit0, { sequenceNumber: 1, referenceSequenceNumber: 0 });
// Sequenced edits should be iterated before local edits
const expectedEditIdStack = [id1, id0];
log.editIds.forEach((editId) => {
expect(editId).to.equal(expectedEditIdStack.pop());
});
expect(expectedEditIdStack.length).to.equal(0);
});
it('can add sequenced edits', () => {
const log = new EditLog();
log.addSequencedEdit(edit0, { sequenceNumber: 1, referenceSequenceNumber: 0 });
expect(log.numberOfSequencedEdits).to.equal(1);
expect(log.numberOfLocalEdits).to.equal(0, 'Log should have only sequenced edits.');
log.addSequencedEdit(edit1, { sequenceNumber: 2, referenceSequenceNumber: 1 });
expect(log.numberOfSequencedEdits).to.equal(2);
expect(log.numberOfLocalEdits).to.equal(0, 'Log should have only sequenced edits.');
expect(log.length).to.equal(2);
});
it('can add local edits', () => {
const log = new EditLog();
log.addLocalEdit(edit0);
expect(log.numberOfLocalEdits).to.equal(1);
expect(log.numberOfSequencedEdits).to.equal(0, 'Log should have only local edits.');
log.addLocalEdit(edit1);
expect(log.numberOfLocalEdits).to.equal(2);
expect(log.numberOfSequencedEdits).to.equal(0, 'Log should have only local edits.');
expect(log.length).to.equal(2);
});
it('tracks the min sequence number of sequenced edits', () => {
const log = new EditLog();
expect(log.minSequenceNumber).equals(0);
log.addSequencedEdit(edit0, { sequenceNumber: 1, referenceSequenceNumber: 0 });
expect(log.minSequenceNumber).equals(0);
log.addSequencedEdit(edit1, { sequenceNumber: 43, referenceSequenceNumber: 42, minimumSequenceNumber: 42 });
expect(log.minSequenceNumber).equals(42);
expect(() =>
log.addSequencedEdit('fake-edit' as unknown as Edit<unknown>, {
sequenceNumber: 44,
referenceSequenceNumber: 43,
})
).throws('min number');
});
it('detects causal ordering violations', () => {
const log = new EditLog();
log.addLocalEdit(edit0);
log.addLocalEdit(edit1);
expect(() => log.addSequencedEdit(edit1, { sequenceNumber: 1, referenceSequenceNumber: 0 })).throws('ordering');
});
it('can sequence a local edit', async () => {
const log = new EditLog();
log.addLocalEdit(edit0);
expect(log.numberOfLocalEdits).to.equal(1);
let editFromId0 = await log.tryGetEdit(id0);
expect(editFromId0).to.not.be.undefined;
expect(assertNotUndefined(editFromId0).id).equals(edit0.id, 'Log should contain local edit.');
log.addSequencedEdit(edit0, { sequenceNumber: 1, referenceSequenceNumber: 0 });
expect(log.length).to.equal(1);
expect(log.numberOfSequencedEdits).to.equal(1);
expect(log.numberOfLocalEdits).to.equal(0, 'Log should have only sequenced edits.');
editFromId0 = await log.tryGetEdit(id0);
expect(editFromId0).to.not.be.undefined;
expect(assertNotUndefined(editFromId0).id).equals(edit0.id, 'Log should contain sequenced edit.');
});
it('Throws on duplicate sequenced edits', async () => {
const log = new EditLog();
log.addSequencedEdit(edit0, { sequenceNumber: 1, referenceSequenceNumber: 0 });
expect(() => log.addSequencedEdit(edit0, { sequenceNumber: 1, referenceSequenceNumber: 0 }))
.to.throw(Error)
.that.has.property('message')
.which.matches(/Duplicate/);
});
it('can sequence multiple local edits', async () => {
const log = new EditLog();
const ids: EditId[] = [];
const numEdits = 10;
for (let i = 0; i < numEdits; i++) {
const edit = newEdit([]);
log.addLocalEdit(edit);
ids.push(edit.id);
expect(log.getIndexOfId(edit.id)).equals(i, 'Local edits should be appended to the end of the log.');
}
expect(log.length).equals(log.numberOfLocalEdits).and.equals(numEdits, 'Only local edits should be present.');
log.sequenceLocalEdits();
expect(log.editIds).to.deep.equal(ids, 'Sequencing a local edit should not change its index.');
expect(log.length)
.equals(log.numberOfSequencedEdits)
.and.equals(numEdits, 'Only sequenced edits should be present.');
});
it('can correctly compare equality to other edit logs', () => {
const edit0Copy: Edit<Change> = { ...edit0 };
const edit1Copy: Edit<Change> = { ...edit1 };
const { editWithoutId: editWithoutId0Copy } = separateEditAndId(edit0Copy);
const { editWithoutId: editWithoutId1Copy } = separateEditAndId(edit1Copy);
const editChunks = [{ startRevision: 0, chunk: [editWithoutId0, editWithoutId1] }];
const editChunksCopy = [{ startRevision: 0, chunk: [editWithoutId0Copy, editWithoutId1Copy] }];
const editIds = [id0, id1];
const log0 = new EditLog({ editChunks, editIds });
const log1 = new EditLog({ editChunks: editChunksCopy, editIds });
expect(log0.equals(log1)).to.be.true;
const log2 = new EditLog<Change>({
editChunks: [{ startRevision: 0, chunk: [editWithoutId0] }],
editIds: [id0],
});
log2.addLocalEdit(edit1Copy);
expect(log0.equals(log2)).to.be.true;
const differentLog = new EditLog({
editChunks: [{ startRevision: 0, chunk: [editWithoutId0] }],
editIds: [id0],
});
expect(log0.equals(differentLog)).to.be.false;
});
it('creates a new edit chunk once the previous one has been filled', () => {
const log = new EditLog();
for (let i = 0; i < log.editsPerChunk; i++) {
const edit = newEdit([]);
log.addSequencedEdit(edit, { sequenceNumber: i + 1, referenceSequenceNumber: i });
expect(log.getEditLogSummary().editChunks.length).to.be.equal(1);
}
const edit = newEdit([]);
log.addSequencedEdit(edit, {
sequenceNumber: log.editsPerChunk,
referenceSequenceNumber: log.editsPerChunk - 1,
});
expect(log.getEditLogSummary().editChunks.length).to.be.equal(2);
});
it('can load edits from a handle', async () => {
const log = createEditLogWithHandles();
// Check that each edit can be retrieved correctly
for (let i = 0; i < 10; i++) {
expect((await log.getEditAtIndex(i)).id).to.equal(log.editIds[i]);
}
});
it('can add edits to logs with varying edit chunk sizes', async () => {
const numberOfChunks = 2;
const editsPerChunk = 5;
const log = createEditLogWithHandles(numberOfChunks, editsPerChunk, 100);
// Load the edits for the last edit chunk
await log.getEditAtIndex(numberOfChunks * editsPerChunk - 1);
// Add a sequenced edit and check it's been added
const edit = newEdit([]);
log.addSequencedEdit(edit, {
sequenceNumber: log.editsPerChunk,
referenceSequenceNumber: log.editsPerChunk - 1,
});
expect(log.getIdAtIndex(numberOfChunks * editsPerChunk)).to.equal(edit.id);
});
}); | the_stack |
import { GM_xmlhttpRequest } from '../@types/tm_f'
/**
* 由B站cookie获取token
* 因为Tampermonkey的限制或者bug, 无法独立设置cookie, 所以不支持多用户
* 使用之前请确认已经登录
* 使用方法 await new BilibiliToken().getToken()
* 更多高级用法请自行开发
*
* @class BilibiliToken
*/
class BilibiliToken {
protected _W = typeof unsafeWindow === 'undefined' ? window : unsafeWindow
protected static readonly __loginSecretKey: string = '59b43e04ad6965f34319062b478f83dd'
public static readonly loginAppKey: string = '4409e2ce8ffd12b8'
protected static readonly __secretKey: string = '560c52ccd288fed045859ed18bffd973'
public static readonly appKey: string = '1d8b6e7d45233436'
public static get biliLocalId(): string { return this.RandomID(20) }
public biliLocalId = BilibiliToken.biliLocalId
public static readonly build: string = '102401'
public static get buvid(): string { return this.RandomID(37).toLocaleUpperCase() }
public buvid = BilibiliToken.buvid
public static readonly channel: string = 'master'
public static readonly device: string = 'Sony'
// 同一客户端与biliLocalId相同
public static get deviceId(): string { return this.biliLocalId }
public deviceId = this.biliLocalId
public static readonly deviceName: string = 'J9110'
public static readonly devicePlatform: string = 'Android10SonyJ9110'
public static get fingerprint(): string { return this.RandomID(62) }
public fingerprint = BilibiliToken.fingerprint
// 同一客户端与buvid相同
public static get guid(): string { return this.buvid }
public guid = this.buvid
// 同一客户端与fingerprint相同
public static get localFingerprint(): string { return this.fingerprint }
public localFingerprint = this.fingerprint
// 同一客户端与buvid相同
public static get localId(): string { return this.buvid }
public localId = this.buvid
public static readonly mobiApp: string = 'android_tv_yst'
public static readonly networkstate: string = 'wifi'
public static readonly platform: string = 'android'
/**
* 谜一样的TS
*
* @readonly
* @static
* @type {number}
* @memberof BilibiliToken
*/
public static get TS(): number { return Math.floor(Date.now() / 1000) }
/**
* 谜一样的RND
*
* @readonly
* @static
* @type {number}
* @memberof BilibiliToken
*/
public static get RND(): number { return this.RandomNum(9) }
/**
* 谜一样的RandomNum
*
* @static
* @param {number} length
* @returns {number}
* @memberof BilibiliToken
*/
public static RandomNum(length: number): number {
const words = '0123456789'
let randomNum = ''
randomNum += words[Math.floor(Math.random() * 9) + 1]
for (let i = 0; i < length - 1; i++) randomNum += words[Math.floor(Math.random() * 10)]
return +randomNum
}
/**
* 谜一样的RandomID
*
* @static
* @param {number} length
* @returns {string}
* @memberof BilibiliToken
*/
public static RandomID(length: number): string {
const words = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
let randomID = ''
randomID += words[Math.floor(Math.random() * 61) + 1]
for (let i = 0; i < length - 1; i++) randomID += words[Math.floor(Math.random() * 62)]
return randomID
}
/**
* 请求头
*
* @static
* @type {XHRheaders}
* @memberof BilibiliToken
*/
public static get headers(): XHRheaders {
return {
'User-Agent': 'Mozilla/5.0 BiliTV/1.2.4.1 (bbcallen@gmail.com)',
'APP-KEY': this.mobiApp,
'Buvid': this.buvid,
'env': 'prod'
}
}
/**
* 请求头
*
* @type {XHRheaders}
* @memberof BilibiliToken
*/
public headers: XHRheaders = {
'User-Agent': 'Mozilla/5.0 BiliTV/1.2.4.1 (bbcallen@gmail.com)',
'APP-KEY': BilibiliToken.mobiApp,
'Buvid': this.buvid,
'env': 'prod'
}
/**
* 登录请求参数
*
* @readonly
* @static
* @type {string}
* @memberof BilibiliToken
*/
public static get loginQuery(): string {
const biliLocalId = this.biliLocalId
const buvid = this.buvid
const fingerprint = this.fingerprint
return `appkey=${this.loginAppKey}&bili_local_id=${biliLocalId}&build=${this.build}&buvid=${buvid}&channel=${this.channel}&device=${biliLocalId}\
&device_id=${this.deviceId}&device_name=${this.deviceName}&device_platform=${this.devicePlatform}&fingerprint=${fingerprint}&guid=${buvid}\
&local_fingerprint=${fingerprint}&local_id=${buvid}&mobi_app=${this.mobiApp}&networkstate=${this.networkstate}&platform=${this.platform}`
}
/**
* 登录请求参数
*
* @readonly
* @type {string}
* @memberof BilibiliToken
*/
public get loginQuery(): string {
const biliLocalId = this.biliLocalId
const buvid = this.buvid
const fingerprint = this.fingerprint
return `appkey=${BilibiliToken.loginAppKey}&bili_local_id=${biliLocalId}&build=${BilibiliToken.build}&buvid=${buvid}&channel=${BilibiliToken.channel}&device=${biliLocalId}\
&device_id=${this.deviceId}&device_name=${BilibiliToken.deviceName}&device_platform=${BilibiliToken.devicePlatform}&fingerprint=${fingerprint}&guid=${buvid}\
&local_fingerprint=${fingerprint}&local_id=${buvid}&mobi_app=${BilibiliToken.mobiApp}&networkstate=${BilibiliToken.networkstate}&platform=${BilibiliToken.platform}`
}
/**
* 对参数签名
*
* @static
* @param {string} params
* @param {boolean} [ts=true]
* @param {string} [secretKey=this.__secretKey]
* @returns {string}
* @memberof BilibiliToken
*/
public static signQuery(params: string, ts: boolean = true, secretKey: string = this.__secretKey): string {
let paramsSort = params
if (ts) paramsSort = `${params}&ts=${this.TS}`
paramsSort = paramsSort.split('&').sort().join('&')
const paramsSecret = paramsSort + secretKey
const paramsHash = this.md5(paramsSecret)
return `${paramsSort}&sign=${paramsHash}`
}
/**
* 对登录参数加参后签名
*
* @static
* @param {string} [params]
* @returns {string}
* @memberof BilibiliToken
*/
public static signLoginQuery(params?: string): string {
const paramsBase = params === undefined ? this.loginQuery : `${params}&${this.loginQuery}`
return this.signQuery(paramsBase, true, this.__loginSecretKey)
}
/**
* 对登录参数加参后签名
*
* @param {string} [params]
* @returns {string}
* @memberof BilibiliToken
*/
public signLoginQuery(params?: string): string {
const paramsBase = params === undefined ? this.loginQuery : `${params}&${this.loginQuery}`
return BilibiliToken.signQuery(paramsBase, true, BilibiliToken.__loginSecretKey)
}
/**
* 获取二维码
*
* @returns {(Promise<string | void>)}
* @memberof BilibiliToken
*/
public async getAuthCode(): Promise<string | void> {
const authCode = await BilibiliToken.XHR<authCode>({
GM: true,
anonymous: true,
method: 'POST',
url: 'https://passport.bilibili.com/x/passport-tv-login/qrcode/auth_code',
data: this.signLoginQuery(),
responseType: 'json',
headers: this.headers
})
if (authCode !== undefined && authCode.response.status === 200 && authCode.body.code === 0) return authCode.body.data.auth_code
return console.error('getAuthCode', authCode)
}
/**
* 确认二维码
*
* @param {string} authCode
* @param {string} csrf
* @returns {(Promise<string | void>)}
* @memberof BilibiliToken
*/
public async qrcodeConfirm(authCode: string, csrf: string): Promise<string | void> {
const confirm = await BilibiliToken.XHR<confirm>({
GM: true,
method: 'POST',
url: 'https://passport.bilibili.com/x/passport-tv-login/h5/qrcode/confirm',
data: `auth_code=${authCode}&csrf=${csrf}`,
responseType: 'json',
headers: this.headers
})
if (confirm !== undefined && confirm.response.status === 200 && confirm.body.code === 0) return confirm.body.data.gourl
return console.error('qrcodeConfirm', confirm)
}
/**
* 取得token
*
* @param {string} authCode
* @returns {(Promise<pollData | void>)}
* @memberof BilibiliToken
*/
public async qrcodePoll(authCode: string): Promise<pollData | void> {
const poll = await BilibiliToken.XHR<poll>({
GM: true,
anonymous: true,
method: 'POST',
url: 'https://passport.bilibili.com/x/passport-tv-login/qrcode/poll',
data: this.signLoginQuery(`auth_code=${authCode}`),
responseType: 'json',
headers: this.headers
})
if (poll !== undefined && poll.response.status === 200 && poll.body.code === 0) return poll.body.data
return console.error('qrcodePoll', poll)
}
/**
* 获取此时浏览器登录账号token
*
* @returns {(Promise<pollData | void>)}
* @memberof BilibiliToken
*/
public async getToken(): Promise<pollData | void> {
const cookie = this._W.document.cookie.match(/bili_jct=(?<csrf>.*?);/)
if (cookie === null || cookie.groups === undefined) return console.error('getToken', 'cookie获取失败')
const csrf = cookie.groups['csrf']
const authCode = await this.getAuthCode()
if (authCode === undefined) return
const confirm = await this.qrcodeConfirm(authCode, csrf)
if (confirm === undefined) return
const token = await this.qrcodePoll(authCode)
if (token === undefined) return
return token
}
/*
* JavaScript MD5
* https://github.com/blueimp/JavaScript-MD5
*
* Copyright 2011, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* https://opensource.org/licenses/MIT
*
* Based on
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
public static md5(string: string, key?: string, raw?: boolean): string {
return md5(string, key, raw)
/**
* Add integers, wrapping at 2^32.
* This uses 16-bit operations internally to work around bugs in interpreters.
*
* @param {number} x First integer
* @param {number} y Second integer
* @returns {number} Sum
*/
function safeAdd(x: number, y: number): number {
var lsw = (x & 0xffff) + (y & 0xffff)
var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
return (msw << 16) | (lsw & 0xffff)
}
/**
* Bitwise rotate a 32-bit number to the left.
*
* @param {number} num 32-bit number
* @param {number} cnt Rotation count
* @returns {number} Rotated number
*/
function bitRotateLeft(num: number, cnt: number): number {
return (num << cnt) | (num >>> (32 - cnt))
}
/**
* Basic operation the algorithm uses.
*
* @param {number} q q
* @param {number} a a
* @param {number} b b
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
function md5cmn(q: number, a: number, b: number, x: number, s: number, t: number): number {
return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b)
}
/**
* Basic operation the algorithm uses.
*
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @param {number} d d
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
function md5ff(a: number, b: number, c: number, d: number, x: number, s: number, t: number): number {
return md5cmn((b & c) | (~b & d), a, b, x, s, t)
}
/**
* Basic operation the algorithm uses.
*
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @param {number} d d
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
function md5gg(a: number, b: number, c: number, d: number, x: number, s: number, t: number): number {
return md5cmn((b & d) | (c & ~d), a, b, x, s, t)
}
/**
* Basic operation the algorithm uses.
*
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @param {number} d d
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
function md5hh(a: number, b: number, c: number, d: number, x: number, s: number, t: number): number {
return md5cmn(b ^ c ^ d, a, b, x, s, t)
}
/**
* Basic operation the algorithm uses.
*
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @param {number} d d
* @param {number} x x
* @param {number} s s
* @param {number} t t
* @returns {number} Result
*/
function md5ii(a: number, b: number, c: number, d: number, x: number, s: number, t: number): number {
return md5cmn(c ^ (b | ~d), a, b, x, s, t)
}
/**
* Calculate the MD5 of an array of little-endian words, and a bit length.
*
* @param {Array} x Array of little-endian words
* @param {number} len Bit length
* @returns {Array<number>} MD5 Array
*/
function binlMD5(x: Array<any>, len: number): Array<number> {
/* append padding */
x[len >> 5] |= 0x80 << len % 32
x[(((len + 64) >>> 9) << 4) + 14] = len
var i
var olda
var oldb
var oldc
var oldd
var a = 1732584193
var b = -271733879
var c = -1732584194
var d = 271733878
for (i = 0; i < x.length; i += 16) {
olda = a
oldb = b
oldc = c
oldd = d
a = md5ff(a, b, c, d, x[i], 7, -680876936)
d = md5ff(d, a, b, c, x[i + 1], 12, -389564586)
c = md5ff(c, d, a, b, x[i + 2], 17, 606105819)
b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330)
a = md5ff(a, b, c, d, x[i + 4], 7, -176418897)
d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426)
c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341)
b = md5ff(b, c, d, a, x[i + 7], 22, -45705983)
a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416)
d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417)
c = md5ff(c, d, a, b, x[i + 10], 17, -42063)
b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162)
a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682)
d = md5ff(d, a, b, c, x[i + 13], 12, -40341101)
c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290)
b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329)
a = md5gg(a, b, c, d, x[i + 1], 5, -165796510)
d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632)
c = md5gg(c, d, a, b, x[i + 11], 14, 643717713)
b = md5gg(b, c, d, a, x[i], 20, -373897302)
a = md5gg(a, b, c, d, x[i + 5], 5, -701558691)
d = md5gg(d, a, b, c, x[i + 10], 9, 38016083)
c = md5gg(c, d, a, b, x[i + 15], 14, -660478335)
b = md5gg(b, c, d, a, x[i + 4], 20, -405537848)
a = md5gg(a, b, c, d, x[i + 9], 5, 568446438)
d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690)
c = md5gg(c, d, a, b, x[i + 3], 14, -187363961)
b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501)
a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467)
d = md5gg(d, a, b, c, x[i + 2], 9, -51403784)
c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473)
b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734)
a = md5hh(a, b, c, d, x[i + 5], 4, -378558)
d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463)
c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562)
b = md5hh(b, c, d, a, x[i + 14], 23, -35309556)
a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060)
d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353)
c = md5hh(c, d, a, b, x[i + 7], 16, -155497632)
b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640)
a = md5hh(a, b, c, d, x[i + 13], 4, 681279174)
d = md5hh(d, a, b, c, x[i], 11, -358537222)
c = md5hh(c, d, a, b, x[i + 3], 16, -722521979)
b = md5hh(b, c, d, a, x[i + 6], 23, 76029189)
a = md5hh(a, b, c, d, x[i + 9], 4, -640364487)
d = md5hh(d, a, b, c, x[i + 12], 11, -421815835)
c = md5hh(c, d, a, b, x[i + 15], 16, 530742520)
b = md5hh(b, c, d, a, x[i + 2], 23, -995338651)
a = md5ii(a, b, c, d, x[i], 6, -198630844)
d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415)
c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905)
b = md5ii(b, c, d, a, x[i + 5], 21, -57434055)
a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571)
d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606)
c = md5ii(c, d, a, b, x[i + 10], 15, -1051523)
b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799)
a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359)
d = md5ii(d, a, b, c, x[i + 15], 10, -30611744)
c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380)
b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649)
a = md5ii(a, b, c, d, x[i + 4], 6, -145523070)
d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379)
c = md5ii(c, d, a, b, x[i + 2], 15, 718787259)
b = md5ii(b, c, d, a, x[i + 9], 21, -343485551)
a = safeAdd(a, olda)
b = safeAdd(b, oldb)
c = safeAdd(c, oldc)
d = safeAdd(d, oldd)
}
return [a, b, c, d]
}
/**
* Convert an array of little-endian words to a string
*
* @param {Array<number>} input MD5 Array
* @returns {string} MD5 string
*/
function binl2rstr(input: Array<number>): string {
var i
var output = ''
var length32 = input.length * 32
for (i = 0; i < length32; i += 8) {
output += String.fromCharCode((input[i >> 5] >>> i % 32) & 0xff)
}
return output
}
/**
* Convert a raw string to an array of little-endian words
* Characters >255 have their high-byte silently ignored.
*
* @param {string} input Raw input string
* @returns {Array<number>} Array of little-endian words
*/
function rstr2binl(input: string): Array<number> {
var i
var output = []
output[(input.length >> 2) - 1] = undefined
for (i = 0; i < output.length; i += 1) {
output[i] = 0
}
var length8 = input.length * 8
for (i = 0; i < length8; i += 8) {
// @ts-ignore
output[i >> 5] |= (input.charCodeAt(i / 8) & 0xff) << i % 32
}
// @ts-ignore
return output
}
/**
* Calculate the MD5 of a raw string
*
* @param {string} s Input string
* @returns {string} Raw MD5 string
*/
function rstrMD5(s: string): string {
return binl2rstr(binlMD5(rstr2binl(s), s.length * 8))
}
/**
* Calculates the HMAC-MD5 of a key and some data (raw strings)
*
* @param {string} key HMAC key
* @param {string} data Raw input string
* @returns {string} Raw MD5 string
*/
function rstrHMACMD5(key: string, data: string): string {
var i
var bkey = rstr2binl(key)
var ipad = []
var opad = []
var hash
ipad[15] = opad[15] = undefined
if (bkey.length > 16) {
bkey = binlMD5(bkey, key.length * 8)
}
for (i = 0; i < 16; i += 1) {
ipad[i] = bkey[i] ^ 0x36363636
opad[i] = bkey[i] ^ 0x5c5c5c5c
}
hash = binlMD5(ipad.concat(rstr2binl(data)), 512 + data.length * 8)
return binl2rstr(binlMD5(opad.concat(hash), 512 + 128))
}
/**
* Convert a raw string to a hex string
*
* @param {string} input Raw input string
* @returns {string} Hex encoded string
*/
function rstr2hex(input: string): string {
var hexTab = '0123456789abcdef'
var output = ''
var x
var i
for (i = 0; i < input.length; i += 1) {
x = input.charCodeAt(i)
output += hexTab.charAt((x >>> 4) & 0x0f) + hexTab.charAt(x & 0x0f)
}
return output
}
/**
* Encode a string as UTF-8
*
* @param {string} input Input string
* @returns {string} UTF8 string
*/
function str2rstrUTF8(input: string): string {
return unescape(encodeURIComponent(input))
}
/**
* Encodes input string as raw MD5 string
*
* @param {string} s Input string
* @returns {string} Raw MD5 string
*/
function rawMD5(s: string): string {
return rstrMD5(str2rstrUTF8(s))
}
/**
* Encodes input string as Hex encoded string
*
* @param {string} s Input string
* @returns {string} Hex encoded string
*/
function hexMD5(s: string): string {
return rstr2hex(rawMD5(s))
}
/**
* Calculates the raw HMAC-MD5 for the given key and data
*
* @param {string} k HMAC key
* @param {string} d Input string
* @returns {string} Raw MD5 string
*/
function rawHMACMD5(k: string, d: string): string {
return rstrHMACMD5(str2rstrUTF8(k), str2rstrUTF8(d))
}
/**
* Calculates the Hex encoded HMAC-MD5 for the given key and data
*
* @param {string} k HMAC key
* @param {string} d Input string
* @returns {string} Raw MD5 string
*/
function hexHMACMD5(k: string, d: string): string {
return rstr2hex(rawHMACMD5(k, d))
}
/**
* Calculates MD5 value for a given string.
* If a key is provided, calculates the HMAC-MD5 value.
* Returns a Hex encoded string unless the raw argument is given.
*
* @param {string} string Input string
* @param {string} [key] HMAC key
* @param {boolean} [raw] Raw output switch
* @returns {string} MD5 output
*/
function md5(string: string, key?: string, raw?: boolean): string {
if (!key) {
if (!raw) {
return hexMD5(string)
}
return rawMD5(string)
}
if (!raw) {
return hexHMACMD5(key, string)
}
return rawHMACMD5(key, string)
}
}
/**
*
* 使用Promise封装xhr
* 因为上下文问题, GM_xmlhttpRequest为单独一项
* fetch和GM_xmlhttpRequest兼容过于复杂, 所以使用XMLHttpRequest
*
* @static
* @template T
* @param {XHROptions} XHROptions
* @returns {(Promise<response<T> | undefined>)}
* @memberof BilibiliToken
*/
public static XHR<T>(XHROptions: XHROptions): Promise<response<T> | undefined> {
return new Promise(resolve => {
const onerror = (error: any) => {
console.error(GM_info.script.name, error)
resolve(undefined)
}
if (XHROptions.GM) {
if (XHROptions.method === 'POST') {
if (XHROptions.headers === undefined) XHROptions.headers = {}
if (XHROptions.headers['Content-Type'] === undefined)
XHROptions.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
}
XHROptions.timeout = 30 * 1000
XHROptions.onload = res => resolve({ response: res, body: res.response })
XHROptions.onerror = onerror
XHROptions.ontimeout = onerror
GM_xmlhttpRequest(XHROptions)
}
else {
const xhr = new XMLHttpRequest()
xhr.open(XHROptions.method, XHROptions.url)
if (XHROptions.method === 'POST' && xhr.getResponseHeader('Content-Type') === null)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8')
if (XHROptions.withCredentials) xhr.withCredentials = true
if (XHROptions.responseType !== undefined) xhr.responseType = XHROptions.responseType
xhr.timeout = 30 * 1000
xhr.onload = ev => {
const res = <XMLHttpRequest>ev.target
resolve({ response: res, body: res.response })
}
xhr.onerror = onerror
xhr.ontimeout = onerror
xhr.send(XHROptions.data)
}
})
}
}
export default BilibiliToken | the_stack |
import * as moment from 'moment';
import { Bucket, DirectoryObject, graph, Plan, Planner, TaskAddResult, Group } from '@pnp/graph';
import { IGroup } from './IGroups';
import { IGroupMember, IMember } from './IGroupMembers';
import { IPlannerBucket } from './IPlannerBucket';
import { IPlannerPlan } from './IPlannerPlan';
import { IPlannerPlanDetails } from './IPlannerPlanDetails';
import { IPlannerPlanExtended } from './IPlannerPlanExtended';
import { ITask } from './ITask';
import { ITaskDetails } from './ITaskDetails';
import { ITaskProperty } from './ITaskProperty';
import { IUser } from './IUser';
import { MSGraphClient, SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { PropertyPaneDynamicFieldSet } from "@microsoft/sp-property-pane";
import {
SearchProperty,
SearchQuery,
SearchResults,
SortDirection,
sp,
Web,
PagedItemCollection,
ChunkedFileUploadProgressData,
FileAddResult
} from '@pnp/pnpjs';
import { SPComponentLoader } from '@microsoft/sp-loader';
import { User } from '@pnp/graph/src/users';
import * as $ from 'jquery';
import { List } from 'office-ui-fabric-react';
import * as MicrosoftGraph from '@microsoft/microsoft-graph-types';
const DEFAULT_PERSONA_IMG_HASH: string = '7ad602295f8386b7615b582d87bcc294';
const DEFAULT_IMAGE_PLACEHOLDER_HASH: string = '4a48f26592f4e1498d7a478a4c48609c';
const MD5_MODULE_ID: string = '8494e7d7-6b99-47b2-a741-59873e42f16f';
const PROFILE_IMAGE_URL: string = '/_layouts/15/userphoto.aspx?size=M&accountname=';
export default class spservices {
private graphClient: MSGraphClient = null;
public currentUser: string = undefined;
constructor(public context: WebPartContext) {
/*
Initialize MSGraph
*/
sp.setup({
spfxContext: this.context
});
graph.setup({
spfxContext: this.context
});
this.currentUser = this.context.pageContext.user.email;
}
public async getTaskById(taskId: string): Promise<ITask> {
try {
const task: ITask = await graph.planner.tasks.getById(taskId).get();
return task;
} catch (error) {
Promise.reject(error);
}
}
/**
* Gets user groups
* @returns user groups
*/
public async getUserGroups(): Promise<IGroup[]> {
let o365Groups: IGroup[] = [];
try {
this.graphClient = await this.context.msGraphClientFactory.getClient();
const groups = await this.graphClient
.api(`me/memberof`)
.version('v1.0')
.get();
// Get O365 Groups
for (const group of groups.value as IGroup[]) {
const hasO365Group = group.groupTypes && group.groupTypes.length > 0 ? group.groupTypes.indexOf('Unified') : -1;
if (hasO365Group !== -1) {
o365Groups.push(group);
}
}
return o365Groups;
} catch (error) {
Promise.reject(error);
}
}
/**
* Gets user plans by group id
* @param groupId
* @returns user plans by group id
*/
public async getUserPlansByGroupId(groupId: string): Promise<IPlannerPlan[]> {
try {
const groupPlans: IPlannerPlan[] = await graph.groups.getById(groupId).plans.get();
return groupPlans;
} catch (error) {
Promise.reject(error);
}
}
/**
* Gets user plans
* @returns user plans
*/
public async getUserPlans(): Promise<IPlannerPlanExtended[]> {
try {
let userPlans: IPlannerPlanExtended[] = [];
const o365Groups: IGroup[] = await this.getUserGroups();
for (const group of o365Groups) {
const plans: IPlannerPlan[] = await this.getUserPlansByGroupId(group.id);
for (const plan of plans) {
const groupPhoto: string = await this.getGroupPhoto(group.id);
const userPlan: IPlannerPlanExtended = { ...plan, planPhoto: groupPhoto };
userPlans.push(userPlan);
}
}
// Sort plans by Title
userPlans = userPlans.sort((a, b) => {
if (a.title < b.title) return -1;
if (a.title > b.title) return 1;
return 0;
});
return userPlans;
} catch (error) {
Promise.reject(error);
}
}
/**
* Gets group photo
* @param groupId
* @returns group photo
*/
public async getGroupPhoto(groupId: string): Promise<any> {
return new Promise(async (resolve, reject) => {
try {
let url: any = '';
const photo = await graph.groups.getById(groupId).photo.getBlob();
let reader = new FileReader();
reader.addEventListener(
'load',
() => {
url = reader.result; // data url
resolve(url);
},
false
);
reader.readAsDataURL(photo); // converts the blob to base64 and calls onload
} catch (error) {
resolve(undefined);
}
});
}
/**
* Gets tasks
* @returns tasks
*/
public async getTasks(): Promise<ITask[]> {
try {
//const myTasks: ITask[] = await graph.me.tasks.get();
let myTasks: ITask[] = [];
this.graphClient = await this.context.msGraphClientFactory.getClient();
const results: any = await this.graphClient
.api(`/me/planner/tasks`)
.version('v1.0')
.get();
return results.value;
} catch (error) {
throw new Error('Error on get user task');
}
}
/**
* Gets group members
* @param groupId
* @returns group members
*/
public async getGroupMembers(groupId: string, skipToken: string): Promise<IGroupMember> {
try {
let groupMembers: IGroupMember;
if (skipToken) {
this.graphClient = await this.context.msGraphClientFactory.getClient();
groupMembers = await this.graphClient
.api(`groups/${groupId}/members`)
.version('v1.0')
.skipToken(skipToken)
.get();
} else {
this.graphClient = await this.context.msGraphClientFactory.getClient();
groupMembers = await this.graphClient
.api(`groups/${groupId}/members`)
.version('v1.0')
.top(100)
.get();
}
return groupMembers;
} catch (error) {
throw new Error('Error on get group members');
}
}
/**
* Gets task details
* @param taskId
* @returns task details
*/
public async getTaskDetails(taskId: string): Promise<ITaskDetails> {
try {
const taskDetails: ITaskDetails = await graph.planner.tasks.getById(taskId).details.get();
return taskDetails;
} catch (error) {
Promise.reject(error);
}
return null;
}
/**
* Updates task as completed
* @param taskId
* @param etag
* @returns task as completed
*/
public async updateTaskAsCompleted(taskId: string, etag: string): Promise<void> {
try {
// await graph.planner.tasks.getById(taskId).update({percentComplete: 100});
this.graphClient = await this.context.msGraphClientFactory.getClient();
await this.graphClient
.api(`planner/tasks/${taskId}`)
.version('v1.0')
.header(`If-Match`, etag)
.patch({ percentComplete: 100 });
} catch (error) {
throw new Error('Error get task Details');
}
}
/**
* Updates task not started
* @param taskId
* @param etag
* @returns task not started
*/
public async updateTaskNotStarted(taskId: string, etag: string): Promise<void> {
try {
//await graph.planner.tasks.getById(taskId).update({percentComplete: 100});
await this.graphClient
.api(`planner/tasks/${taskId}`)
.version('v1.0')
.header(`If-Match`, etag)
.patch({ percentComplete: 0 });
} catch (error) {
throw new Error('Error on update task progress');
}
}
/**
* async getPlan
planId:string :Promise<string> */
public async getPlan(planId: string): Promise<IPlannerPlan> {
try {
const plan: Plan = await graph.planner.plans.getById(planId);
const plannerPlan: IPlannerPlan = await plan.get();
return plannerPlan;
} catch (error) {
Promise.reject(error);
}
}
public async updatePlannerDetailsProperty(
plannerId: string,
plannerDetailsPropertyName: string,
plannerDetailsPropertyValue: any,
etag: string
): Promise<string> {
try {
let parameterValue: any;
// Test typeof parameter
switch (typeof plannerDetailsPropertyValue) {
case 'object':
parameterValue = JSON.stringify(plannerDetailsPropertyValue);
break;
case 'number':
parameterValue = plannerDetailsPropertyValue;
break;
case 'string':
parameterValue = `'${plannerDetailsPropertyValue}'`;
break;
default:
parameterValue = `'${plannerDetailsPropertyValue}'`;
break;
}
this.graphClient = await this.context.msGraphClientFactory.getClient();
await this.graphClient
.api(`planner/plans/${plannerId}/details`)
.version('v1.0')
.header(`If-Match`, etag)
.patch(`{${plannerDetailsPropertyName} : ${parameterValue}}`);
// const _task: ITaskProperty = {[taskPropertyName] : taskPropertyValue};
// await graph.planner.tasks.getById(taskId).update(_task, etag);
const plannerDetails: IPlannerPlanDetails = await this.getPlanDetails(plannerId);
return plannerDetails['@odata.etag'];
} catch (error) {
console.log(error);
throw new Error('Error on update planner Details');
}
}
/**
* Adds task
* @param taskInfo
* @returns task
*/
public async updateTaskProperty(taskId: string, taskPropertyName: string, taskPropertyValue: any, etag: string): Promise<ITask> {
try {
let parameterValue: any;
// Test typeof parameter
switch (typeof taskPropertyValue) {
case 'object':
parameterValue = JSON.stringify(taskPropertyValue);
break;
case 'number':
parameterValue = taskPropertyValue;
break;
case 'string':
parameterValue = `'${taskPropertyValue}'`;
break;
default:
parameterValue = `'${taskPropertyValue}'`;
break;
}
this.graphClient = await this.context.msGraphClientFactory.getClient();
const task = await this.graphClient
.api(`planner/tasks/${taskId}`)
.version('v1.0')
.headers({["Prefer"]: "return=representation", ["if-Match"]: etag, ["Content-type"]: "application/json"})
.patch(`{${taskPropertyName} : ${parameterValue}}`);
// const _task: ITaskProperty = {[taskPropertyName] : taskPropertyValue};
// await graph.planner.tasks.getById(taskId).update(_task, etag);
// const task = await this.getTaskById(taskId);
// return task2['@odata.etag'];
return task;
} catch (error) {
console.log(error);
throw new Error('Error on add task');
}
}
public async updateTaskDetailsProperty(
taskId: string,
taskPropertyName: string,
taskPropertyValue: object | number | string,
etag: string
): Promise<ITaskDetails> {
try {
let parameterValue: any;
// Test typeof parameter
switch (typeof taskPropertyValue) {
case 'object':
parameterValue = JSON.stringify(taskPropertyValue);
break;
case 'number':
parameterValue = taskPropertyValue;
break;
case 'string':
parameterValue = `'${taskPropertyValue}'`;
break;
default:
parameterValue = `'${taskPropertyValue}'`;
break;
}
this.graphClient = await this.context.msGraphClientFactory.getClient();
const taskDetails = await this.graphClient
.api(`planner/tasks/${taskId}/details`)
.version('v1.0')
.headers({["Prefer"]: "return=representation", ["if-Match"]: etag, ["Content-type"]: "application/json"})
.patch(`{${taskPropertyName} : ${parameterValue}}`);
// const _task: ITaskProperty = {[taskPropertyName] : taskPropertyValue};
// await graph.planner.tasks.getById(taskId).update(_task, etag);
//const taskDetails = await this.getTaskDetails(taskId);
// return taskDetails['@odata.etag'];
return taskDetails;
} catch (error) {
console.log(error);
throw new Error('Error on update property Task, please try later.');
}
}
/**
* Adds task
* @param taskInfo
* @returns task
*/
public async addTask(taskInfo: string[]): Promise<TaskAddResult> {
try {
this.graphClient = await this.context.msGraphClientFactory.getClient();
const task = await this.graphClient
.api(`planner/tasks`)
.version('v1.0')
.post({
planId: taskInfo['planId'],
bucketId: taskInfo['bucketId'],
title: taskInfo['title'],
dueDateTime: taskInfo['dueDate'] ? moment(taskInfo['dueDate']).toISOString() : undefined,
assignments: taskInfo['assignments']
});
//const task: TaskAddResult = await graph.planner.tasks.add( taskInfo['planId'], taskInfo['title'], taskInfo['assignments'], taskInfo['bucketId']);
return task;
} catch (error) {
throw new Error('Error on add task');
}
}
public async deleteTask(taskId: string, etag:string): Promise<void> {
try {
// await graph.planner.tasks.getById(taskId).update({percentComplete: 100});
this.graphClient = await this.context.msGraphClientFactory.getClient();
await this.graphClient
.api(`planner/tasks/${taskId}`)
.version('v1.0')
.header(`If-Match`, etag)
.delete();
} catch (error) {
throw new Error(error);
}
}
/**
* Gets plan details
* @param planId
* @returns plan details
*/
public async getPlanDetails(planId: string): Promise<IPlannerPlanDetails> {
try {
const plan: Plan = await graph.planner.plans.getById(planId);
const plannerPlanDetails: IPlannerPlanDetails = await plan.details.get();
await this.getPlanBuckets(planId);
return plannerPlanDetails;
} catch (error) {
throw new Error('Error on get planner details');
}
}
/**
* Gets plan buckets
* @param planId
* @returns plan buckets
*/
public async getPlanBuckets(planId: string): Promise<IPlannerBucket[]> {
try {
const plan: Plan = await graph.planner.plans.getById(planId);
const plannerBuckets: IPlannerBucket[] = await plan.buckets.get();
return plannerBuckets;
} catch (error) {
throw new Error('Error get Planner buckets');
}
}
/**
* Gets user
* @param userId
* @returns user
*/
public async getUser(userId: string): Promise<IMember> {
try {
const user: IMember = await graph.users.getById(userId).get();
return user;
} catch (error) {
throw new Error('Error on get user details');
}
}
/*
public async getPhoto(userId: string): Promise<any> {
let photo: any = undefined;
try {
let photoBlob = await graph.users.getById(userId).photo.getBlob();
let groupPhotoUrl = window.URL;
photo = groupPhotoUrl.createObjectURL(photoBlob);
} catch (error) {
return undefined;
}
return photo;
}
*/
/**
* Gets user photo
* @param userId
* @returns user photo
*/
public async getUserPhoto(userId): Promise<string> {
const personaImgUrl = PROFILE_IMAGE_URL + userId;
const url: string = await this.getImageBase64(personaImgUrl);
const newHash = await this.getMd5HashForUrl(url);
if (newHash !== DEFAULT_PERSONA_IMG_HASH && newHash !== DEFAULT_IMAGE_PLACEHOLDER_HASH) {
return 'data:image/png;base64,' + url;
} else {
return 'undefined';
}
}
/**
* Get MD5Hash for the image url to verify whether user has default image or custom image
* @param url
*/
private getMd5HashForUrl(url: string) {
return new Promise(async (resolve, reject) => {
const library: any = await this.loadSPComponentById(MD5_MODULE_ID);
try {
const md5Hash = library.Md5Hash;
if (md5Hash) {
const convertedHash = md5Hash(url);
resolve(convertedHash);
}
} catch (error) {
resolve(url);
}
});
}
/**
* Load SPFx component by id, SPComponentLoader is used to load the SPFx components
* @param componentId - componentId, guid of the component library
*/
private loadSPComponentById(componentId: string) {
return new Promise((resolve, reject) => {
SPComponentLoader.loadComponentById(componentId)
.then((component: any) => {
resolve(component);
})
.catch(error => {});
});
}
/**
* Gets image base64
* @param pictureUrl
* @returns image base64
*/
private getImageBase64(pictureUrl: string): Promise<string> {
return new Promise((resolve, reject) => {
let image = new Image();
image.addEventListener('load', () => {
let tempCanvas = document.createElement('canvas');
(tempCanvas.width = image.width), (tempCanvas.height = image.height), tempCanvas.getContext('2d').drawImage(image, 0, 0);
let base64Str;
try {
base64Str = tempCanvas.toDataURL('image/png');
} catch (e) {
return '';
}
base64Str = base64Str.replace(/^data:image\/png;base64,/, '');
resolve(base64Str);
});
image.src = pictureUrl;
});
}
/**
* Searchs users
* @param searchString
* @returns users
*/
public async searchUsers(searchString: string): Promise<IMember[]> {
try {
this.graphClient = await this.context.msGraphClientFactory.getClient();
const returnUsers = await this.graphClient
.api(`users`)
.version('v1.0')
.top(100)
.filter(`startswith(DisplayName, '${searchString}') or startswith(mail, '${searchString}')`)
.get();
return returnUsers.value;
} catch (error) {
throw new Error('Error on search users');
}
}
public async getGrouoUrl(groupId): Promise<string> {
try {
this.graphClient = await this.context.msGraphClientFactory.getClient();
const returnGroupInfo = await this.graphClient
.api(`groups/${groupId}/sites/root`)
.version('v1.0')
.get();
return returnGroupInfo.webUrl;
} catch (error) {
console.log(error.message);
throw new Error('Error get group Url');
}
}
public async getSharePointFiles(groupId: string, sortField: string, ascending: boolean): Promise<PagedItemCollection<any[]>> {
try {
// let libraryUrl: string = await this.getGroupDocumentLibraryUrl(groupId);
const groupUrl: string = await this.getGrouoUrl(groupId);
const web = new Web(groupUrl);
const defualtDocumentLibrary = await web.defaultDocumentLibrary.get();
const results: PagedItemCollection<any[]> = await web.lists
.getById(defualtDocumentLibrary.Id)
.items.select(
'Title',
'File_x0020_Type',
'FileSystemObjectType',
'File/Name',
'File/ServerRelativeUrl',
'File/Title',
'File/Id',
'File/TimeLastModified'
)
.top(8)
.expand('File')
.orderBy(`${sortField}`, ascending)
.getPaged();
return results;
} catch (error) {
throw new Error('Error on read files from Documents ' + error.message);
}
}
/**
* Gets group document library url
* @param groupId
* @returns group document library url
*/
public async getGroupDocumentLibraryUrl(groupId: string): Promise<string> {
try {
this.graphClient = await this.context.msGraphClientFactory.getClient();
const returnGroupDriveInfo = await this.graphClient
.api(`groups/${groupId}/sites/root/drive`)
.version('v1.0')
.get();
return returnGroupDriveInfo.webUrl;
} catch (error) {
console.log(error.message);
throw new Error('Error get group default Document Library');
}
}
public ValidateEmail(mail: string): boolean {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail)) {
return true;
}
return false;
}
public async uploadFileToSharePoint(documentLibrary: string, webUrl: string, fileName: string, fileB64: any): Promise<any> {
try {
const web = new Web(webUrl);
documentLibrary = documentLibrary.replace(location.origin, '');
console.log(documentLibrary);
const rs: FileAddResult = await web.getFolderByServerRelativeUrl(documentLibrary).files.addChunked(
fileName,
fileB64,
(data: ChunkedFileUploadProgressData) => {
console.log('File Upload chunked %', data.currentPointer / data.fileSize);
return data.currentPointer / data.fileSize;
},
true
);
return rs;
// const rs:FileAddResult = await web.getFolderByServerRelativeUrl(documentLibrary).files.add(fileName,fileB64,true);
} catch (error) {
console.log(error);
}
}
} | the_stack |
import {app, BrowserWindow, shell, Menu, BrowserWindowConstructorOptions, Event} from 'electron';
import {isAbsolute, normalize, sep} from 'path';
import {URL, fileURLToPath} from 'url';
import {v4 as uuidv4} from 'uuid';
import isDev from 'electron-is-dev';
import updater from '../updater';
import toElectronBackgroundColor from '../utils/to-electron-background-color';
import {icon, homeDirectory} from '../config/paths';
import createRPC from '../rpc';
import notify from '../notify';
import fetchNotifications from '../notifications';
import Session from '../session';
import contextMenuTemplate from './contextmenu';
import {execCommand} from '../commands';
import {setRendererType, unsetRendererType} from '../utils/renderer-utils';
import {decorateSessionOptions, decorateSessionClass} from '../plugins';
import {enable as remoteEnable} from '@electron/remote/main';
import {configOptions} from '../../lib/config';
import {getWorkingDirectoryFromPID} from 'native-process-working-directory';
export function newWindow(
options_: BrowserWindowConstructorOptions,
cfg: configOptions,
fn?: (win: BrowserWindow) => void
): BrowserWindow {
const classOpts = Object.assign({uid: uuidv4()});
app.plugins.decorateWindowClass(classOpts);
const winOpts: BrowserWindowConstructorOptions = {
minWidth: 370,
minHeight: 190,
backgroundColor: toElectronBackgroundColor(cfg.backgroundColor || '#000'),
titleBarStyle: 'hiddenInset',
title: 'Hyper.app',
// we want to go frameless on Windows and Linux
frame: process.platform === 'darwin',
transparent: process.platform === 'darwin',
icon,
show: Boolean(process.env.HYPER_DEBUG || process.env.HYPERTERM_DEBUG || isDev),
acceptFirstMouse: true,
webPreferences: {
nodeIntegration: true,
navigateOnDragDrop: true,
contextIsolation: false
},
...options_
};
const window = new BrowserWindow(app.plugins.getDecoratedBrowserOptions(winOpts));
// Enable remote module on this window
remoteEnable(window.webContents);
window.uid = classOpts.uid;
app.plugins.onWindowClass(window);
window.uid = classOpts.uid;
const rpc = createRPC(window);
const sessions = new Map<string, Session>();
const updateBackgroundColor = () => {
const cfg_ = app.plugins.getDecoratedConfig();
window.setBackgroundColor(toElectronBackgroundColor(cfg_.backgroundColor || '#000'));
};
// set working directory
let argPath = process.argv[1];
if (argPath && process.platform === 'win32') {
if (/[a-zA-Z]:"/.test(argPath)) {
argPath = argPath.replace('"', sep);
}
argPath = normalize(argPath + sep);
}
let workingDirectory = homeDirectory;
if (argPath && isAbsolute(argPath)) {
workingDirectory = argPath;
} else if (cfg.workingDirectory && isAbsolute(cfg.workingDirectory)) {
workingDirectory = cfg.workingDirectory;
}
// config changes
const cfgUnsubscribe = app.config.subscribe(() => {
const cfg_ = app.plugins.getDecoratedConfig();
// notify renderer
window.webContents.send('config change');
// notify user that shell changes require new sessions
if (cfg_.shell !== cfg.shell || JSON.stringify(cfg_.shellArgs) !== JSON.stringify(cfg.shellArgs)) {
notify('Shell configuration changed!', 'Open a new tab or window to start using the new shell');
}
// update background color if necessary
updateBackgroundColor();
cfg = cfg_;
});
rpc.on('init', () => {
window.show();
updateBackgroundColor();
// If no callback is passed to createWindow,
// a new session will be created by default.
if (!fn) {
fn = (win: BrowserWindow) => {
win.rpc.emit('termgroup add req', {});
};
}
// app.windowCallback is the createWindow callback
// that can be set before the 'ready' app event
// and createWindow definition. It's executed in place of
// the callback passed as parameter, and deleted right after.
(app.windowCallback || fn)(window);
app.windowCallback = undefined;
fetchNotifications(window);
// auto updates
if (!isDev) {
updater(window);
} else {
console.log('ignoring auto updates during dev');
}
});
function createSession(extraOptions: any = {}) {
const uid = uuidv4();
const extraOptionsFiltered: any = {};
Object.keys(extraOptions).forEach((key) => {
if (extraOptions[key] !== undefined) extraOptionsFiltered[key] = extraOptions[key];
});
let cwd = '';
if (cfg.preserveCWD === undefined || cfg.preserveCWD) {
const activePID = extraOptionsFiltered.activeUid && sessions.get(extraOptionsFiltered.activeUid)?.pty?.pid;
try {
cwd = activePID && getWorkingDirectoryFromPID(activePID);
} catch (error) {
console.error(error);
}
cwd = cwd && isAbsolute(cwd) ? cwd : '';
}
// remove the rows and cols, the wrong value of them will break layout when init create
const defaultOptions = Object.assign(
{
cwd: cwd || workingDirectory,
splitDirection: undefined,
shell: cfg.shell,
shellArgs: cfg.shellArgs && Array.from(cfg.shellArgs)
},
extraOptionsFiltered,
{uid}
);
const options = decorateSessionOptions(defaultOptions);
const DecoratedSession = decorateSessionClass(Session);
const session = new DecoratedSession(options);
sessions.set(uid, session);
return {session, options};
}
rpc.on('new', (extraOptions) => {
const {session, options} = createSession(extraOptions);
sessions.set(options.uid, session);
rpc.emit('session add', {
rows: options.rows,
cols: options.cols,
uid: options.uid,
splitDirection: options.splitDirection,
shell: session.shell,
pid: session.pty ? session.pty.pid : null,
activeUid: options.activeUid
});
session.on('data', (data: string) => {
rpc.emit('session data', data);
});
session.on('exit', () => {
rpc.emit('session exit', {uid: options.uid});
unsetRendererType(options.uid);
sessions.delete(options.uid);
});
});
rpc.on('exit', ({uid}) => {
const session = sessions.get(uid);
if (session) {
session.exit();
}
});
rpc.on('unmaximize', () => {
window.unmaximize();
});
rpc.on('maximize', () => {
window.maximize();
});
rpc.on('minimize', () => {
window.minimize();
});
rpc.on('resize', ({uid, cols, rows}) => {
const session = sessions.get(uid);
if (session) {
session.resize({cols, rows});
}
});
rpc.on('data', ({uid, data, escaped}: {uid: string; data: string; escaped: boolean}) => {
const session = sessions.get(uid);
if (session) {
if (escaped) {
const escapedData = session.shell?.endsWith('cmd.exe')
? `"${data}"` // This is how cmd.exe does it
: `'${data.replace(/'/g, `'\\''`)}'`; // Inside a single-quoted string nothing is interpreted
session.write(escapedData);
} else {
session.write(data);
}
}
});
rpc.on('info renderer', ({uid, type}) => {
// Used in the "About" dialog
setRendererType(uid, type);
});
rpc.on('open external', ({url}) => {
void shell.openExternal(url);
});
rpc.on('open context menu', (selection) => {
const {createWindow} = app;
Menu.buildFromTemplate(contextMenuTemplate(createWindow, selection)).popup({window});
});
rpc.on('open hamburger menu', ({x, y}) => {
Menu.getApplicationMenu()!.popup({x: Math.ceil(x), y: Math.ceil(y)});
});
// Same deal as above, grabbing the window titlebar when the window
// is maximized on Windows results in unmaximize, without hitting any
// app buttons
for (const ev of ['maximize', 'unmaximize', 'minimize', 'restore'] as any) {
window.on(ev, () => {
rpc.emit('windowGeometry change', {isMaximized: window.isMaximized()});
});
}
window.on('move', () => {
const position = window.getPosition();
rpc.emit('move', {bounds: {x: position[0], y: position[1]}});
});
rpc.on('close', () => {
window.close();
});
rpc.on('command', (command) => {
const focusedWindow = BrowserWindow.getFocusedWindow();
execCommand(command, focusedWindow!);
});
// pass on the full screen events from the window to react
rpc.win.on('enter-full-screen', () => {
rpc.emit('enter full screen', {});
});
rpc.win.on('leave-full-screen', () => {
rpc.emit('leave full screen', {});
});
const deleteSessions = () => {
sessions.forEach((session, key) => {
session.removeAllListeners();
session.destroy();
sessions.delete(key);
});
};
// we reset the rpc channel only upon
// subsequent refreshes (ie: F5)
let i = 0;
window.webContents.on('did-navigate', () => {
if (i++) {
deleteSessions();
}
});
const handleDrop = (event: Event, url: string) => {
const protocol = typeof url === 'string' && new URL(url).protocol;
if (protocol === 'file:') {
event.preventDefault();
const path = fileURLToPath(url);
rpc.emit('session data send', {data: path, escaped: true});
} else if (protocol === 'http:' || protocol === 'https:') {
event.preventDefault();
rpc.emit('session data send', {data: url});
}
};
// If file is dropped onto the terminal window, navigate and new-window events are prevented
// and his path is added to active session.
window.webContents.on('will-navigate', handleDrop);
window.webContents.on('new-window', handleDrop);
// expose internals to extension authors
window.rpc = rpc;
window.sessions = sessions;
const load = () => {
app.plugins.onWindow(window);
};
// load plugins
load();
const pluginsUnsubscribe = app.plugins.subscribe((err: any) => {
if (!err) {
load();
window.webContents.send('plugins change');
updateBackgroundColor();
}
});
// Keep track of focus time of every window, to figure out
// which one of the existing window is the last focused.
// Works nicely even if a window is closed and removed.
const updateFocusTime = () => {
window.focusTime = process.uptime();
};
window.on('focus', () => {
updateFocusTime();
});
// the window can be closed by the browser process itself
window.clean = () => {
app.config.winRecord(window);
rpc.destroy();
deleteSessions();
cfgUnsubscribe();
pluginsUnsubscribe();
};
// Ensure focusTime is set on window open. The focus event doesn't
// fire from the dock (see bug #583)
updateFocusTime();
return window;
} | the_stack |
import Conditions from '../../../../../resources/conditions';
import NetRegexes from '../../../../../resources/netregexes';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
export type Data = RaidbossData;
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.TheTwinning,
timelineFile: 'twinning.txt',
triggers: [
{
id: 'Twinning Main Head',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3DBC', source: 'Surplus Kaliya' }),
netRegexDe: NetRegexes.startsUsing({ id: '3DBC', source: 'Massengefertigt(?:e|er|es|en) Kaliya' }),
netRegexFr: NetRegexes.startsUsing({ id: '3DBC', source: 'Kaliya De Surplus' }),
netRegexJa: NetRegexes.startsUsing({ id: '3DBC', source: '量産型カーリア' }),
netRegexCn: NetRegexes.startsUsing({ id: '3DBC', source: '量产型卡利亚' }),
netRegexKo: NetRegexes.startsUsing({ id: '3DBC', source: '양산형 칼리야' }),
condition: (data) => data.CanStun() || data.CanSilence(),
response: Responses.stun(),
},
{
id: 'Twinning Berserk',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3DC0', source: 'Vitalized Reptoid' }),
netRegexDe: NetRegexes.startsUsing({ id: '3DC0', source: 'Gestärkt(?:e|er|es|en) Reptoid' }),
netRegexFr: NetRegexes.startsUsing({ id: '3DC0', source: 'Reptoïde Vitalisé' }),
netRegexJa: NetRegexes.startsUsing({ id: '3DC0', source: 'ヴァイタライズ・レプトイド' }),
netRegexCn: NetRegexes.startsUsing({ id: '3DC0', source: '活力化爬虫半人马' }),
netRegexKo: NetRegexes.startsUsing({ id: '3DC0', source: '활성된 파충류' }),
condition: (data) => data.CanStun() || data.CanSilence(),
response: Responses.interrupt(),
},
{
id: 'Twinning 128 Tonze Swing',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3DBA', source: 'Servomechanical Minotaur' }),
netRegexDe: NetRegexes.startsUsing({ id: '3DBA', source: 'Servomechanisch(?:e|er|es|en) Minotaurus' }),
netRegexFr: NetRegexes.startsUsing({ id: '3DBA', source: 'Minotaure Servomécanique' }),
netRegexJa: NetRegexes.startsUsing({ id: '3DBA', source: 'サーヴォ・ミノタウロス' }),
netRegexCn: NetRegexes.startsUsing({ id: '3DBA', source: '自控化弥诺陶洛斯' }),
netRegexKo: NetRegexes.startsUsing({ id: '3DBA', source: '자동제어 미노타우로스' }),
condition: (data) => data.CanSilence(),
response: Responses.interrupt(),
},
{
// The handling for these mechanics is similar enough it makes sense to combine the trigger
id: 'Twinning Impact + Pounce',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: ['003[2-5]', '005A'], capture: false }),
suppressSeconds: 10,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Spread (avoid cages)',
de: 'Verteilen (Vermeide "Käfige")',
fr: 'Dispersez-vous (évitez les cages)',
ja: '散開 (檻に近づかない)',
cn: '分散(躲避笼子)',
ko: '산개 (몬스터 우리 피하기)',
},
},
},
{
id: 'Twinning Beastly Roar',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3D64', source: 'Alpha Zaghnal', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3D64', source: 'Alpha-Zaghnal', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3D64', source: 'Zaghnal Alpha', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3D64', source: 'アルファ・ザグナル', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3D64', source: '扎戈斧龙一型', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3D64', source: '알파 자그날', capture: false }),
response: Responses.aoe(),
},
{
id: 'Twinning Augurium',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3D65', source: 'Alpha Zaghnal' }),
netRegexDe: NetRegexes.startsUsing({ id: '3D65', source: 'Alpha-Zaghnal' }),
netRegexFr: NetRegexes.startsUsing({ id: '3D65', source: 'Zaghnal Alpha' }),
netRegexJa: NetRegexes.startsUsing({ id: '3D65', source: 'アルファ・ザグナル' }),
netRegexCn: NetRegexes.startsUsing({ id: '3D65', source: '扎戈斧龙一型' }),
netRegexKo: NetRegexes.startsUsing({ id: '3D65', source: '알파 자그날' }),
response: Responses.tankCleave(),
},
{
id: 'Twinning Charge Eradicated',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '005D' }),
response: Responses.stackMarkerOn(),
},
{
id: 'Twinning Thunder Beam',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3DED', source: 'Mithridates' }),
netRegexDe: NetRegexes.startsUsing({ id: '3DED', source: 'Mithridates' }),
netRegexFr: NetRegexes.startsUsing({ id: '3DED', source: 'Mithridate' }),
netRegexJa: NetRegexes.startsUsing({ id: '3DED', source: 'ミトリダテス' }),
netRegexCn: NetRegexes.startsUsing({ id: '3DED', source: '米特里达梯' }),
netRegexKo: NetRegexes.startsUsing({ id: '3DED', source: '미트리다테스' }),
response: Responses.tankBuster(),
},
{
// Alternatively, we could use 1B:\y{ObjectId}:(\y{Name}):....:....:00A0
id: 'Twinning Allagan Thunder',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3DEF', source: 'Mithridates' }),
netRegexDe: NetRegexes.startsUsing({ id: '3DEF', source: 'Mithridates' }),
netRegexFr: NetRegexes.startsUsing({ id: '3DEF', source: 'Mithridate' }),
netRegexJa: NetRegexes.startsUsing({ id: '3DEF', source: 'ミトリダテス' }),
netRegexCn: NetRegexes.startsUsing({ id: '3DEF', source: '米特里达梯' }),
netRegexKo: NetRegexes.startsUsing({ id: '3DEF', source: '미트리다테스' }),
condition: Conditions.targetIsYou(),
response: Responses.spread(),
},
{
id: 'Twinning Magitek Crossray',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3DF8', source: 'The Tycoon', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3DF8', source: 'Tycoon', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3DF8', source: 'Le Magnat', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3DF8', source: 'タイクーン', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3DF8', source: '泰空', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3DF8', source: '타이쿤', capture: false }),
suppressSeconds: 15,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'cardinal lasers',
de: 'Himmelrichtungs-Lasers',
fr: 'Lasers cardinaux',
ja: '十字レーザー',
cn: '正点激光',
ko: '십자 레이저',
},
},
},
{
id: 'Twinning Defensive Array',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3DF2', source: 'The Tycoon', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3DF2', source: 'Tycoon', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3DF2', source: 'Le Magnat', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3DF2', source: 'タイクーン', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3DF2', source: '泰空', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3DF2', source: '타이쿤', capture: false }),
suppressSeconds: 15,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'outer lasers',
de: 'Lasers am Rand',
fr: 'Lasers extérieurs',
ja: '外周レーザー',
cn: '外侧激光',
ko: '외곽 레이저',
},
},
},
{
id: 'Twinning Rail Cannon',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3DFB', source: 'The Tycoon' }),
netRegexDe: NetRegexes.startsUsing({ id: '3DFB', source: 'Tycoon' }),
netRegexFr: NetRegexes.startsUsing({ id: '3DFB', source: 'Le Magnat' }),
netRegexJa: NetRegexes.startsUsing({ id: '3DFB', source: 'タイクーン' }),
netRegexCn: NetRegexes.startsUsing({ id: '3DFB', source: '泰空' }),
netRegexKo: NetRegexes.startsUsing({ id: '3DFB', source: '타이쿤' }),
response: Responses.tankBuster(),
},
{
// An alternative is 1B:\y{ObjectId}:\y{Name}:....:....:00A9
id: 'Twinning Magicrystal',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3E0C', source: 'The Tycoon', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3E0C', source: 'Tycoon', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3E0C', source: 'Le Magnat', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3E0C', source: 'タイクーン', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3E0C', source: '泰空', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3E0C', source: '타이쿤', capture: false }),
response: Responses.spread('alert'),
},
{
id: 'Twinning Discharger',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '3DFC', source: 'The Tycoon', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '3DFC', source: 'Tycoon', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '3DFC', source: 'Le Magnat', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '3DFC', source: 'タイクーン', capture: false }),
netRegexCn: NetRegexes.startsUsing({ id: '3DFC', source: '泰空', capture: false }),
netRegexKo: NetRegexes.startsUsing({ id: '3DFC', source: '타이쿤', capture: false }),
response: Responses.aoe(),
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'vitalized reptoid': 'gestärkt(?:e|er|es|en) Reptoid',
'The Tycoon': 'Tycoon',
'surplus Kaliya': 'massengefertigt(?:e|er|es|en) Kaliya',
'Alpha Zaghnal': 'Alpha-Zaghnal',
'(?<! )Zaghnal': 'Zaghnal',
'Servomechanical Minotaur': 'Servomechanisch(?:e|er|es|en) Minotaurus',
'Mithridates': 'Mithridates',
'Levinball': 'Donnerkugel',
'The Cornice': 'Schnittstelle',
'Aetherial Observation': 'Ätherobservationsdeck',
'Repurposing': 'Umrüstanlage',
'Cladoselache': 'Cladoselache',
},
'replaceText': {
'Thunder Beam': 'Gewitterstrahl',
'Temporal Paradox': 'Zeitparadox',
'Temporal Flow': 'Zeitfluss',
'Shock': 'Entladung',
'Shattered Crystal': 'Berstender Kristall',
'Rail Cannon': 'Magnetschienenkanone',
'Pounce Errant': 'Tobende Tatze',
'Magitek Ray': 'Magitek-Laser',
'Magitek Crossray': 'Magitek-Kreuzlaser',
'Magicrystal': 'Magitek-Kristall',
'Laserblade': 'Laserklingen',
'High-Tension Discharger': 'Hochspannungsentlader',
'High Gravity': 'Hohe Gravitation',
'Forlorn Impact': 'Einsamer Einschlag',
'Electric Discharge': 'Elektrische Entladung',
'Defensive Array': 'Magitek-Schutzlaser',
'Charge Eradicated': 'Ausrottung',
'Beastly Roar': 'Bestialisches Brüllen',
'Beast Rampant': 'Ungezügelt',
'Beast Passant': 'Stahlpranke',
'Augurium': 'Schmetterbohrer',
'Artificial Gravity': 'Künstliche Gravitation',
'Allagan Thunder': 'Allagischer Blitzschlag',
'(?<! )Gravity': 'Gravitation',
'(?<! )Crossray': 'Kreuzlaser',
},
},
{
'locale': 'fr',
'replaceSync': {
'vitalized reptoid': 'Reptoïde vitalisé',
'The Tycoon': 'Le Magnat',
'surplus Kaliya': 'Kaliya de surplus',
'alpha zaghnal': 'Zaghnal alpha',
'Servomechanical Minotaur': 'Minotaure Servomécanique',
'Mithridates': 'Mithridate',
'Levinball': 'boule foudroyante',
'The Cornice': 'Cœur du propulseur dimensionnel',
'Aetherial Observation': 'Observatoire des flux éthérés',
'Repurposing': 'Atelier d\'opti-rénovation',
'Cladoselache': 'Cladoselache',
},
'replaceText': {
'Thunder Beam': 'Rayon de foudre',
'Temporal Paradox': 'Paradoxe temporel',
'Temporal Flow': 'Flux temporel',
'Shock': 'Décharge électrostatique',
'Shattered Crystal': 'Éclatement de cristal',
'Rail Cannon': 'Canon électrique',
'Pounce Errant': 'Attaque subite XXX',
'Magitek Ray': 'Rayon magitek',
'Magitek Crossray': 'Rayon croisé magitek',
'Magicrystal': 'Cristal magitek',
'Laserblade': 'Lame laser',
'High-Tension Discharger': 'Déchargeur haute tension',
'High Gravity': 'Haute gravité',
'(?<! )Gravity/(?! )Crossray\\?\\?': 'Gravité/Rayon ??',
'Forlorn Impact': 'Déflagration affligeante',
'Electric Discharge': 'Décharge électrique',
'Defensive Array': 'Rayon protecteur magitek',
'Charge Eradicated': 'Éradicateur',
'Beastly Roar': 'Rugissement bestial',
'Beast Rampant': 'Rampant',
'Beast Passant': 'Passant',
'Augurium': 'Coup de tarière',
'Artificial Gravity': 'Gravité artificielle',
'Allagan Thunder': 'Foudre d\'Allag',
},
},
{
'locale': 'ja',
'replaceSync': {
'vitalized reptoid': 'ヴァイタライズ・レプトイド',
'The Tycoon': 'タイクーン',
'surplus Kaliya': '量産型カーリア',
'alpha zaghnal': 'アルファ・ザグナル',
'Servomechanical Minotaur': 'サーヴォ・ミノタウロス',
'Mithridates': 'ミトリダテス',
'Levinball': '雷弾',
'The Cornice': '次元潜行装置中枢',
'Aetherial Observation': 'エーテル観測台',
'Repurposing': '改装作業拠点',
'Cladoselache': 'クラドセラケ',
},
'replaceText': {
'Thunder Beam': 'サンダービーム',
'Temporal Paradox': 'タイムパラドックス',
'Temporal Flow': '時間解凍',
'Shock': '放電',
'Shattered Crystal': 'クリスタル破裂',
'Rail Cannon': 'レールキャノン',
'Pounce Errant': 'XXXパウンス',
'Magitek Ray': '魔導レーザー',
'Magitek Crossray': '魔導クロスレーザー',
'Magicrystal': '魔導クリスタル',
'Laserblade': 'レーザーブレード',
'High-Tension Discharger': 'ハイテンション・ディスチャージャー',
'High Gravity': '高重力',
'Forlorn Impact': 'フォローンインパクト',
'Electric Discharge': 'エレクトリック・ディスチャージ',
'Defensive Array': '魔導プロテクティブレーザー',
'Charge Eradicated': 'エラディケイター',
'Beastly Roar': 'ビーストロア',
'Beast Rampant': 'ランパント',
'Beast Passant': 'パッサント',
'Augurium': 'アウガースマッシュ',
'Artificial Gravity': 'アーティフィシャル・グラビティ',
'Allagan Thunder': 'アラガン・サンダー',
'(?<! )Gravity': '(?<! )重力',
'(?<! )Crossray': '(?<! )クロスレイ',
},
},
{
'locale': 'cn',
'replaceSync': {
'vitalized reptoid': '活力化爬虫半人马',
'The Tycoon': '泰空',
'surplus Kaliya': '量产型卡利亚',
'alpha zaghnal': '扎戈斧龙一型',
'Servomechanical Minotaur': '自控化弥诺陶洛斯',
'Mithridates': '米特里达梯',
'Levinball': '雷弹',
'The Cornice': '时空潜行装置中枢',
'Aetherial Observation': '以太观测台',
'Repurposing': '改造据点',
'Cladoselache': '裂口鲨',
},
'replaceText': {
'Thunder Beam': '电光束',
'Temporal Paradox': '时间悖论',
'Temporal Flow': '时间解冻',
'Shock': '放电',
'Shattered Crystal': '水晶破裂',
'Rail Cannon': '轨道炮',
'Pounce Errant': 'XXX突袭',
'Magitek Ray': '魔导激光',
'Magitek Crossray': '魔导交叉激光',
'Magicrystal': '魔导水晶',
'Laserblade': '激光剑',
'High-Tension Discharger': '高压排电',
'High Gravity': '高重力',
'Forlorn Impact': '绝望冲击',
'Electric Discharge': '排电',
'Defensive Array': '魔导防护激光',
'Charge Eradicated': '歼灭弹',
'Beastly Roar': '残虐咆哮',
'Beast Rampant': '人立而起',
'Beast Passant': '四足着地',
'Augurium': '预兆',
'Artificial Gravity': '人造重力',
'Allagan Thunder': '亚拉戈闪雷',
'(?<! )Gravity': '(?<! )重力',
'(?<! )Crossray': '(?<! )交叉激光',
},
},
{
'locale': 'ko',
'replaceSync': {
'vitalized reptoid': '활성된 파충류',
'The Tycoon': '타이쿤',
'surplus Kaliya': '양산형 칼리야',
'alpha zaghnal': '알파 자그날',
'Servomechanical Minotaur': '자동제어 미노타우로스',
'Mithridates': '미트리다테스',
'Levinball': '뇌탄',
'Cladoselache': '클라도셀라케',
'The Cornice': '차원 잠행 장치 중추',
'Aetherial Observation': '에테르 관측대',
'Repurposing': '개조 작업 거점',
},
'replaceText': {
'Thunder Beam': '번개 광선',
'Temporal Paradox': '시간 역설',
'Temporal Flow': '시간 해동',
'Shock': '방전',
'Shattered Crystal': '크리스탈 파열',
'Rail Cannon': '전자기포',
'Pounce Errant': 'XXX 덮치기',
'Magitek Ray': '마도 레이저',
'Magitek Crossray': '마도 십자 레이저',
'Magicrystal': '마도 크리스탈',
'Laserblade': '레이저 칼날',
'High-Tension Discharger': '고압 전류 방출',
'High Gravity': '고중력',
'Forlorn Impact': '쓸쓸한 충격',
'Electric Discharge': '전류 방출',
'Defensive Array': '마도 방어 레이저',
'Charge Eradicated': '박멸',
'Beastly Roar': '야수의 포효',
'Beast Rampant': '두발걷기',
'Beast Passant': '네발걷기',
'Augurium': '공격 조짐',
'Artificial Gravity': '인공 중력',
'Allagan Thunder': '알라그 선더',
'(?<! )Gravity': '그라비데',
'(?<! )Crossray': '십자 레이저',
},
},
],
};
export default triggerSet; | the_stack |
import { ipcRenderer } from 'electron';
import { delay, SagaIterator } from 'redux-saga';
import { all, call, getContext, put, race, select, spawn, take } from 'redux-saga/effects';
import { BrowserXAppWorker } from '../../app-worker';
import { MAIN_APP_READY } from '../../app/duck';
import { getFocusedTabId } from '../../app/selectors';
import { isAlwaysLoaded } from '../../application-settings/api';
import { getApplicationsSettings } from '../../application-settings/selectors';
import { ApplicationsSettingsImmutable } from '../../application-settings/types';
import { getAllManifests } from '../../applications/api';
import { navigateToApplicationTabAutomatically } from '../../applications/duck';
import { getApplicationId } from '../../applications/get';
import { BxAppManifest } from '../../applications/manifest-provider/bxAppManifest';
import { getApplicationsByManifestURLs, getInstalledManifestURLs } from '../../applications/selectors';
import { ApplicationsImmutable } from '../../applications/types';
import { getFrontActiveTabId } from '../../applications/utils';
import { MARK_AS_DONE } from '../../onboarding/duck';
import { isDone } from '../../onboarding/selectors';
import { closeTab, updateBackForwardState, updateLastActivity, updateTabURL } from '../../tabs/duck';
import { getTabApplicationId, getTabId } from '../../tabs/get';
import { getTabs } from '../../tabs/selectors';
import { StationTabsImmutable } from '../../tabs/types';
import {
callService,
createWebContentsServiceObserverChannel,
takeEveryWitness,
takeLatestWitness,
serviceAddObserverChannel,
} from '../../utils/sagas';
import SubWindowManager from '../../windows/utils/SubWindowManager';
import {
ATTACH_WEBCONTENTS_TO_TAB,
CHANGE_HASH_AND_NAVIGATE_TO_TAB,
ChangeHashAndNavigateToTabAction,
CloseAfterReattachedOrTimeoutAction,
doAttach,
domReady,
DomReadyAction,
EXECUTE_WEBVIEW_METHOD_FOR_CURRENT_TAB,
executeWebviewMethod,
ExecuteWebviewMethodForCurrentTabAction,
FRONT_ACTIVE_TAB_CHANGE,
FrontActiveTabChangeAction,
NAVIGATE_TAB_TO_URL,
NavigateTabToURLAction,
NEW_WEBCONTENTS_ATTACHED_TO_TAB,
newWebcontentsAttachedToTab,
NewWebcontentsAttachedToTabAction,
RACE_CLOSE,
removeWebcontents,
} from '../duck';
import {
getTabWebcontents,
getTabWebcontentsByWebContentsId,
getWebcontentsCrashed,
getWebcontentsId,
getWebcontentsIdForTabId,
getWebcontentsTabId,
} from '../selectors';
import sleepingSagas from './sleeping';
import closeCurrentTabSagas from './close-current-tab';
import ms = require('ms');
import { ContextMenuService } from '../../services/services/menu/interface';
import services from '../../services/servicesManager';
let seenWebcontents = new Set();
function* reloadTabIfCrashed(action: FrontActiveTabChangeAction): SagaIterator {
const targetWebcontents = yield select(getTabWebcontents);
const { tabId } = action;
if (!tabId || !targetWebcontents.get(tabId)) return;
const twc = targetWebcontents.get(tabId);
if (getWebcontentsCrashed(twc)) yield put(executeWebviewMethod(tabId, 'reload'));
}
function* interceptPrint({ webcontentsId, tabId }: NewWebcontentsAttachedToTabAction): SagaIterator {
let waitingForPrint = false;
const printChannel = createWebContentsServiceObserverChannel(
webcontentsId, 'addPrintObserver', 'onPrint', 'intercept-print');
// Listen for print events
yield takeEveryWitness(printChannel, function* handle() {
const currentActiveTabId = yield select(getFrontActiveTabId);
if (currentActiveTabId === tabId) {
// If print is called on current active tab, show print modal...
// delay is a workaround for https://github.com/electron/electron/issues/16792
yield call(delay, 500);
yield callService('tabWebContents', 'print', webcontentsId);
} else {
// ... else, add it to print queue.
waitingForPrint = true;
}
});
// Listen for active tab change events
yield takeLatestWitness(FRONT_ACTIVE_TAB_CHANGE, function* handle(action: FrontActiveTabChangeAction) {
// When active tab is changed, if the new active tab is in the print queue,
// trigger the print modal.
if (waitingForPrint && action.tabId === tabId) {
waitingForPrint = false;
const wcId = yield select(getWebcontentsIdForTabId, action.tabId);
yield callService('tabWebContents', 'print', wcId);
}
});
}
function* interceptDestroyedEvents({ webcontentsId, tabId }: NewWebcontentsAttachedToTabAction): SagaIterator {
const destroyedChannel = createWebContentsServiceObserverChannel(
webcontentsId, 'addLifeCycleObserver', 'onDestroyed', 'intercept-destroyed');
yield takeEveryWitness(destroyedChannel, function* () {
const twc = yield select(getTabWebcontentsByWebContentsId, webcontentsId);
// only clear tabWebcontents if the tabIb have not been reattached
if (twc && getWebcontentsTabId(twc) === tabId) {
yield put(removeWebcontents(tabId));
}
});
}
function* interceptCloseEvents({ webcontentsId, tabId }: NewWebcontentsAttachedToTabAction): SagaIterator {
const nextCloseEvent = createWebContentsServiceObserverChannel(
webcontentsId, 'addLifeCycleObserver', 'onClose', 'intercept-close');
while (true) {
yield take(nextCloseEvent);
yield put(closeTab(tabId));
}
}
function* watchForNewWebContents({ tabId, webcontentsId }: NewWebcontentsAttachedToTabAction): SagaIterator {
if (!seenWebcontents.has(webcontentsId)) {
yield put(newWebcontentsAttachedToTab(tabId, webcontentsId));
seenWebcontents = seenWebcontents.add(webcontentsId);
}
}
function* interceptWebcontentsReady({ webcontentsId, tabId }: DomReadyAction) {
const domReadyEventChannel = createWebContentsServiceObserverChannel(
webcontentsId, 'addLifeCycleObserver', 'onDomReady', 'intercept-ready');
yield takeEveryWitness(domReadyEventChannel, function* handle() {
yield put(domReady(webcontentsId, tabId));
});
}
function* interceptNavigateEvents({ webcontentsId, tabId }: NewWebcontentsAttachedToTabAction): SagaIterator {
const navigationEventChannel = createWebContentsServiceObserverChannel(
webcontentsId, 'addLifeCycleObserver', 'onNavigate', 'intercept-nav');
yield takeEveryWitness(navigationEventChannel,
function* navigationEventChannelCallback({ canGoBack, canGoForward }: { canGoBack: boolean, canGoForward: boolean }) {
yield put(updateBackForwardState(tabId, canGoBack, canGoForward));
}
);
}
function* closeSubwindowIfReattachedOrTimeout({ tabId }: CloseAfterReattachedOrTimeoutAction): SagaIterator {
yield race({
reattach: take((action: any) =>
action.type === ATTACH_WEBCONTENTS_TO_TAB && action.tabId === tabId),
timeout: call(delay, 5000),
});
yield call([SubWindowManager, SubWindowManager.close], tabId);
}
function* getTabsToLoadOnStartup() {
const bxApp: BrowserXAppWorker = yield getContext('bxApp');
const manifestURLs = yield select(getInstalledManifestURLs);
const manifests: Map<string, BxAppManifest> = yield call(getAllManifests, bxApp, manifestURLs);
const appSettings: ApplicationsSettingsImmutable = yield select(getApplicationsSettings);
const alwaysLoadedManifests = Array.from(manifests.entries())
.filter(([manifestURL, manifest]) => isAlwaysLoaded(manifest, appSettings.get(manifestURL)))
.map(([manifestURL]) => manifestURL);
const applicationsToLoad: ApplicationsImmutable = yield select(
getApplicationsByManifestURLs,
alwaysLoadedManifests
);
const applicationIds = applicationsToLoad.map(getApplicationId);
const tabs: StationTabsImmutable = yield select(getTabs);
return tabs.filter(tab => {
const applicationId = getTabApplicationId(tab);
return applicationIds.includes(applicationId);
});
}
function* startProgressiveWarmup() {
const isOnboardingDone = yield select(isDone);
if (!isOnboardingDone) {
yield take((action: any) => action.type === MARK_AS_DONE && action.done);
}
const tabsToLoad = yield call(getTabsToLoadOnStartup);
const tabId1 = yield select(getFrontActiveTabId);
yield put(doAttach(tabId1));
yield takeEveryWitness(FRONT_ACTIVE_TAB_CHANGE, function* ({ tabId }: FrontActiveTabChangeAction) {
yield put(doAttach(tabId));
});
// wait for the first tab to load correctly
yield call(delay, ms('15sec'));
for (const tab of tabsToLoad.values()) {
yield put(doAttach(getTabId(tab)));
yield call(delay, ms('4sec'));
}
}
function* setTabActivityDebounced({ tabId }: FrontActiveTabChangeAction) {
const now = yield call(Date.now);
// FRONT_ACTIVE_TAB_CHANGE can be triggered 2 times quickly
// when switching from tab 1 in app A to tab 2 in app B
// we debounce and take only last one
yield call(delay, 100);
yield put(updateLastActivity(tabId, now));
}
function* pushUrlOnTabWebcontentsThenNavigate({ tabId, url }: ChangeHashAndNavigateToTabAction): SagaIterator {
const twcs = yield select(getTabWebcontents);
const twc = twcs.get(tabId);
if (!twc) {
// webContents not loaded, so we can just update the tab's URL, then it will load when we'll navigate to it
yield put(updateTabURL(tabId, url));
} else {
// new url differs only from hash
const code = `
document.location.href = '${url.replace('\'', '\\\'')}';
`;
yield callService('tabWebContents', 'executeJavaScript', getWebcontentsId(twc), code);
}
yield put(navigateToApplicationTabAutomatically(tabId));
}
function* loadURLOnTabWebcontents({ tabId, url }: NavigateTabToURLAction): SagaIterator {
/*
* When a NavigateTabToURLAction is dispatched, corresponding tab URL should be updated
* it's necessessary to update URL here because `handleDidNavigate` (in Application.js) does not handle all the cases
*/
yield put(updateTabURL(tabId, url));
const twcs = yield select(getTabWebcontents);
const twc = twcs.get(tabId);
if (!twc) return;
try {
yield callService('tabWebContents', 'loadURL', getWebcontentsId(twc), url);
} catch (e) {
console.warn(e);
}
}
function* sagaExecuteWebviewMethodForCurrentTab({ method }: ExecuteWebviewMethodForCurrentTabAction): SagaIterator {
const tabId = yield select(getFocusedTabId);
if (!tabId) return;
yield put(executeWebviewMethod(tabId, method));
}
function* interceptAutofill({ webcontentsId }: { webcontentsId: number }) {
const autofillMenu: ContextMenuService = yield callService('contextMenu', 'create', { webcontentsId });
// const popupChannel = serviceAddObserverChannel(autofillMenu, 'onAskAutofillPopup', 'autofill-popup-asked');
const clickChannel = serviceAddObserverChannel(autofillMenu, 'onClickItem', 'autofill-popup-value-selected');
yield takeEveryWitness(clickChannel, function* handle({ action, args }: any) {
if (args.length > 0) ipcRenderer.sendTo(webcontentsId, action, args[0]);
});
// yield takeEveryWitness(popupChannel, function* handle(rect: any) {
// const email = yield select(getUserEmail);
// if (email) yield autofillMenu.popupAutofill({ emails: [email], rect });
// });
}
export default function* main() {
yield all([
takeEveryWitness(MAIN_APP_READY, startProgressiveWarmup),
takeEveryWitness(FRONT_ACTIVE_TAB_CHANGE, reloadTabIfCrashed),
// takeLatestWitness + delay => debounce
takeLatestWitness(FRONT_ACTIVE_TAB_CHANGE, setTabActivityDebounced),
takeEveryWitness(ATTACH_WEBCONTENTS_TO_TAB, watchForNewWebContents),
takeEveryWitness(ATTACH_WEBCONTENTS_TO_TAB, interceptAutofill),
takeEveryWitness(NEW_WEBCONTENTS_ATTACHED_TO_TAB, interceptCloseEvents),
takeEveryWitness(NEW_WEBCONTENTS_ATTACHED_TO_TAB, interceptDestroyedEvents),
takeEveryWitness(NEW_WEBCONTENTS_ATTACHED_TO_TAB, interceptNavigateEvents),
takeEveryWitness(NEW_WEBCONTENTS_ATTACHED_TO_TAB, interceptWebcontentsReady),
takeEveryWitness(NEW_WEBCONTENTS_ATTACHED_TO_TAB, interceptPrint),
takeEveryWitness(NAVIGATE_TAB_TO_URL, loadURLOnTabWebcontents),
takeEveryWitness(CHANGE_HASH_AND_NAVIGATE_TO_TAB, pushUrlOnTabWebcontentsThenNavigate),
takeEveryWitness(RACE_CLOSE, closeSubwindowIfReattachedOrTimeout),
takeEveryWitness(EXECUTE_WEBVIEW_METHOD_FOR_CURRENT_TAB, sagaExecuteWebviewMethodForCurrentTab),
spawn(sleepingSagas),
spawn(closeCurrentTabSagas),
]);
} | the_stack |
* @packageDocumentation
* @module core/math
*/
import { CCClass } from '../data/class';
import { ValueType } from '../value-types/value-type';
import { Mat4 } from './mat4';
import { IMat4Like, IQuatLike, IVec4Like } from './type-define';
import { clamp, EPSILON, random } from './utils';
import { legacyCC } from '../global-exports';
/**
* @en Representation of four-dimensional vectors.
* @zh 四维向量。
*/
export class Vec4 extends ValueType {
public static ZERO = Object.freeze(new Vec4(0, 0, 0, 0));
public static ONE = Object.freeze(new Vec4(1, 1, 1, 1));
public static NEG_ONE = Object.freeze(new Vec4(-1, -1, -1, -1));
/**
* @en Obtains a clone of the given vector object
* @zh 获得指定向量的拷贝
*/
public static clone <Out extends IVec4Like> (a: Out) {
return new Vec4(a.x, a.y, a.z, a.w);
}
/**
* @en Copy the target vector and save the results to out vector object
* @zh 复制目标向量
*/
public static copy <Out extends IVec4Like> (out: Out, a: Out) {
out.x = a.x;
out.y = a.y;
out.z = a.z;
out.w = a.w;
return out;
}
/**
* @en Sets the out vector with the given x, y, z and w values
* @zh 设置向量值
*/
public static set <Out extends IVec4Like> (out: Out, x: number, y: number, z: number, w: number) {
out.x = x;
out.y = y;
out.z = z;
out.w = w;
return out;
}
/**
* @en Element-wise vector addition and save the results to out vector object
* @zh 逐元素向量加法
*/
public static add <Out extends IVec4Like> (out: Out, a: Out, b: Out) {
out.x = a.x + b.x;
out.y = a.y + b.y;
out.z = a.z + b.z;
out.w = a.w + b.w;
return out;
}
/**
* @en Element-wise vector subtraction and save the results to out vector object
* @zh 逐元素向量减法
*/
public static subtract <Out extends IVec4Like> (out: Out, a: Out, b: Out) {
out.x = a.x - b.x;
out.y = a.y - b.y;
out.z = a.z - b.z;
out.w = a.w - b.w;
return out;
}
/**
* @en Element-wise vector multiplication and save the results to out vector object
* @zh 逐元素向量乘法
*/
public static multiply <Out extends IVec4Like> (out: Out, a: Out, b: Out) {
out.x = a.x * b.x;
out.y = a.y * b.y;
out.z = a.z * b.z;
out.w = a.w * b.w;
return out;
}
/**
* @en Element-wise vector division and save the results to out vector object
* @zh 逐元素向量除法
*/
public static divide <Out extends IVec4Like> (out: Out, a: Out, b: Out) {
out.x = a.x / b.x;
out.y = a.y / b.y;
out.z = a.z / b.z;
out.w = a.w / b.w;
return out;
}
/**
* @en Rounds up by elements of the vector and save the results to out vector object
* @zh 逐元素向量向上取整
*/
public static ceil <Out extends IVec4Like> (out: Out, a: Out) {
out.x = Math.ceil(a.x);
out.y = Math.ceil(a.y);
out.z = Math.ceil(a.z);
out.w = Math.ceil(a.w);
return out;
}
/**
* @en Element-wise rounds down of the current vector and save the results to the out vector
* @zh 逐元素向量向下取整
*/
public static floor <Out extends IVec4Like> (out: Out, a: Out) {
out.x = Math.floor(a.x);
out.y = Math.floor(a.y);
out.z = Math.floor(a.z);
out.w = Math.floor(a.w);
return out;
}
/**
* @en Calculates the minimum values by elements of the vector and save the results to the out vector
* @zh 逐元素向量最小值
*/
public static min <Out extends IVec4Like> (out: Out, a: Out, b: Out) {
out.x = Math.min(a.x, b.x);
out.y = Math.min(a.y, b.y);
out.z = Math.min(a.z, b.z);
out.w = Math.min(a.w, b.w);
return out;
}
/**
* @en Calculates the maximum values by elements of the vector and save the results to the out vector
* @zh 逐元素向量最大值
*/
public static max <Out extends IVec4Like> (out: Out, a: Out, b: Out) {
out.x = Math.max(a.x, b.x);
out.y = Math.max(a.y, b.y);
out.z = Math.max(a.z, b.z);
out.w = Math.max(a.w, b.w);
return out;
}
/**
* @en Calculates element-wise round results and save to the out vector
* @zh 逐元素向量四舍五入取整
*/
public static round <Out extends IVec4Like> (out: Out, a: Out) {
out.x = Math.round(a.x);
out.y = Math.round(a.y);
out.z = Math.round(a.z);
out.w = Math.round(a.w);
return out;
}
/**
* @en Vector scalar multiplication and save the results to out vector object
* @zh 向量标量乘法
*/
public static multiplyScalar <Out extends IVec4Like> (out: Out, a: Out, b: number) {
out.x = a.x * b;
out.y = a.y * b;
out.z = a.z * b;
out.w = a.w * b;
return out;
}
/**
* @en Element-wise multiplication and addition with the equation: a + b * scale
* @zh 逐元素向量乘加: A + B * scale
*/
public static scaleAndAdd <Out extends IVec4Like> (out: Out, a: Out, b: Out, scale: number) {
out.x = a.x + (b.x * scale);
out.y = a.y + (b.y * scale);
out.z = a.z + (b.z * scale);
out.w = a.w + (b.w * scale);
return out;
}
/**
* @en Calculates the euclidean distance of two vectors
* @zh 求两向量的欧氏距离
*/
public static distance <Out extends IVec4Like> (a: Out, b: Out) {
const x = b.x - a.x;
const y = b.y - a.y;
const z = b.z - a.z;
const w = b.w - a.w;
return Math.sqrt(x * x + y * y + z * z + w * w);
}
/**
* @en Calculates the squared euclidean distance of two vectors
* @zh 求两向量的欧氏距离平方
*/
public static squaredDistance <Out extends IVec4Like> (a: Out, b: Out) {
const x = b.x - a.x;
const y = b.y - a.y;
const z = b.z - a.z;
const w = b.w - a.w;
return x * x + y * y + z * z + w * w;
}
/**
* @en Calculates the length of the vector
* @zh 求向量长度
*/
public static len <Out extends IVec4Like> (a: Out) {
const x = a.x;
const y = a.y;
const z = a.z;
const w = a.w;
return Math.sqrt(x * x + y * y + z * z + w * w);
}
/**
* @en Calculates the squared length of the vector
* @zh 求向量长度平方
*/
public static lengthSqr <Out extends IVec4Like> (a: Out) {
const x = a.x;
const y = a.y;
const z = a.z;
const w = a.w;
return x * x + y * y + z * z + w * w;
}
/**
* @en Sets each element to its negative value
* @zh 逐元素向量取负
*/
public static negate <Out extends IVec4Like> (out: Out, a: Out) {
out.x = -a.x;
out.y = -a.y;
out.z = -a.z;
out.w = -a.w;
return out;
}
/**
* @en Sets each element to its inverse value, zero value will become Infinity
* @zh 逐元素向量取倒数,接近 0 时返回 Infinity
*/
public static inverse <Out extends IVec4Like> (out: Out, a: Out) {
out.x = 1.0 / a.x;
out.y = 1.0 / a.y;
out.z = 1.0 / a.z;
out.w = 1.0 / a.w;
return out;
}
/**
* @en Sets each element to its inverse value, zero value will remain zero
* @zh 逐元素向量取倒数,接近 0 时返回 0
*/
public static inverseSafe <Out extends IVec4Like> (out: Out, a: Out) {
const x = a.x;
const y = a.y;
const z = a.z;
const w = a.w;
if (Math.abs(x) < EPSILON) {
out.x = 0;
} else {
out.x = 1.0 / x;
}
if (Math.abs(y) < EPSILON) {
out.y = 0;
} else {
out.y = 1.0 / y;
}
if (Math.abs(z) < EPSILON) {
out.z = 0;
} else {
out.z = 1.0 / z;
}
if (Math.abs(w) < EPSILON) {
out.w = 0;
} else {
out.w = 1.0 / w;
}
return out;
}
/**
* @en Sets the normalized vector to the out vector
* @zh 归一化向量
*/
public static normalize <Out extends IVec4Like> (out: Out, a: Out) {
const x = a.x;
const y = a.y;
const z = a.z;
const w = a.w;
let len = x * x + y * y + z * z + w * w;
if (len > 0) {
len = 1 / Math.sqrt(len);
out.x = x * len;
out.y = y * len;
out.z = z * len;
out.w = w * len;
}
return out;
}
/**
* @en Calculates the dot product of the vector
* @zh 向量点积(数量积)
*/
public static dot <Out extends IVec4Like> (a: Out, b: Out) {
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
/**
* @en Calculates the linear interpolation between two vectors with a given ratio
* @zh 逐元素向量线性插值: A + t * (B - A)
*/
public static lerp <Out extends IVec4Like> (out: Out, a: Out, b: Out, t: number) {
out.x = a.x + t * (b.x - a.x);
out.y = a.y + t * (b.y - a.y);
out.z = a.z + t * (b.z - a.z);
out.w = a.w + t * (b.w - a.w);
return out;
}
/**
* @en Generates a uniformly distributed random vector points from center to the surface of the unit sphere
* @zh 生成一个在单位球体上均匀分布的随机向量
* @param scale vector length
*/
public static random <Out extends IVec4Like> (out: Out, scale?: number) {
scale = scale || 1.0;
const phi = random() * 2.0 * Math.PI;
const cosTheta = random() * 2 - 1;
const sinTheta = Math.sqrt(1 - cosTheta * cosTheta);
out.x = sinTheta * Math.cos(phi) * scale;
out.y = sinTheta * Math.sin(phi) * scale;
out.z = cosTheta * scale;
out.w = 0;
return out;
}
/**
* @en Vector and fourth order matrix multiplication
* @zh 向量与四维矩阵乘法
*/
public static transformMat4 <Out extends IVec4Like, MatLike extends IMat4Like> (out: Out, a: Out, m: MatLike) {
const x = a.x;
const y = a.y;
const z = a.z;
const w = a.w;
out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12 * w;
out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13 * w;
out.z = m.m02 * x + m.m06 * y + m.m10 * z + m.m14 * w;
out.w = m.m03 * x + m.m07 * y + m.m11 * z + m.m15 * w;
return out;
}
/**
* @en Transform the vector with the given affine transformation
* @zh 向量仿射变换
*/
public static transformAffine<Out extends IVec4Like, VecLike extends IVec4Like, MatLike extends IMat4Like>
(out: Out, v: VecLike, m: MatLike) {
const x = v.x;
const y = v.y;
const z = v.z;
const w = v.w;
out.x = m.m00 * x + m.m01 * y + m.m02 * z + m.m03 * w;
out.y = m.m04 * x + m.m05 * y + m.m06 * z + m.m07 * w;
out.x = m.m08 * x + m.m09 * y + m.m10 * z + m.m11 * w;
out.w = v.w;
return out;
}
/**
* @en Vector quaternion multiplication
* @zh 向量四元数乘法
*/
public static transformQuat <Out extends IVec4Like, QuatLike extends IQuatLike> (out: Out, a: Out, q: QuatLike) {
const { x, y, z } = a;
const _x = q.x;
const _y = q.y;
const _z = q.z;
const _w = q.w;
// calculate quat * vec
const ix = _w * x + _y * z - _z * y;
const iy = _w * y + _z * x - _x * z;
const iz = _w * z + _x * y - _y * x;
const iw = -_x * x - _y * y - _z * z;
// calculate result * inverse quat
out.x = ix * _w + iw * -_x + iy * -_z - iz * -_y;
out.y = iy * _w + iw * -_y + iz * -_x - ix * -_z;
out.z = iz * _w + iw * -_z + ix * -_y - iy * -_x;
out.w = a.w;
return out;
}
/**
* @en Converts the given vector to an array
* @zh 向量转数组
* @param ofs Array Start Offset
*/
public static toArray <Out extends IWritableArrayLike<number>> (out: Out, v: IVec4Like, ofs = 0) {
out[ofs + 0] = v.x;
out[ofs + 1] = v.y;
out[ofs + 2] = v.z;
out[ofs + 3] = v.w;
return out;
}
/**
* @en Converts the given array to a vector
* @zh 数组转向量
* @param ofs Array Start Offset
*/
public static fromArray <Out extends IVec4Like> (out: Out, arr: IWritableArrayLike<number>, ofs = 0) {
out.x = arr[ofs + 0];
out.y = arr[ofs + 1];
out.z = arr[ofs + 2];
out.w = arr[ofs + 3];
return out;
}
/**
* @en Check the equality of the two given vectors
* @zh 向量等价判断
*/
public static strictEquals <Out extends IVec4Like> (a: Out, b: Out) {
return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w;
}
/**
* @en Check whether the two given vectors are approximately equivalent
* @zh 排除浮点数误差的向量近似等价判断
*/
public static equals <Out extends IVec4Like> (a: Out, b: Out, epsilon = EPSILON) {
return (Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x))
&& Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y))
&& Math.abs(a.z - b.z) <= epsilon * Math.max(1.0, Math.abs(a.z), Math.abs(b.z))
&& Math.abs(a.w - b.w) <= epsilon * Math.max(1.0, Math.abs(a.w), Math.abs(b.w)));
}
/**
* @en x component.
* @zh x 分量。
*/
public declare x: number;
/**
* @en y component.
* @zh y 分量。
*/
public declare y: number;
/**
* @en z component.
* @zh z 分量。
*/
public declare z: number;
/**
* @en w component.
* @zh w 分量。
*/
public declare w: number;
constructor (other: Vec4);
constructor (x?: number, y?: number, z?: number, w?: number);
constructor (x?: number | Vec4, y?: number, z?: number, w?: number) {
super();
if (x && typeof x === 'object') {
this.x = x.x;
this.y = x.y;
this.z = x.z;
this.w = x.w;
} else {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
this.w = w || 0;
}
}
/**
* @en clone the current Vec4 value.
* @zh 克隆当前向量。
*/
public clone () {
return new Vec4(this.x, this.y, this.z, this.w);
}
/**
* @en Set the current vector value with the given vector.
* @zh 设置当前向量使其与指定向量相等。
* @param other Specified vector
* @returns `this`
*/
public set (other: Vec4);
/**
* @en Set the value of each component of the current vector.
* @zh 设置当前向量的具体分量值。
* @param x x value
* @param y y value
* @param z z value
* @param w w value
* @returns `this`
*/
public set (x?: number, y?: number, z?: number, w?: number);
public set (x?: number | Vec4, y?: number, z?: number, w?: number) {
if (x && typeof x === 'object') {
this.x = x.x;
this.y = x.y;
this.z = x.z;
this.w = x.w;
} else {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
this.w = w || 0;
}
return this;
}
/**
* @en Check whether the vector approximately equals another one.
* @zh 判断当前向量是否在误差范围内与指定向量相等。
* @param other Specified vector
* @param epsilon The error allowed. It`s should be a non-negative number.
* @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`.
*/
public equals (other: Vec4, epsilon = EPSILON) {
return (Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x))
&& Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y))
&& Math.abs(this.z - other.z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(other.z))
&& Math.abs(this.w - other.w) <= epsilon * Math.max(1.0, Math.abs(this.w), Math.abs(other.w)));
}
/**
* @en Check whether the vector approximately equals another one.
* @zh 判断当前向量是否在误差范围内与指定分量的向量相等。
* @param x The x value of specified vector
* @param y The y value of specified vector
* @param z The z value of specified vector
* @param w The w value of specified vector
* @param epsilon The error allowed. It`s should be a non-negative number.
* @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`.
*/
public equals4f (x: number, y: number, z: number, w: number, epsilon = EPSILON) {
return (Math.abs(this.x - x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(x))
&& Math.abs(this.y - y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(y))
&& Math.abs(this.z - z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(z))
&& Math.abs(this.w - w) <= epsilon * Math.max(1.0, Math.abs(this.w), Math.abs(w)));
}
/**
* @en Check whether the current vector strictly equals another Vec4.
* @zh 判断当前向量是否与指定向量相等。
* @param other specified vector
* @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`.
*/
public strictEquals (other: Vec4) {
return this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w;
}
/**
* @en Check whether the current vector strictly equals another Vec4.
* @zh 判断当前向量是否与指定分量的向量相等。
* @param x The x value of specified vector
* @param y The y value of specified vector
* @param z The z value of specified vector
* @param w The w value of specified vector
* @returns Returns `true` when the components of both vectors are equal within the specified range of error; otherwise it returns `false`.
*/
public strictEquals4f (x: number, y: number, z: number, w: number) {
return this.x === x && this.y === y && this.z === z && this.w === w;
}
/**
* @en Calculate linear interpolation result between this vector and another one with given ratio.
* @zh 根据指定的插值比率,从当前向量到目标向量之间做插值。
* @param to Target vector
* @param ratio The interpolation coefficient.The range is [0,1].
*/
public lerp (to: Vec4, ratio: number) {
const x = this.x;
const y = this.y;
const z = this.z;
const w = this.w;
this.x = x + ratio * (to.x - x);
this.y = y + ratio * (to.y - y);
this.z = z + ratio * (to.z - z);
this.w = w + ratio * (to.w - w);
return this;
}
/**
* @en Return the information of the vector in string
* @zh 返回当前向量的字符串表示。
* @returns The string with vector information
*/
public toString () {
return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.z.toFixed(2)}, ${this.w.toFixed(2)})`;
}
/**
* @en Clamp the vector between minInclusive and maxInclusive.
* @zh 设置当前向量的值,使其各个分量都处于指定的范围内。
* @param minInclusive Minimum value allowed
* @param maxInclusive Maximum value allowed
* @returns `this`
*/
public clampf (minInclusive: Vec4, maxInclusive: Vec4) {
this.x = clamp(this.x, minInclusive.x, maxInclusive.x);
this.y = clamp(this.y, minInclusive.y, maxInclusive.y);
this.z = clamp(this.z, minInclusive.z, maxInclusive.z);
this.w = clamp(this.w, minInclusive.w, maxInclusive.w);
return this;
}
/**
* @en Adds the current vector with another one and return this
* @zh 向量加法。将当前向量与指定向量的相加
* @param other specified vector
*/
public add (other: Vec4) {
this.x += other.x;
this.y += other.y;
this.z += other.z;
this.w += other.w;
return this;
}
/**
* @en Adds the current vector with another one and return this
* @zh 向量加法。将当前向量与指定分量的向量相加
* @param x The x value of specified vector
* @param y The y value of specified vector
* @param z The z value of specified vector
* @param w The w value of specified vector
*/
public add4f (x: number, y: number, z: number, w: number) {
this.x += x;
this.y += y;
this.z += z;
this.w += w;
return this;
}
/**
* @en Subtracts one vector from this, and returns this.
* @zh 向量减法。将当前向量减去指定向量
* @param other specified vector
*/
public subtract (other: Vec4) {
this.x -= other.x;
this.y -= other.y;
this.z -= other.z;
this.w -= other.w;
return this;
}
/**
* @en Subtracts one vector from this, and returns this.
* @zh 向量减法。将当前向量减去指定分量的向量
* @param x The x value of specified vector
* @param y The y value of specified vector
* @param z The z value of specified vector
* @param w The w value of specified vector
*/
public subtract4f (x: number, y: number, z: number, w: number) {
this.x -= x;
this.y -= y;
this.z -= z;
this.w -= w;
return this;
}
/**
* @en Multiplies the current vector with a number, and returns this.
* @zh 向量数乘。将当前向量数乘指定标量
* @param scalar scalar number
*/
public multiplyScalar (scalar: number) {
if (typeof scalar === 'object') { console.warn('should use Vec4.multiply for vector * vector operation'); }
this.x *= scalar;
this.y *= scalar;
this.z *= scalar;
this.w *= scalar;
return this;
}
/**
* @en Multiplies the current vector with another one and return this
* @zh 向量乘法。将当前向量乘以指定向量
* @param other specified vector
*/
public multiply (other: Vec4) {
if (typeof other !== 'object') { console.warn('should use Vec4.scale for vector * scalar operation'); }
this.x *= other.x;
this.y *= other.y;
this.z *= other.z;
this.w *= other.w;
return this;
}
/**
* @en Multiplies the current vector with another one and return this
* @zh 向量乘法。将当前向量与指定分量的向量相乘的结果赋值给当前向量。
* @param x The x value of specified vector
* @param y The y value of specified vector
* @param z The z value of specified vector
* @param w The w value of specified vector
*/
public multiply4f (x: number, y: number, z: number, w: number) {
this.x *= x;
this.y *= y;
this.z *= z;
this.w *= w;
return this;
}
/**
* @en Element-wisely divides this vector with another one, and return this.
* @zh 向量逐元素相除。将当前向量与指定分量的向量相除的结果赋值给当前向量。
* @param other specified vector
*/
public divide (other: Vec4) {
this.x /= other.x;
this.y /= other.y;
this.z /= other.z;
this.w /= other.w;
return this;
}
/**
* @en Element-wisely divides this vector with another one, and return this.
* @zh 向量逐元素相除。将当前向量与指定分量的向量相除的结果赋值给当前向量。
* @param x The x value of specified vector
* @param y The y value of specified vector
* @param z The z value of specified vector
* @param w The w value of specified vector
*/
public divide4f (x: number, y: number, z: number, w: number) {
this.x /= x;
this.y /= y;
this.z /= z;
this.w /= w;
return this;
}
/**
* @en Sets each component of this vector with its negative value
* @zh 将当前向量的各个分量取反
*/
public negative () {
this.x = -this.x;
this.y = -this.y;
this.z = -this.z;
this.w = -this.w;
return this;
}
/**
* @en Calculates the dot product with another vector
* @zh 向量点乘。
* @param other specified vector
* @returns 当前向量与指定向量点乘的结果。
*/
public dot (vector: Vec4) {
return this.x * vector.x + this.y * vector.y + this.z * vector.z + this.w * vector.w;
}
/**
* @en Calculates the cross product with another vector.
* @zh 向量叉乘。视当前向量和指定向量为三维向量(舍弃 w 分量),将当前向量左叉乘指定向量
* @param other specified vector
*/
public cross (vector: Vec4) {
const { x: ax, y: ay, z: az } = this;
const { x: bx, y: by, z: bz } = vector;
this.x = ay * bz - az * by;
this.y = az * bx - ax * bz;
this.z = ax * by - ay * bx;
return this;
}
/**
* @en Returns the length of this vector.
* @zh 计算向量的长度(模)。
* @returns Length of vector
*/
public length () {
const x = this.x;
const y = this.y;
const z = this.z;
const w = this.w;
return Math.sqrt(x * x + y * y + z * z + w * w);
}
/**
* @en Returns the squared length of this vector.
* @zh 计算向量长度(模)的平方。
* @returns the squared length of this vector
*/
public lengthSqr () {
const x = this.x;
const y = this.y;
const z = this.z;
const w = this.w;
return x * x + y * y + z * z + w * w;
}
/**
* @en Normalize the current vector.
* @zh 将当前向量归一化
*/
public normalize () {
const x = this.x;
const y = this.y;
const z = this.z;
const w = this.w;
let len = x * x + y * y + z * z + w * w;
if (len > 0) {
len = 1 / Math.sqrt(len);
this.x = x * len;
this.y = y * len;
this.z = z * len;
this.w = w * len;
}
return this;
}
/**
* @en Transforms the vec4 with a mat4
* @zh 应用四维矩阵变换到当前矩阵
* @param matrix matrix to transform with
*/
public transformMat4 (matrix: Mat4) {
const x = this.x;
const y = this.y;
const z = this.z;
const w = this.w;
this.x = matrix.m00 * x + matrix.m04 * y + matrix.m08 * z + matrix.m12 * w;
this.y = matrix.m01 * x + matrix.m05 * y + matrix.m09 * z + matrix.m13 * w;
this.z = matrix.m02 * x + matrix.m06 * y + matrix.m10 * z + matrix.m14 * w;
this.w = matrix.m03 * x + matrix.m07 * y + matrix.m11 * z + matrix.m15 * w;
return this;
}
}
CCClass.fastDefine('cc.Vec4', Vec4, { x: 0, y: 0, z: 0, w: 0 });
legacyCC.Vec4 = Vec4;
export function v4 (other: Vec4): Vec4;
export function v4 (x?: number, y?: number, z?: number, w?: number): Vec4;
export function v4 (x?: number | Vec4, y?: number, z?: number, w?: number) {
return new Vec4(x as any, y, z, w);
}
legacyCC.v4 = v4; | the_stack |
import {caretPosition, debounce} from '@deckdeckgo/utils';
import configStore from '../stores/config.store';
import containerStore from '../stores/container.store';
import undoRedoStore from '../stores/undo-redo.store';
import {
UndoRedoAddRemoveParagraph,
UndoRedoInput,
UndoRedoSelection,
UndoRedoUpdateParagraph
} from '../types/undo-redo';
import {elementIndex, nodeDepths, toHTMLElement} from '../utils/node.utils';
import {findParagraph} from '../utils/paragraph.utils';
import {
filterAttributesMutations,
findAddedNodesParagraphs,
findAddedParagraphs,
findRemovedNodesParagraphs,
findRemovedParagraphs,
findSelectionParagraphs,
findUpdatedParagraphs,
RemovedParagraph
} from '../utils/paragraphs.utils';
import {getRange, getSelection} from '../utils/selection.utils';
import {toUndoRedoSelection} from '../utils/undo-redo-selection.utils';
import {
nextRedoChanges,
nextUndoChanges,
redo,
stackUndoInput,
stackUndoParagraphs,
undo
} from '../utils/undo-redo.utils';
interface UndoUpdateParagraphs extends UndoRedoUpdateParagraph {
paragraph: HTMLElement;
}
export class UndoRedoEvents {
private observer: MutationObserver | undefined;
private undoInputs: UndoRedoInput[] | undefined = undefined;
private undoUpdateParagraphs: UndoUpdateParagraphs[] = [];
private undoSelection: UndoRedoSelection | undefined = undefined;
private readonly debounceUpdateInputs: () => void = debounce(() => this.stackUndoInputs(), 350);
private unsubscribe;
init() {
this.undoInputs = undefined;
this.undoUpdateParagraphs = [];
this.observer = new MutationObserver(this.onMutation);
this.observe();
containerStore.state.ref?.addEventListener('keydown', this.onKeydown);
containerStore.state.ref?.addEventListener('keyup', this.onKeyup);
containerStore.state.ref?.addEventListener('mousedown', this.onMouseTouchDown);
containerStore.state.ref?.addEventListener('touchstart', this.onMouseTouchDown);
containerStore.state.ref?.addEventListener('snapshotParagraph', this.onSnapshotParagraph);
document.addEventListener('selectionchange', this.onSelectionChange);
document.addEventListener('toolbarActivated', this.onToolbarActivated);
document.addEventListener('menuActivated', this.onMenuActivated);
this.unsubscribe = undoRedoStore.onChange('observe', (observe: boolean) => {
if (observe) {
// We re-active the selection as if we would have selected a paragraphs because we might need to record next update
this.copySelectedParagraphs({filterEmptySelection: false});
this.undoInputs = undefined;
this.observe();
return;
}
this.disconnect();
});
}
destroy() {
this.disconnect();
containerStore.state.ref?.removeEventListener('keydown', this.onKeydown);
containerStore.state.ref?.removeEventListener('keyup', this.onKeyup);
containerStore.state.ref?.removeEventListener('mousedown', this.onMouseTouchDown);
containerStore.state.ref?.removeEventListener('touchstart', this.onMouseTouchDown);
containerStore.state.ref?.removeEventListener('snapshotParagraph', this.onSnapshotParagraph);
document.removeEventListener('selectionchange', this.onSelectionChange);
document.removeEventListener('toolbarActivated', this.onToolbarActivated);
document.removeEventListener('menuActivated', this.onMenuActivated);
this.unsubscribe?.();
}
private onKeydown = async ($event: KeyboardEvent) => {
const {key, ctrlKey, metaKey, shiftKey} = $event;
if (key === 'Enter') {
this.stackUndoInputs();
return;
}
if (key === 'z' && (ctrlKey || metaKey) && !shiftKey) {
await this.undo($event);
return;
}
if (key === 'z' && (ctrlKey || metaKey) && shiftKey) {
await this.redo($event);
return;
}
if (key === 'Backspace') {
this.stackBackspace();
}
};
private onKeyup = () => {
this.onEventUpdateParagraphs(getSelection(containerStore.state.ref)?.anchorNode);
};
private onSelectionChange = () =>
(this.undoSelection = toUndoRedoSelection(containerStore.state.ref));
private async undo($event: KeyboardEvent) {
$event.preventDefault();
if (nextUndoChanges() === undefined) {
return;
}
await this.undoRedo({undoRedo: undo});
}
private async redo($event: KeyboardEvent) {
$event.preventDefault();
if (nextRedoChanges() === undefined) {
return;
}
await this.undoRedo({undoRedo: redo});
}
private stackUndoInputs() {
this.copySelectedParagraphs({filterEmptySelection: false});
if (!this.undoInputs) {
return;
}
stackUndoInput({
data: this.undoInputs,
container: containerStore.state.ref
});
this.undoInputs = undefined;
}
// When user hits backspace at the begin of a paragraph we should stack previous paragraph for update and current one because it will be removed
private stackBackspace() {
const {range} = getRange(containerStore.state.ref);
if (!range) {
return;
}
const zeroWidthSpace: boolean =
range.startOffset === 1 && range.startContainer.textContent.charAt(0) === '\u200B';
// Begin of paragraph?
if (!(range.startOffset === 0 || zeroWidthSpace)) {
return;
}
const anchorNode: Node | undefined = getSelection(containerStore.state.ref)?.anchorNode;
if (!anchorNode) {
return;
}
const paragraph: HTMLElement | undefined = toHTMLElement(
findParagraph({
element: anchorNode,
container: containerStore.state.ref
})
);
if (!paragraph) {
return;
}
this.undoUpdateParagraphs = this.toUpdateParagraphs([
...(paragraph.previousElementSibling
? [paragraph.previousElementSibling as HTMLElement]
: []),
paragraph
]);
}
private async undoRedo({undoRedo}: {undoRedo: () => Promise<void>}) {
// We skip mutations when we process undo redo
this.disconnect();
await undoRedo();
this.observe();
}
private observe() {
this.observer.observe(containerStore.state.ref, {
childList: true,
characterData: true,
characterDataOldValue: true,
attributes: true,
subtree: true
});
}
private disconnect() {
this.observer?.disconnect();
}
private onToolbarActivated = () => {
this.copySelectedParagraphs({filterEmptySelection: true});
};
private onMenuActivated = ({detail}: CustomEvent<{paragraph: HTMLElement}>) => {
const {paragraph} = detail;
this.undoUpdateParagraphs = this.toUpdateParagraphs([paragraph]);
};
private onSnapshotParagraph = ({target}: CustomEvent<void>) => {
this.onEventUpdateParagraphs(target as Node);
};
private onMouseTouchDown = ({target}: MouseEvent | TouchEvent) => {
this.onEventUpdateParagraphs(target as Node);
};
private onEventUpdateParagraphs(target: Node | undefined) {
if (!target) {
return;
}
const paragraph: HTMLElement | undefined = toHTMLElement(
findParagraph({element: target as Node, container: containerStore.state.ref})
);
if (!paragraph) {
return;
}
this.undoUpdateParagraphs = this.toUpdateParagraphs([paragraph]);
}
// Copy current paragraphs value to a local state so we can add it to the undo redo global store in case of modifications
private copySelectedParagraphs({filterEmptySelection}: {filterEmptySelection: boolean}) {
const paragraphs: HTMLElement[] | undefined = findSelectionParagraphs({
container: containerStore.state.ref,
filterEmptySelection
});
if (!paragraphs) {
return;
}
this.undoUpdateParagraphs = this.toUpdateParagraphs(paragraphs);
}
private toUpdateParagraphs(paragraphs: HTMLElement[]): UndoUpdateParagraphs[] {
return paragraphs.map((paragraph: HTMLElement) => ({
outerHTML: paragraph.outerHTML,
index: elementIndex(paragraph),
paragraph
}));
}
private onCharacterDataMutations(mutations: MutationRecord[]) {
const characterMutations: MutationRecord[] = mutations.filter(
({oldValue}: MutationRecord) => oldValue !== null
);
// No character mutations
if (characterMutations.length <= 0) {
return;
}
if (!this.undoInputs) {
this.undoInputs = characterMutations
.map((mutation: MutationRecord) => this.toUndoInput(mutation))
.filter((undoInput: UndoRedoInput | undefined) => undoInput !== undefined);
}
if (this.undoInputs.length <= 0) {
this.undoInputs = undefined;
return;
}
this.debounceUpdateInputs();
}
private toUndoInput(mutation: MutationRecord): UndoRedoInput | undefined {
const target: Node = mutation.target;
const newValue: string = target.nodeValue;
// Firefox triggers a character mutation that has same previous and new value when we delete a range in deleteContentBackward
if (newValue === mutation.oldValue) {
return undefined;
}
const paragraph: HTMLElement | undefined = toHTMLElement(
findParagraph({element: target, container: containerStore.state.ref})
);
if (!paragraph || !target.parentNode) {
return undefined;
}
// We find the list of node indexes of the parent of the modified text
const depths: number[] = nodeDepths({target, paragraph});
return {
oldValue: mutation.oldValue,
offset: caretPosition({target}) + (mutation.oldValue.length - newValue.length),
index: elementIndex(paragraph),
indexDepths: depths
};
}
private onMutation = (mutations: MutationRecord[]) => {
const addRemoveParagraphs: UndoRedoAddRemoveParagraph[] = this.onParagraphsMutations(mutations);
const updateParagraphs: UndoRedoUpdateParagraph[] = this.onNodesParagraphsMutation(mutations);
stackUndoParagraphs({
container: containerStore.state.ref,
addRemoveParagraphs: addRemoveParagraphs,
updateParagraphs,
selection: this.undoSelection
});
// We assume that all paragraphs updates do contain attributes and input changes
if (updateParagraphs.length > 0) {
return;
}
this.onAttributesMutation(mutations);
this.onCharacterDataMutations(mutations);
};
/**
* Paragraphs added and removed
*/
private onParagraphsMutations(mutations: MutationRecord[]): UndoRedoAddRemoveParagraph[] {
const changes: UndoRedoAddRemoveParagraph[] = [];
// New paragraph
const addedParagraphs: HTMLElement[] = findAddedParagraphs({
mutations,
container: containerStore.state.ref
});
addedParagraphs.forEach((paragraph: HTMLElement) =>
changes.push({
outerHTML: this.cleanOuterHTML(paragraph),
mutation: 'add',
index: paragraph.previousElementSibling
? elementIndex(toHTMLElement(paragraph.previousElementSibling)) + 1
: 0
})
);
// Sort descending because undo-redo will remove the items in that order with their index
changes.sort(
({index: indexA}: UndoRedoAddRemoveParagraph, {index: indexB}: UndoRedoAddRemoveParagraph) =>
indexB - indexA
);
// Paragraphs removed
const removedParagraphs: RemovedParagraph[] = findRemovedParagraphs({
mutations,
container: containerStore.state.ref,
paragraphIdentifier: configStore.state.attributes.paragraphIdentifier
});
const lowerIndex: number = Math.min(
...removedParagraphs.map(({previousSibling}: RemovedParagraph) =>
previousSibling ? elementIndex(toHTMLElement(previousSibling)) + 1 : 0
)
);
removedParagraphs.forEach(({paragraph}: RemovedParagraph, index: number) => {
const elementIndex: number = index + (Number.isFinite(lowerIndex) ? lowerIndex : 0);
const undoParagraph: UndoUpdateParagraphs | undefined = this.undoUpdateParagraphs.find(
({index}: UndoUpdateParagraphs) => index === elementIndex
);
// cleanOuterHTML is only there as fallback, we should find the previous outerHTML value in undoUpdateParagraphs
return changes.push({
outerHTML: undoParagraph?.outerHTML || this.cleanOuterHTML(paragraph),
mutation: 'remove',
index: elementIndex
});
});
return changes;
}
/**
* Nodes within paragraphs added and removed.
*
* If we stack an update of the paragraph we shall not also stack an "input" update at the same time.
*
* @return did update
*/
private onNodesParagraphsMutation(mutations: MutationRecord[]): UndoUpdateParagraphs[] {
const addedNodesMutations: MutationRecord[] = findAddedNodesParagraphs({
mutations,
container: containerStore.state.ref
});
const removedNodesMutations: MutationRecord[] = findRemovedNodesParagraphs({
mutations,
paragraphIdentifier: configStore.state.attributes.paragraphIdentifier
});
const needsUpdate: boolean = addedNodesMutations.length > 0 || removedNodesMutations.length > 0;
if (!needsUpdate) {
return [];
}
if (this.undoUpdateParagraphs.length <= 0) {
return [];
}
const addedParagraphs: HTMLElement[] = findAddedParagraphs({
mutations,
container: containerStore.state.ref
});
// Check that the nodes of the paragraphs to update were not already been added to the undoRedo store in `onParagraphsMutations`
const filterUndoUpdateParagraphs: UndoUpdateParagraphs[] = this.undoUpdateParagraphs.filter(
({paragraph}: UndoUpdateParagraphs) =>
paragraph.isConnected &&
addedParagraphs.find((element: HTMLElement) => element.isEqualNode(paragraph)) === undefined
);
if (filterUndoUpdateParagraphs.length <= 0) {
this.copySelectedParagraphs({filterEmptySelection: true});
return [];
}
this.copySelectedParagraphs({filterEmptySelection: true});
this.undoInputs = undefined;
return filterUndoUpdateParagraphs;
}
private cleanOuterHTML(paragraph: HTMLElement): string {
const clone: HTMLElement = paragraph.cloneNode(true) as HTMLElement;
clone.removeAttribute('placeholder');
return clone.outerHTML;
}
private onAttributesMutation(mutations: MutationRecord[]) {
const updateParagraphs: HTMLElement[] = findUpdatedParagraphs({
mutations: filterAttributesMutations({
mutations,
excludeAttributes: configStore.state.attributes.exclude
}),
container: containerStore.state.ref
});
if (updateParagraphs.length <= 0) {
return;
}
if (this.undoUpdateParagraphs.length <= 0) {
return;
}
stackUndoParagraphs({
container: containerStore.state.ref,
addRemoveParagraphs: [],
updateParagraphs: this.undoUpdateParagraphs,
selection: this.undoSelection
});
this.undoUpdateParagraphs = this.toUpdateParagraphs(updateParagraphs);
}
} | the_stack |
import React from 'react';
import { Popconfirm, Row, Col, Slider, Collapse, Typography } from 'antd';
import { ExclamationCircleFilled } from '@ant-design/icons';
import classNames from 'classnames';
import { FieldUpdaterFunc, VideoVariant, UpdateArgs } from '../../types/config-section';
import TextField from './form-textfield';
import {
DEFAULT_VARIANT_STATE,
VIDEO_VARIANT_SETTING_DEFAULTS,
VIDEO_NAME_DEFAULTS,
ENCODER_PRESET_SLIDER_MARKS,
ENCODER_PRESET_TOOLTIPS,
VIDEO_BITRATE_DEFAULTS,
VIDEO_BITRATE_SLIDER_MARKS,
FRAMERATE_SLIDER_MARKS,
FRAMERATE_DEFAULTS,
FRAMERATE_TOOLTIPS,
} from '../../utils/config-constants';
import ToggleSwitch from './form-toggleswitch';
const { Panel } = Collapse;
interface VideoVariantFormProps {
dataState: VideoVariant;
onUpdateField: FieldUpdaterFunc;
}
export default function VideoVariantForm({
dataState = DEFAULT_VARIANT_STATE,
onUpdateField,
}: VideoVariantFormProps) {
const videoPassthroughEnabled = dataState.videoPassthrough;
const handleFramerateChange = (value: number) => {
onUpdateField({ fieldName: 'framerate', value });
};
const handleVideoBitrateChange = (value: number) => {
onUpdateField({ fieldName: 'videoBitrate', value });
};
const handleVideoCpuUsageLevelChange = (value: number) => {
onUpdateField({ fieldName: 'cpuUsageLevel', value });
};
const handleScaledWidthChanged = (args: UpdateArgs) => {
const value = Number(args.value);
// eslint-disable-next-line no-restricted-globals
if (isNaN(value)) {
return;
}
onUpdateField({ fieldName: 'scaledWidth', value: value || 0 });
};
const handleScaledHeightChanged = (args: UpdateArgs) => {
const value = Number(args.value);
// eslint-disable-next-line no-restricted-globals
if (isNaN(value)) {
return;
}
onUpdateField({ fieldName: 'scaledHeight', value: value || 0 });
};
// Video passthrough handling
const handleVideoPassConfirm = () => {
onUpdateField({ fieldName: 'videoPassthrough', value: true });
};
// If passthrough is currently on, set it back to false on toggle.
// Else let the Popconfirm turn it on.
const handleVideoPassthroughToggle = (value: boolean) => {
if (videoPassthroughEnabled) {
onUpdateField({ fieldName: 'videoPassthrough', value });
}
};
const handleNameChanged = (args: UpdateArgs) => {
onUpdateField({ fieldName: 'name', value: args.value });
};
// Slider notes
const selectedVideoBRnote = () => {
if (videoPassthroughEnabled) {
return 'Bitrate selection is disabled when Video Passthrough is enabled.';
}
let note = `${dataState.videoBitrate}${VIDEO_BITRATE_DEFAULTS.unit}`;
if (dataState.videoBitrate < 2000) {
note = `${note} - Good for low bandwidth environments.`;
} else if (dataState.videoBitrate < 3500) {
note = `${note} - Good for most bandwidth environments.`;
} else {
note = `${note} - Good for high bandwidth environments.`;
}
return note;
};
const selectedFramerateNote = () => {
if (videoPassthroughEnabled) {
return 'Framerate selection is disabled when Video Passthrough is enabled.';
}
return FRAMERATE_TOOLTIPS[dataState.framerate] || '';
};
const cpuUsageNote = () => {
if (videoPassthroughEnabled) {
return 'CPU usage selection is disabled when Video Passthrough is enabled.';
}
return ENCODER_PRESET_TOOLTIPS[dataState.cpuUsageLevel] || '';
};
const classes = classNames({
'config-variant-form': true,
'video-passthrough-enabled': videoPassthroughEnabled,
});
return (
<div className={classes}>
<p className="description">
<a
href="https://owncast.online/docs/video?source=admin"
target="_blank"
rel="noopener noreferrer"
>
Learn more
</a>{' '}
about how each of these settings can impact the performance of your server.
</p>
{videoPassthroughEnabled && (
<p className="passthrough-warning">
NOTE: Video Passthrough for this output stream variant is <em>enabled</em>, disabling the
below video encoding settings.
</p>
)}
<Row gutter={16}>
<TextField
maxLength="10"
{...VIDEO_NAME_DEFAULTS}
value={dataState.name}
onChange={handleNameChanged}
/>
<Col sm={24} md={12}>
<div className="form-module cpu-usage-container">
<Typography.Title level={3}>CPU or GPU Utilization</Typography.Title>
<p className="description">
Reduce to improve server performance, or increase it to improve video quality.
</p>
<div className="segment-slider-container">
<Slider
tipFormatter={value => ENCODER_PRESET_TOOLTIPS[value]}
onChange={handleVideoCpuUsageLevelChange}
min={1}
max={Object.keys(ENCODER_PRESET_SLIDER_MARKS).length}
marks={ENCODER_PRESET_SLIDER_MARKS}
defaultValue={dataState.cpuUsageLevel}
value={dataState.cpuUsageLevel}
disabled={dataState.videoPassthrough}
/>
<p className="selected-value-note">{cpuUsageNote()}</p>
</div>
<p className="read-more-subtext">
This could mean GPU or CPU usage depending on your server environment.{' '}
<a
href="https://owncast.online/docs/video/?source=admin#cpu-usage"
target="_blank"
rel="noopener noreferrer"
>
Read more about hardware performance.
</a>
</p>
</div>
</Col>
<Col sm={24} md={12}>
{/* VIDEO BITRATE FIELD */}
<div
className={`form-module bitrate-container ${
dataState.videoPassthrough ? 'disabled' : ''
}`}
>
<Typography.Title level={3}>Video Bitrate</Typography.Title>
<p className="description">{VIDEO_BITRATE_DEFAULTS.tip}</p>
<div className="segment-slider-container">
<Slider
tipFormatter={value => `${value} ${VIDEO_BITRATE_DEFAULTS.unit}`}
disabled={dataState.videoPassthrough}
defaultValue={dataState.videoBitrate}
value={dataState.videoBitrate}
onChange={handleVideoBitrateChange}
step={VIDEO_BITRATE_DEFAULTS.incrementBy}
min={VIDEO_BITRATE_DEFAULTS.min}
max={VIDEO_BITRATE_DEFAULTS.max}
marks={VIDEO_BITRATE_SLIDER_MARKS}
/>
<p className="selected-value-note">{selectedVideoBRnote()}</p>
</div>
<p className="read-more-subtext">
<a
href="https://owncast.online/docs/video/?source=admin"
target="_blank"
rel="noopener noreferrer"
>
Read more about bitrates.
</a>
</p>
</div>
</Col>
</Row>
<Collapse className="advanced-settings">
<Panel header="Advanced Settings" key="1">
<Row gutter={16}>
<Col sm={24} md={12}>
<div className="form-module resolution-module">
<Typography.Title level={3}>Resolution</Typography.Title>
<p className="description">
Resizing your content will take additional resources on your server. If you wish
to optionally resize your content for this stream output then you should either
set the width <strong>or</strong> the height to keep your aspect ratio.{' '}
<a
href="https://owncast.online/docs/video/?source=admin"
target="_blank"
rel="noopener noreferrer"
>
Read more about resolutions.
</a>
</p>
<br />
<TextField
type="number"
{...VIDEO_VARIANT_SETTING_DEFAULTS.scaledWidth}
value={dataState.scaledWidth}
onChange={handleScaledWidthChanged}
disabled={dataState.videoPassthrough}
/>
<TextField
type="number"
{...VIDEO_VARIANT_SETTING_DEFAULTS.scaledHeight}
value={dataState.scaledHeight}
onChange={handleScaledHeightChanged}
disabled={dataState.videoPassthrough}
/>
</div>
</Col>
<Col sm={24} md={12}>
{/* VIDEO PASSTHROUGH FIELD */}
<div className="form-module video-passthrough-module">
<Typography.Title level={3}>Video Passthrough</Typography.Title>
<div className="description">
<p>
Enabling video passthrough may allow for less hardware utilization, but may also
make your stream <strong>unplayable</strong>.
</p>
<p>
All other settings for this stream output will be disabled if passthrough is
used.
</p>
<p>
<a
href="https://owncast.online/docs/video/?source=admin#video-passthrough"
target="_blank"
rel="noopener noreferrer"
>
Read the documentation before enabling, as it impacts your stream.
</a>
</p>
</div>
<Popconfirm
disabled={dataState.videoPassthrough === true}
title="Did you read the documentation about video passthrough and understand the risks involved with enabling it?"
icon={<ExclamationCircleFilled />}
onConfirm={handleVideoPassConfirm}
okText="Yes"
cancelText="No"
>
{/* adding an <a> tag to force Popcofirm to register click on toggle */}
{/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
<a href="#">
<ToggleSwitch
label="Use Video Passthrough?"
fieldName="video-passthrough"
tip={VIDEO_VARIANT_SETTING_DEFAULTS.videoPassthrough.tip}
checked={dataState.videoPassthrough}
onChange={handleVideoPassthroughToggle}
/>
</a>
</Popconfirm>
</div>
</Col>
</Row>
{/* FRAME RATE FIELD */}
<div className="form-module frame-rate-module">
<Typography.Title level={3}>Frame rate</Typography.Title>
<p className="description">{FRAMERATE_DEFAULTS.tip}</p>
<div className="segment-slider-container">
<Slider
tipFormatter={value => `${value} ${FRAMERATE_DEFAULTS.unit}`}
defaultValue={dataState.framerate}
value={dataState.framerate}
onChange={handleFramerateChange}
step={FRAMERATE_DEFAULTS.incrementBy}
min={FRAMERATE_DEFAULTS.min}
max={FRAMERATE_DEFAULTS.max}
marks={FRAMERATE_SLIDER_MARKS}
disabled={dataState.videoPassthrough}
/>
<p className="selected-value-note">{selectedFramerateNote()}</p>
</div>
<p className="read-more-subtext">
<a
href="https://owncast.online/docs/video/?source=admin#framerate"
target="_blank"
rel="noopener noreferrer"
>
Read more about framerates.
</a>
</p>
</div>
</Panel>
</Collapse>
</div>
);
} | the_stack |
import axios from "axios"
import {Md5} from "ts-md5"
import * as dotenv from "dotenv"
import {existsSync, readFileSync} from "fs"
import {sendNotify} from './sendNotify'
dotenv.config()
const USER_AGENTS_ARR: string[] = [
"jdapp;android;10.0.2;10;network/wifi;Mozilla/5.0 (Linux; Android 10; ONEPLUS A5010 Build/QKQ1.191014.012; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045230 Mobile Safari/537.36",
"jdapp;iPhone;10.0.2;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;android;10.0.2;9;network/4g;Mozilla/5.0 (Linux; Android 9; Mi Note 3 Build/PKQ1.181007.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/045131 Mobile Safari/537.36",
"jdapp;android;10.0.2;10;network/wifi;Mozilla/5.0 (Linux; Android 10; GM1910 Build/QKQ1.190716.003; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045230 Mobile Safari/537.36",
"jdapp;android;10.0.2;9;network/wifi;Mozilla/5.0 (Linux; Android 9; 16T Build/PKQ1.190616.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/044942 Mobile Safari/537.36",
"jdapp;iPhone;10.0.2;13.6;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 13_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;iPhone;10.0.2;13.6;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 13_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;iPhone;10.0.2;13.5;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 13_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;iPhone;10.0.2;14.1;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 14_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;iPhone;10.0.2;13.3;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;iPhone;10.0.2;13.7;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;iPhone;10.0.2;14.1;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 14_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;iPhone;10.0.2;13.3;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;iPhone;10.0.2;13.4;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 13_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;iPhone;10.0.2;14.3;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;android;10.0.2;9;network/wifi;Mozilla/5.0 (Linux; Android 9; MI 6 Build/PKQ1.190118.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/044942 Mobile Safari/537.36",
"jdapp;android;10.0.2;11;network/wifi;Mozilla/5.0 (Linux; Android 11; Redmi K30 5G Build/RKQ1.200826.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045511 Mobile Safari/537.36",
"jdapp;iPhone;10.0.2;11.4;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 11_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15F79",
"jdapp;android;10.0.2;10;;network/wifi;Mozilla/5.0 (Linux; Android 10; M2006J10C Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045230 Mobile Safari/537.36",
"jdapp;android;10.0.2;10;network/wifi;Mozilla/5.0 (Linux; Android 10; M2006J10C Build/QP1A.190711.020; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045230 Mobile Safari/537.36",
"jdapp;android;10.0.2;10;network/wifi;Mozilla/5.0 (Linux; Android 10; ONEPLUS A6000 Build/QKQ1.190716.003; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045224 Mobile Safari/537.36",
"jdapp;android;10.0.2;9;network/wifi;Mozilla/5.0 (Linux; Android 9; MHA-AL00 Build/HUAWEIMHA-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/044942 Mobile Safari/537.36",
"jdapp;android;10.0.2;8.1.0;network/wifi;Mozilla/5.0 (Linux; Android 8.1.0; 16 X Build/OPM1.171019.026; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/044942 Mobile Safari/537.36",
"jdapp;android;10.0.2;8.0.0;network/wifi;Mozilla/5.0 (Linux; Android 8.0.0; HTC U-3w Build/OPR6.170623.013; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/044942 Mobile Safari/537.36",
"jdapp;iPhone;10.0.2;14.0.1;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 14_0_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;android;10.0.2;10;network/wifi;Mozilla/5.0 (Linux; Android 10; LYA-AL00 Build/HUAWEILYA-AL00L; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045230 Mobile Safari/537.36",
"jdapp;iPhone;10.0.2;14.2;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;iPhone;10.0.2;14.3;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;iPhone;10.0.2;14.2;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;android;10.0.2;8.1.0;network/wifi;Mozilla/5.0 (Linux; Android 8.1.0; MI 8 Build/OPM1.171019.026; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/6.2 TBS/045131 Mobile Safari/537.36",
"jdapp;android;10.0.2;10;network/wifi;Mozilla/5.0 (Linux; Android 10; Redmi K20 Pro Premium Edition Build/QKQ1.190825.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045227 Mobile Safari/537.36",
"jdapp;iPhone;10.0.2;14.3;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;iPhone;10.0.2;14.3;network/4g;Mozilla/5.0 (iPhone; CPU iPhone OS 14_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
"jdapp;android;10.0.2;11;network/wifi;Mozilla/5.0 (Linux; Android 11; Redmi K20 Pro Premium Edition Build/RKQ1.200826.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045513 Mobile Safari/537.36",
"jdapp;android;10.0.2;10;network/wifi;Mozilla/5.0 (Linux; Android 10; MI 8 Build/QKQ1.190828.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/77.0.3865.120 MQQBrowser/6.2 TBS/045227 Mobile Safari/537.36",
"jdapp;iPhone;10.0.2;14.1;network/wifi;Mozilla/5.0 (iPhone; CPU iPhone OS 14_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1",
]
function getRandomNumberByRange(start: number, end: number) {
end <= start && (end = start + 100)
return Math.floor(Math.random() * (end - start) + start)
}
let USER_AGENT = USER_AGENTS_ARR[getRandomNumberByRange(0, USER_AGENTS_ARR.length)]
async function getBeanShareCode(cookie: string) {
let {data}: any = await axios.post('https://api.m.jd.com/client.action',
`functionId=plantBeanIndex&body=${encodeURIComponent(
JSON.stringify({version: "9.0.0.1", "monitor_source": "plant_app_plant_index", "monitor_refer": ""})
)}&appid=ld&client=apple&area=5_274_49707_49973&build=167283&clientVersion=9.1.0`, {
headers: {
Cookie: cookie,
Host: "api.m.jd.com",
Accept: "*/*",
Connection: "keep-alive",
"User-Agent": USER_AGENT
}
})
if (data.data?.jwordShareInfo?.shareUrl)
return data.data.jwordShareInfo.shareUrl.split('Uuid=')![1]
else
return ''
}
async function getFarmShareCode(cookie: string) {
let {data}: any = await axios.post('https://api.m.jd.com/client.action?functionId=initForFarm', `body=${encodeURIComponent(JSON.stringify({"version": 4}))}&appid=wh5&clientVersion=9.1.0`, {
headers: {
"cookie": cookie,
"origin": "https://home.m.jd.com",
"referer": "https://home.m.jd.com/myJd/newhome.action",
"User-Agent": USER_AGENT,
"Content-Type": "application/x-www-form-urlencoded"
}
})
if (data.farmUserPro)
return data.farmUserPro.shareCode
else
return ''
}
async function getCookie(check: boolean = false): Promise<string[]> {
let pwd: string = __dirname
let cookiesArr: string[] = []
const jdCookieNode = require('./jdCookie.js')
let keys: string[] = Object.keys(jdCookieNode)
for (let i = 0; i < keys.length; i++) {
let cookie = jdCookieNode[keys[i]]
if (!check) {
if (pwd.includes('/ql') && !pwd.includes('JDHelloWorld')) {
} else {
cookiesArr.push(cookie)
}
} else {
if (await checkCookie(cookie)) {
cookiesArr.push(cookie)
} else {
let username = decodeURIComponent(jdCookieNode[keys[i]].match(/pt_pin=([^;]*)/)![1])
console.log('Cookie失效', username)
await sendNotify('Cookie失效', '【京东账号】' + username)
}
}
}
console.log(`共${cookiesArr.length}个京东账号\n`)
return cookiesArr
}
async function checkCookie(cookie: string) {
await wait(3000)
try {
let {data}: any = await axios.get(`https://api.m.jd.com/client.action?functionId=GetJDUserInfoUnion&appid=jd-cphdeveloper-m&body=${encodeURIComponent(JSON.stringify({"orgFlag": "JD_PinGou_New", "callSource": "mainorder", "channel": 4, "isHomewhite": 0, "sceneval": 2}))}&loginType=2&_=${Date.now()}&sceneval=2&g_login_type=1&callback=GetJDUserInfoUnion&g_ty=ls`, {
headers: {
'authority': 'api.m.jd.com',
'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',
'referer': 'https://home.m.jd.com/',
'cookie': cookie
}
})
data = JSON.parse(data.match(/GetJDUserInfoUnion\((.*)\)/)[1])
return data.retcode === '0';
} catch (e) {
return false
}
}
function wait(ms: number) {
return new Promise(resolve => {
setTimeout(resolve, ms)
})
}
function getJxToken(cookie: string, phoneId: string = '') {
function generateStr(input: number) {
let src = 'abcdefghijklmnopqrstuvwxyz1234567890'
let res = ''
for (let i = 0; i < input; i++) {
res += src[Math.floor(src.length * Math.random())]
}
return res
}
if (!phoneId)
phoneId = generateStr(40)
let timestamp = Date.now().toString()
let nickname = cookie.match(/pt_pin=([^;]*)/)![1]
let jstoken = Md5.hashStr('' + decodeURIComponent(nickname) + timestamp + phoneId + 'tPOamqCuk9NLgVPAljUyIHcPRmKlVxDy')
return {
'strPgtimestamp': timestamp,
'strPhoneID': phoneId,
'strPgUUNum': jstoken
}
}
function exceptCookie(filename: string = 'x.ts') {
let except: any = []
if (existsSync('./utils/exceptCookie.json')) {
try {
except = JSON.parse(readFileSync('./utils/exceptCookie.json').toString() || '{}')[filename] || []
} catch (e) {
console.log('./utils/exceptCookie.json JSON格式错误')
}
}
return except
}
function randomString(e: number, word?: number) {
e = e || 32
let t = word === 26 ? "012345678abcdefghijklmnopqrstuvwxyz" : "0123456789abcdef", a = t.length, n = ""
for (let i = 0; i < e; i++)
n += t.charAt(Math.floor(Math.random() * a))
return n
}
function o2s(arr: object, title: string = '') {
title ? console.log(title, JSON.stringify(arr)) : console.log(JSON.stringify(arr))
}
function randomNumString(e: number) {
e = e || 32
let t = '0123456789', a = t.length, n = ""
for (let i = 0; i < e; i++)
n += t.charAt(Math.floor(Math.random() * a))
return n
}
function randomWord(n: number = 1) {
let t = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', a = t.length
let rnd: string = ''
for (let i = 0; i < n; i++) {
rnd += t.charAt(Math.floor(Math.random() * a))
}
return rnd
}
async function getshareCodeHW(key: string) {
let shareCodeHW: string[] = []
for (let i = 0; i < 5; i++) {
try {
let {data}: any = await axios.get('https://api.jdsharecode.xyz/api/HW_CODES')
shareCodeHW = data[key] || []
if (shareCodeHW.length !== 0) {
break
}
} catch (e) {
console.log("getshareCodeHW Error, Retry...")
await wait(getRandomNumberByRange(2000, 6000))
}
}
return shareCodeHW
}
async function getShareCodePool(key: string, num: number) {
let shareCode: string[] = []
for (let i = 0; i < 2; i++) {
try {
let {data}: any = await axios.get(`https://api.jdsharecode.xyz/api/${key}/${num}`)
shareCode = data.data || []
console.log(`随机获取${num}个${key}成功:${JSON.stringify(shareCode)}`)
if (shareCode.length !== 0) {
break
}
} catch (e) {
console.log("getShareCodePool Error, Retry...")
await wait(getRandomNumberByRange(2000, 6000))
}
}
return shareCode
}
/*
async function wechat_app_msg(title: string, content: string, user: string) {
let corpid: string = "", corpsecret: string = ""
let {data: gettoken} = await axios.get(`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${corpid}&corpsecret=${corpsecret}`)
let access_token: string = gettoken.access_token
let {data: send} = await axios.post(`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${access_token}`, {
"touser": user,
"msgtype": "text",
"agentid": 1000002,
"text": {
"content": `${title}\n\n${content}`
},
"safe": 0
})
if (send.errcode === 0) {
console.log('企业微信应用消息发送成功')
} else {
console.log('企业微信应用消息发送失败', send)
}
}
*/
async function getDevice() {
let {data} = await axios.get('https://betahub.cn/api/apple/devices/iPhone', {
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
}
})
data = data[getRandomNumberByRange(0, 16)]
return data.identifier
}
async function getVersion(device: string) {
let {data} = await axios.get(`https://betahub.cn/api/apple/firmwares/${device}`, {
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
}
})
data = data[getRandomNumberByRange(0, data.length)]
return data.firmware_info.version
}
async function jdpingou() {
let device: string, version: string;
device = await getDevice();
version = await getVersion(device);
return `jdpingou;iPhone;5.19.0;${version};${randomString(40)};network/wifi;model/${device};appBuild/100833;ADID/;supportApplePay/1;hasUPPay/0;pushNoticeIsOpen/0;hasOCPay/0;supportBestPay/0;session/${getRandomNumberByRange(10, 90)};pap/JA2019_3111789;brand/apple;supportJDSHWK/1;Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148`
}
function get(url: string, headers?: any): Promise<any> {
return new Promise((resolve, reject) => {
axios.get(url, {
headers: headers
}).then(res => {
if (typeof res.data === 'string' && res.data.includes('jsonpCBK')) {
resolve(JSON.parse(res.data.match(/jsonpCBK.?\(([\w\W]*)\);?/)[1]))
} else {
resolve(res.data)
}
}).catch(err => {
reject({
code: err?.response?.status || -1,
msg: err?.response?.statusText || err.message || 'error'
})
})
})
}
function post(url: string, prarms?: string | object, headers?: any): Promise<any> {
return new Promise((resolve, reject) => {
axios.post(url, prarms, {
headers: headers
}).then(res => {
resolve(res.data)
}).catch(err => {
reject({
code: err?.response?.status || -1,
msg: err?.response?.statusText || err.message || 'error'
})
})
})
}
export default USER_AGENT
export {
getBeanShareCode,
getFarmShareCode,
getCookie,
wait,
getRandomNumberByRange,
getJxToken,
exceptCookie,
randomString,
o2s,
randomNumString,
getshareCodeHW,
getShareCodePool,
randomWord,
jdpingou,
get,
post,
USER_AGENTS_ARR
} | the_stack |
import { Segmentation, SortedArray } from '../../../../mol-data/int';
import { combinations } from '../../../../mol-data/util/combination';
import { IntAdjacencyGraph } from '../../../../mol-math/graph';
import { Vec3 } from '../../../../mol-math/linear-algebra';
import { PrincipalAxes } from '../../../../mol-math/linear-algebra/matrix/principal-axes';
import { fillSerial, arraySetAdd } from '../../../../mol-util/array';
import { ResidueIndex, Model } from '../../model';
import { ElementSymbol, BondType } from '../../model/types';
import { getPositions } from '../../util';
import { StructureElement } from '../element';
import { Structure } from '../structure';
import { Unit } from '../unit';
import { CarbohydrateElement, CarbohydrateLink, Carbohydrates, CarbohydrateTerminalLink, PartialCarbohydrateElement, EmptyCarbohydrates } from './data';
import { UnitRings, UnitRing } from '../unit/rings';
import { ElementIndex } from '../../model/indexing';
import { cantorPairing } from '../../../../mol-data/util';
const C = ElementSymbol('C'), O = ElementSymbol('O');
const SugarRingFps = [
UnitRing.elementFingerprint([C, C, C, O]),
UnitRing.elementFingerprint([C, C, C, C, O]),
UnitRing.elementFingerprint([C, C, C, C, C, O]),
UnitRing.elementFingerprint([C, C, C, C, C, C, O]),
];
function getAnomericCarbon(unit: Unit.Atomic, ringAtoms: ArrayLike<StructureElement.UnitIndex>): ElementIndex {
let indexHasTwoOxygen = -1, indexHasOxygenAndCarbon = -1, indexHasC1Name = -1, indexIsCarbon = -1;
const { elements } = unit;
const { type_symbol, label_atom_id } = unit.model.atomicHierarchy.atoms;
const { b: neighbor, offset } = unit.bonds;
for (let i = 0, il = ringAtoms.length; i < il; ++i) {
const ei = elements[ringAtoms[i]];
if (type_symbol.value(ei) !== C) continue;
let linkedOxygenCount = 0;
let linkedCarbonCount = 0;
for (let j = offset[ringAtoms[i]], jl = offset[ringAtoms[i] + 1]; j < jl; ++j) {
const ej = elements[neighbor[j]];
const typeSymbol = type_symbol.value(ej);
if (typeSymbol === O) ++linkedOxygenCount;
else if (typeSymbol === C) ++linkedCarbonCount;
}
if (linkedOxygenCount === 2) {
// found anomeric carbon
indexHasTwoOxygen = ei;
break;
} else if (linkedOxygenCount === 1 && linkedCarbonCount === 1) {
// possibly an anomeric carbon if this is a mono-saccharide without a glycosidic bond
indexHasOxygenAndCarbon = ei;
} else if (label_atom_id.value(ei).startsWith('C1')) {
// likely the anomeric carbon as it is named C1 by convention
indexHasC1Name = ei;
} else {
// use any carbon as a fallback
indexIsCarbon = ei;
}
}
return (indexHasTwoOxygen !== -1 ? indexHasTwoOxygen
: indexHasOxygenAndCarbon !== -1 ? indexHasOxygenAndCarbon
: indexHasC1Name !== -1 ? indexHasC1Name
: indexIsCarbon !== -1 ? indexIsCarbon
: elements[ringAtoms[0]]) as ElementIndex;
}
function getAltId(unit: Unit.Atomic, index: StructureElement.UnitIndex) {
const { elements } = unit;
const { label_alt_id } = unit.model.atomicHierarchy.atoms;
return label_alt_id.value(elements[index]);
}
function getDirection(direction: Vec3, unit: Unit.Atomic, index: ElementIndex, center: Vec3) {
const { position } = unit.conformation;
Vec3.normalize(direction, Vec3.sub(direction, center, position(index, direction)));
return direction;
}
function getAtomId(unit: Unit.Atomic, index: StructureElement.UnitIndex) {
const { elements } = unit;
const { label_atom_id } = unit.model.atomicHierarchy.atoms;
return label_atom_id.value(elements[index]);
}
function filterFusedRings(unitRings: UnitRings, rings: UnitRings.Index[] | undefined) {
if (!rings || !rings.length) return;
const { unit, all } = unitRings;
const fusedRings = new Set<UnitRings.Index>();
const ringCombinations = combinations(fillSerial(new Array(rings.length) as number[]), 2);
for (let i = 0, il = ringCombinations.length; i < il; ++i) {
const rc = ringCombinations[i];
const r0 = all[rings[rc[0]]], r1 = all[rings[rc[1]]];
if (SortedArray.areIntersecting(r0, r1) &&
UnitRing.getAltId(unit, r0) === UnitRing.getAltId(unit, r1)) {
fusedRings.add(rings[rc[0]]);
fusedRings.add(rings[rc[1]]);
}
}
if (fusedRings.size) {
const filteredRings: UnitRings.Index[] = [];
for (let i = 0, il = rings.length; i < il; ++i) {
if (!fusedRings.has(rings[i])) filteredRings.push(rings[i]);
}
return filteredRings;
} else {
return rings;
}
}
function getSaccharideComp(compId: string, model: Model) {
return model.properties.saccharideComponentMap.get(compId);
}
export function computeCarbohydrates(structure: Structure): Carbohydrates {
// skip computation if there are no saccharide components in any model
if (structure.models.reduce((a, v) => a + v.properties.saccharideComponentMap.size, 0) === 0)
return EmptyCarbohydrates;
const links: CarbohydrateLink[] = [];
const terminalLinks: CarbohydrateTerminalLink[] = [];
const elements: CarbohydrateElement[] = [];
const partialElements: PartialCarbohydrateElement[] = [];
const elementsWithRingMap = new Map<string, number[]>();
function ringElementKey(residueIndex: number, unitId: number, altId: string) {
return `${residueIndex}|${unitId}|${altId}`;
}
function addRingElement(key: string, elementIndex: number) {
if (elementsWithRingMap.has(key)) elementsWithRingMap.get(key)!.push(elementIndex);
else elementsWithRingMap.set(key, [elementIndex]);
}
function fixLinkDirection(iA: number, iB: number) {
Vec3.sub(elements[iA].geometry.direction, elements[iB].geometry.center, elements[iA].geometry.center);
Vec3.normalize(elements[iA].geometry.direction, elements[iA].geometry.direction);
}
const tmpV = Vec3.zero();
function fixTerminalLinkDirection(iA: number, indexB: number, unitB: Unit.Atomic) {
const pos = unitB.conformation.position, geo = elements[iA].geometry;
Vec3.sub(geo.direction, pos(unitB.elements[indexB], tmpV), geo.center);
Vec3.normalize(geo.direction, geo.direction);
}
// get carbohydrate elements and carbohydrate links induced by intra-residue bonds
for (let i = 0, il = structure.units.length; i < il; ++i) {
const unit = structure.units[i];
if (!Unit.isAtomic(unit)) continue;
const { model, rings } = unit;
const { chainAtomSegments, residueAtomSegments, atoms } = model.atomicHierarchy;
const { label_comp_id } = atoms;
const chainIt = Segmentation.transientSegments(chainAtomSegments, unit.elements);
const residueIt = Segmentation.transientSegments(residueAtomSegments, unit.elements);
let sugarResidueMap: Map<ResidueIndex, UnitRings.Index[]> | undefined = void 0;
while (chainIt.hasNext) {
residueIt.setSegment(chainIt.move());
while (residueIt.hasNext) {
const { index: residueIndex } = residueIt.move();
const saccharideComp = getSaccharideComp(label_comp_id.value(residueAtomSegments.offsets[residueIndex]), model);
if (!saccharideComp) continue;
if (!sugarResidueMap) {
sugarResidueMap = UnitRings.byFingerprintAndResidue(rings, SugarRingFps);
}
const sugarRings = filterFusedRings(rings, sugarResidueMap.get(residueIndex));
if (!sugarRings || !sugarRings.length) {
partialElements.push({ unit, residueIndex, component: saccharideComp });
continue;
}
const ringElements: number[] = [];
for (let j = 0, jl = sugarRings.length; j < jl; ++j) {
const ringAtoms = rings.all[sugarRings[j]];
const anomericCarbon = getAnomericCarbon(unit, ringAtoms);
const ma = PrincipalAxes.calculateMomentsAxes(getPositions(unit, ringAtoms));
const center = Vec3.copy(Vec3.zero(), ma.origin);
const normal = Vec3.copy(Vec3.zero(), ma.dirC);
const direction = getDirection(Vec3.zero(), unit, anomericCarbon, center);
Vec3.orthogonalize(direction, normal, direction);
const ringAltId = UnitRing.getAltId(unit, ringAtoms);
const elementIndex = elements.length;
ringElements.push(elementIndex);
addRingElement(ringElementKey(residueIndex, unit.id, ringAltId), elementIndex);
if (ringAltId) addRingElement(ringElementKey(residueIndex, unit.id, ''), elementIndex);
elements.push({
geometry: { center, normal, direction },
component: saccharideComp,
ringIndex: sugarRings[j],
altId: ringAltId,
unit, residueIndex
});
}
// add carbohydrate links induced by intra-residue bonds
// (e.g. for structures from the PDB archive __before__ carbohydrate remediation)
const ringCombinations = combinations(fillSerial(new Array(sugarRings.length) as number[]), 2);
for (let j = 0, jl = ringCombinations.length; j < jl; ++j) {
const rc = ringCombinations[j];
const r0 = rings.all[sugarRings[rc[0]]], r1 = rings.all[sugarRings[rc[1]]];
// 1,6 glycosidic links are distance 3 and 1,4 glycosidic links are distance 2
if (IntAdjacencyGraph.areVertexSetsConnected(unit.bonds, r0, r1, 3)) {
const re0 = ringElements[rc[0]];
const re1 = ringElements[rc[1]];
if (elements[re0].altId === elements[re1].altId) {
// TODO handle better, for now fix both directions as it is unclear where the C1 atom is
// would need to know the path connecting the two rings
fixLinkDirection(re0, re1);
fixLinkDirection(re1, re0);
links.push({ carbohydrateIndexA: re0, carbohydrateIndexB: re1 });
links.push({ carbohydrateIndexA: re1, carbohydrateIndexB: re0 });
}
}
}
}
}
}
function getRingElementIndices(unit: Unit.Atomic, index: StructureElement.UnitIndex) {
return elementsWithRingMap.get(ringElementKey(unit.getResidueIndex(index), unit.id, getAltId(unit, index))) || [];
}
// add carbohydrate links induced by intra-unit bonds
// (e.g. for structures from the PDB archive __after__ carbohydrate remediation)
for (let i = 0, il = elements.length; i < il; ++i) {
const cA = elements[i];
const { unit } = cA;
for (let j = i + 1; j < il; ++j) {
const cB = elements[j];
if (unit !== cB.unit || cA.residueIndex === cB.residueIndex) continue;
const rA = unit.rings.all[cA.ringIndex];
const rB = unit.rings.all[cB.ringIndex];
if (IntAdjacencyGraph.areVertexSetsConnected(unit.bonds, rA, rB, 3)) {
// TODO handle better, for now fix both directions as it is unclear where the C1 atom is
// would need to know the path connecting the two rings
fixLinkDirection(i, j);
fixLinkDirection(j, i);
links.push({ carbohydrateIndexA: i, carbohydrateIndexB: j });
links.push({ carbohydrateIndexA: j, carbohydrateIndexB: i });
}
}
}
// get carbohydrate links induced by inter-unit bonds, that is
// inter monosaccharide links for structures from the
// PDB archive __before__ carbohydrate remediation
// plus terminal links for __before__ and __after__
for (let i = 0, il = structure.units.length; i < il; ++i) {
const unit = structure.units[i];
if (!Unit.isAtomic(unit)) continue;
structure.interUnitBonds.getConnectedUnits(unit.id).forEach(pairBonds => {
pairBonds.connectedIndices.forEach(indexA => {
pairBonds.getEdges(indexA).forEach(({ props, indexB }) => {
if (!BondType.isCovalent(props.flag)) return;
const unitA = structure.unitMap.get(pairBonds.unitA) as Unit.Atomic;
const unitB = structure.unitMap.get(pairBonds.unitB) as Unit.Atomic;
const ringElementIndicesA = getRingElementIndices(unitA, indexA);
const ringElementIndicesB = getRingElementIndices(unitB, indexB);
if (ringElementIndicesA.length > 0 && ringElementIndicesB.length > 0) {
const lA = ringElementIndicesA.length;
const lB = ringElementIndicesB.length;
for (let j = 0, jl = Math.max(lA, lB); j < jl; ++j) {
const ringElementIndexA = ringElementIndicesA[Math.min(j, lA - 1)];
const ringElementIndexB = ringElementIndicesB[Math.min(j, lB - 1)];
const atomIdA = getAtomId(unitA, indexA);
if (atomIdA.startsWith('O1') || atomIdA.startsWith('C1')) {
fixLinkDirection(ringElementIndexA, ringElementIndexB);
}
links.push({
carbohydrateIndexA: ringElementIndexA,
carbohydrateIndexB: ringElementIndexB
});
}
} else if (ringElementIndicesB.length === 0) {
for (const ringElementIndexA of ringElementIndicesA) {
const atomIdA = getAtomId(unitA, indexA);
if (atomIdA.startsWith('O1') || atomIdA.startsWith('C1')) {
fixTerminalLinkDirection(ringElementIndexA, indexB, unitB);
}
terminalLinks.push({
carbohydrateIndex: ringElementIndexA,
elementIndex: indexB,
elementUnit: unitB,
fromCarbohydrate: true
});
}
} else if (ringElementIndicesA.length === 0) {
for (const ringElementIndexB of ringElementIndicesB) {
terminalLinks.push({
carbohydrateIndex: ringElementIndexB,
elementIndex: indexA,
elementUnit: unitA,
fromCarbohydrate: false
});
}
}
});
});
});
}
return { links, terminalLinks, elements, partialElements, ...buildLookups(elements, links, terminalLinks) };
}
function buildLookups(elements: CarbohydrateElement[], links: CarbohydrateLink[], terminalLinks: CarbohydrateTerminalLink[]) {
function key(unit: Unit, element: ElementIndex) {
return cantorPairing(unit.id, element);
}
function getIndices(map: Map<number, number[]>, unit: Unit.Atomic, index: ElementIndex): ReadonlyArray<number> {
const indices: number[] = [];
const il = map.get(key(unit, index));
if (il !== undefined) {
for (const i of il) arraySetAdd(indices, i);
}
return indices;
}
// elements
const elementsMap = new Map<number, number[]>();
for (let i = 0, il = elements.length; i < il; ++i) {
const { unit, ringIndex } = elements[i];
const ring = unit.rings.all[ringIndex];
for (let j = 0, jl = ring.length; j < jl; ++j) {
const k = key(unit, unit.elements[ring[j]]);
const e = elementsMap.get(k);
if (e === undefined) elementsMap.set(k, [i]);
else e.push(i);
}
}
function getElementIndices(unit: Unit.Atomic, index: ElementIndex) {
return getIndices(elementsMap, unit, index);
}
// links
const linksMap = new Map<number, number[]>();
for (let i = 0, il = links.length; i < il; ++i) {
const l = links[i];
const { unit, ringIndex } = elements[l.carbohydrateIndexA];
const ring = unit.rings.all[ringIndex];
for (let j = 0, jl = ring.length; j < jl; ++j) {
const k = key(unit, unit.elements[ring[j]]);
const e = linksMap.get(k);
if (e === undefined) linksMap.set(k, [i]);
else e.push(i);
}
}
function getLinkIndices(unit: Unit.Atomic, index: ElementIndex) {
return getIndices(linksMap, unit, index);
}
// terminal links
const terminalLinksMap = new Map<number, number[]>();
for (let i = 0, il = terminalLinks.length; i < il; ++i) {
const { fromCarbohydrate, carbohydrateIndex, elementUnit, elementIndex } = terminalLinks[i];
if (fromCarbohydrate) {
const { unit, ringIndex } = elements[carbohydrateIndex];
const ring = unit.rings.all[ringIndex];
for (let j = 0, jl = ring.length; j < jl; ++j) {
const k = key(unit, unit.elements[ring[j]]);
const e = terminalLinksMap.get(k);
if (e === undefined) terminalLinksMap.set(k, [i]);
else e.push(i);
}
} else {
const k = key(elementUnit, elementUnit.elements[elementIndex]);
const e = terminalLinksMap.get(k);
if (e === undefined) terminalLinksMap.set(k, [i]);
else e.push(i);
}
}
function getTerminalLinkIndices(unit: Unit.Atomic, index: ElementIndex) {
return getIndices(terminalLinksMap, unit, index);
}
return { getElementIndices, getLinkIndices, getTerminalLinkIndices };
} | the_stack |
import { debuglog as dlog } from "../util"
import { Pos, NoPos } from "../pos"
import * as ir from "../ir/ssa"
import { ops as irops, opinfo as iropinfo, opnameMaxLen } from "../ir/ops"
import * as irop from "../ir/op"
import { Config } from "../ir/config"
import { ByteStr } from "../bytestr"
import { t_mem } from "../ast/nodes"
import { UInt64 } from "../int64"
export type Opcode = int // 16-bit unsigned integer
// Instr represent a single machine instruction
export class Instr {
op :Opcode // assembler opcode
pos :Pos // source position of this instruction
spAdj :int = 0 // effect of instruction on stack pointer (increment or decrement amount)
constructor(op :Opcode, pos :Pos) {
this.op = op
this.pos = pos
}
toString() {
let s = this
let sop = s.op.toString(16)
if (s.op <= 0xF) {
sop = "00" + sop
} else if (s.op <= 0xFF) {
sop = "0" + sop
}
return `${sop} // ${s.spAdj} "${iropinfo[s.op].name}"`
}
}
function fmthex<T extends {toString(radix:int):string}>(n :T, z :int = 4) {
let s = n.toString(16)
if (s.length < z) {
s = "0000000000000000".substr(0, z - s.length) + s
}
return s
}
// prefix in text output
const RegPrefix = ""
const IntConstPrefix = "$"
const SPACES = " "
// padr pads s with padding (defaults to spaces) so that s is at least width long.
//
function padr(s :string, width :int, padding? :string) :string {
return s.length < width ? s + (padding || SPACES).substr(0, width - s.length) : s
}
type EntryType = int
const TFUN = 0 as EntryType
, TINSTR = 2 as EntryType
// Entry is one line of assembly
class Entry {
t :EntryType
op :string // operation or label
imm :string[] // immediate arguments
comment :string // comment
pos :Pos // original source position
label :int = -1 // blockId. Used by TINSTR
addr :int = -1 // assigned object-local linear address
targetBlockId :int = -1 // used by branch instructions during addFun
targetEntry :Entry|null = null // target of branch instructions (after addFun)
constructor(t :EntryType, op :string, imm :string[], comment :string, pos :Pos) {
this.t = t
this.op = op
this.imm = imm
this.comment = comment
this.pos = pos
}
toString() {
const e = this
let ind = this.t == TINSTR ? " " : ""
let s = `${ind}${padr(e.op, opnameMaxLen)}`
let imm = e.imm.join(" ")
if (e.comment) {
s += ` ${padr(imm, 24 - ind.length)} ; ${e.comment}`
} else if (imm) {
s += ` ${imm}`
}
return s
}
}
export class Obj {
target :Config
pos :Pos // current source position
entries :Entry[] = [] // all entries in the object
// set to true when addresses have been allocated.
sealed = false
// state used during each addFun call
funEntries :Entry[] = [] // entries in the current function
blockEntries :Entry[] = [] // blockId => Entry(t=TINSTR)
pendingBlockEntry :int = -1 // blockId
constructor(target :Config) {
this.target = target
}
writeStr() :string {
let lines :string[] = []
let entries = this.entries
const addrw = 2
const spacePrefix = SPACES.substr(0, 4 + addrw*2)
for (let i = 0, z = entries.length; i < z; i++) {
let e = entries[i]
if (e.label != -1) {
lines.push(`${spacePrefix} b${e.label}:`)
}
let prefix = (
e.addr >= 0 ? "0x" + fmthex(e.addr, addrw*2) + " "
: spacePrefix
)
lines.push(prefix + e.toString())
}
return lines.join("\n")
}
seal(startAddr :int) {
if (this.sealed) {
throw new Error("already sealed")
}
this.sealed = true
let entries = this.entries
let addr = startAddr
const addrw = 2
let revisitBranches :Entry[] = []
// assign addresses
for (let i = 0, z = entries.length; i < z; i++) {
let e = entries[i]
if (e.t == TFUN) {
// align address to target address size
addr = align(addr, this.target.addrSize)
} else if (e.t == TINSTR) {
e.addr = addr++
if (e.op == "CALL") {
dlog(`TODO: resolve CALL address`)
}
if (e.targetEntry) {
if (e.targetEntry.addr == -1) {
revisitBranches.push(e)
} else {
e.imm.push("0x" + fmthex(e.targetEntry.addr, addrw*2))
e.targetEntry = null // clear so that subsequent calls doesn't add another imm
}
}
}
}
// second pass on forward-jumping branches
for (let e of revisitBranches) {
assert(e.targetEntry)
assert(e.targetEntry!.addr != -1)
e.imm.push("0x" + fmthex(e.targetEntry!.addr, addrw*2))
e.targetEntry = null // clear so that subsequent calls doesn't add another imm
}
}
addFun(f :ir.Fun) {
const o = this
if (o.sealed) {
throw new Error("sealed")
}
// initialize function-specific state
o.blockEntries = []
o.pendingBlockEntry = -1
o.funEntries = []
// FUNC head
this.addEntry(TFUN, `FUNC #${f.id}`, [], f.name.toString(), this.pos)
// Since block IDs may be sparsely numbered, and we depend on lookup, build
// dense list of blocks.
let blocks = f.blocks.filter(b => !!b)
// Emit basic blocks
for (let i = 0; i < blocks.length; i++) {
let nextBlock = blocks[i + 1]
o.addBlock(blocks[i], nextBlock)
}
// resolve branch targets from blockIds to Entry references
for (let i = 0, z = o.funEntries.length; i < z; i++) {
let e = o.funEntries[i]
if (e.targetBlockId != -1) {
e.targetEntry = o.blockEntries[e.targetBlockId]
if (!e.targetEntry) { dlog(o.blockEntries) }
assert(e.targetEntry, `non-existing target b${e.targetBlockId} in ${e}`)
}
}
// add function entries to all entries collection
o.entries = o.entries.concat(o.funEntries)
}
addEntry(t :EntryType, op :string, imm :string[], comment :string, pos :Pos) :Entry {
let e = new Entry(t, op, imm, comment, pos)
this.funEntries.push(e)
return e
}
addInstr(opname :string, imm :string[], comment :string) :Entry {
let e = this.addEntry(TINSTR, opname, imm, comment, this.pos)
if (this.pendingBlockEntry != -1) {
e.label = this.pendingBlockEntry
this.pendingBlockEntry = -1
this.blockEntries[e.label] = e
}
return e
}
addInstrV(v :ir.Value) {
let opinfo = iropinfo[v.op]
if (opinfo.zeroWidth) {
return
}
// immediates
let imms = this.buildImms(v, opinfo)
// let spAdj :int = 0 // stack pointer adjustment delta
this.addInstr(opinfo.name, imms, "")
}
buildImms(v :ir.Value, opinfo :irop.OpInfo) :string[] {
let imms :string[] = []
// inputs
for (let a of v.args) {
let ainfo = iropinfo[a.op]
if (a.reg) {
imms.push(RegPrefix + a.reg.name)
} else if (a.aux !== null) {
// then it must be a memory operand
assert(ainfo.type === t_mem,
`immediate operand ${a} to ${v} not in a register (${a}.type=${ainfo.type})`)
imms.push("0x" + fmthex(a.aux as any as int, 8))
}
}
// add aux
switch (opinfo.aux) {
case irop.AuxType.None:
break
case irop.AuxType.Bool: // auxInt is 1/0 for true/false
case irop.AuxType.Int8: // auxInt is an 8-bit integer
case irop.AuxType.Int16: // auxInt is a 16-bit integer
case irop.AuxType.Int32: // auxInt is a 32-bit integer
case irop.AuxType.Int64: // auxInt is a 64-bit integer
imms.push(IntConstPrefix + v.auxInt.toString(10))
break
case irop.AuxType.Float32: // auxInt is a float32
case irop.AuxType.Float64: { // auxInt is a float64
let i = UInt64.fromFloat64Cast(v.auxInt as number)
imms.push(IntConstPrefix + "0x" + i.toString(16))
break
}
case irop.AuxType.SymOff: // aux is a symbol, auxInt is an offset
case irop.AuxType.SymInt32: // aux is a symbol, auxInt is a 32-bit integer
if (v.aux) {
dlog(`TODO: imm symbol v=${v} aux=${v.aux}`)
}
imms.push(IntConstPrefix + v.auxInt.toString(10))
break
// TODO
case irop.AuxType.Type: // aux is a type
case irop.AuxType.String: // aux is a string
case irop.AuxType.Sym: // aux is a symbol
break
}
// output register
if (v.reg) {
imms.push(RegPrefix + v.reg.name)
} else {
dlog(`TODO: memory output. e.g. 0x10(SP) v=${v}`)
}
// if (opinfo.aux != irop.AuxType.None) {
// if (!imms) { imms = [] }
// imms.push(opinfo.aux)
// }
return imms
}
addJump(blockId :int, comment :string) {
let e = this.addInstr("JUMP", [], comment)
e.targetBlockId = blockId
}
addBranch(blockId :int, cond :string, comment :string) {
let e = this.addInstr("BR", [ cond ], comment)
e.targetBlockId = blockId
}
addBranchNeg(blockId :int, cond :string, comment :string) {
let e = this.addInstr("BRZ", [ cond ], comment)
e.targetBlockId = blockId
}
addBlock(b :ir.Block, nextb :ir.Block|null) {
const o = this
// enqueue block entry
assert(this.pendingBlockEntry == -1, `block immediately following another block`)
o.pendingBlockEntry = b.id
// instructions
for (let v of b.values) {
o.addInstrV(v)
}
// continuation
switch (b.kind) {
case ir.BlockKind.Plain: {
// unconditional jump
// TODO: immediate-successor jump elimination optimization
let contb = b.succs[0]
assert(contb)
o.addJump(contb.id, `b${contb.id}`)
break
}
case ir.BlockKind.First:
// BlockKind.First: 2 successors, always takes the first one (second is dead)
assert(0, `unexpected temporary IR "first" block ${b}`)
break
case ir.BlockKind.If: {
// branch
let thenb = b.succs[0] ; assert(thenb)
let elseb = b.succs[1] ; assert(elseb)
assert(b.control, "missing control (condition) value")
let ctrlReg = b.control!.reg!
assert(ctrlReg, `control value ${b.control} not in register`)
if (nextb === thenb) {
// if false goto elseb; cont thenb
o.addBranchNeg(elseb.id, RegPrefix + ctrlReg.name,
`if !${b.control} ? b${elseb.id} : b${thenb.id}`)
} else if (nextb === elseb) {
// if true goto thenb; cont elseb
o.addBranch(thenb.id, RegPrefix + ctrlReg.name,
`if ${b.control} ? b${thenb.id} : b${elseb.id}`)
} else {
// if true goto thenb; goto elseb
o.addBranch(thenb.id, RegPrefix + ctrlReg.name, `if ${b.control} ? b${thenb.id} ...`)
o.addJump(elseb.id, `... : b${elseb.id}`)
}
break
}
case ir.BlockKind.Ret: {
// return
assert(b.succs.length == 0, "can't have successor to return block")
// TODO: consider if we need to do antyhing with b.control which is the memory
// location at the end (stack memory location.)
o.addInstr("RET", [], "")
break
}
default:
assert(false, `unexpected block kind ${ir.BlockKind[b.kind]}`)
}
}
}
// align rounds up n to closest boundary w (w must be a power of two)
//
// E.g.
// align(0, 4) => 0
// align(1, 4) => 4
// align(2, 4) => 4
// align(3, 4) => 4
// align(4, 4) => 4
// align(5, 4) => 8
// ...
//
function align(n :int, w :int) :int {
assert((w & (w - 1)) == 0, `alignment ${w} not a power of two`)
return (n + (w - 1)) & ~(w - 1)
}
// // These are generic, portable opcodes common to all architectures.
// export const
// AXXX :Opcode = 0
// , ACALL :Opcode = 1
// , ADUFFCOPY :Opcode = 2
// , ADUFFZERO :Opcode = 3
// , AEND :Opcode = 4
// , AFUNCDATA :Opcode = 5
// , AJMP :Opcode = 6
// , ANOP :Opcode = 7
// , APCALIGN :Opcode = 8
// , APCDATA :Opcode = 9
// , ARET :Opcode = 10
// , AGETCALLERPC :Opcode = 11
// , ATEXT :Opcode = 12
// , AUNDEF :Opcode = 13
// export function assemblePkg(pkg :ir.Pkg, c :Config) {
// for (let f of pkg.funs) {
// let fun = Fun.gen(f, c)
// }
// }
// // In-development covm instruction map, mapping IR op => Native op
// // We start beyond the generic op IDs, so we can use generic op IDs verbatim
// // for now, while developing this thing.
// let nextCovmInstrNum :Opcode = 0x1000
// const OP_JUMP = nextCovmInstrNum++
// const OP_RET = nextCovmInstrNum++
// const OP_BR = nextCovmInstrNum++
// const covmInstrMap :Opcode[] = new Array<Opcode>(irops.OpcodeMax)
// covmInstrMap[irops.CovmMOV32const] = nextCovmInstrNum++
// covmInstrMap[irops.CovmLoad8] = nextCovmInstrNum++
// covmInstrMap[irops.CovmLoad16] = nextCovmInstrNum++
// covmInstrMap[irops.CovmLoad32] = nextCovmInstrNum++
// covmInstrMap[irops.CovmLoad64] = nextCovmInstrNum++
// covmInstrMap[irops.CovmStore8] = nextCovmInstrNum++
// covmInstrMap[irops.CovmStore16] = nextCovmInstrNum++
// covmInstrMap[irops.CovmStore32] = nextCovmInstrNum++
// covmInstrMap[irops.CovmStore64] = nextCovmInstrNum++
// covmInstrMap[irops.CovmADD32] = nextCovmInstrNum++
// covmInstrMap[irops.CovmADD32const] = nextCovmInstrNum++
// covmInstrMap[irops.CovmADD64] = nextCovmInstrNum++
// covmInstrMap[irops.CovmADD32] = nextCovmInstrNum++
// covmInstrMap[irops.CovmADD32const] = nextCovmInstrNum++
// covmInstrMap[irops.CovmADD64] = nextCovmInstrNum++
// covmInstrMap[irops.CovmMUL32] = nextCovmInstrNum++
// covmInstrMap[irops.CovmCALL] = nextCovmInstrNum++
// covmInstrMap[irops.CovmLowNilCheck] = nextCovmInstrNum++
// covmInstrMap[irops.CovmZeroLarge] = nextCovmInstrNum++ | the_stack |
import { useApi } from '@backstage/core-plugin-api';
import { useAsync, useAsyncFn } from 'react-use';
import React from 'react';
import { CalverTagParts } from '../../../helpers/tagParts/getCalverTagParts';
import { getPatchCommitSuffix } from '../helpers/getPatchCommitSuffix';
import { GetRecentCommitsResultSingle } from '../../../api/GitReleaseClient';
import { gitReleaseManagerApiRef } from '../../../api/serviceApiRef';
import { GitReleaseManagerError } from '../../../errors/GitReleaseManagerError';
import { Project } from '../../../contexts/ProjectContext';
import { SemverTagParts } from '../../../helpers/tagParts/getSemverTagParts';
import { useResponseSteps } from '../../../hooks/useResponseSteps';
export interface UsePatchDryRun {
bumpedTag: string;
releaseBranchName: string;
project: Project;
tagParts: NonNullable<CalverTagParts | SemverTagParts>;
}
const PatchDryRunMessage = ({ message }: { message: string }) => (
<>
<strong>[Patch dry run]</strong> {message}
</>
);
// Inspiration: https://stackoverflow.com/questions/53859199/how-to-cherry-pick-through-githubs-api
export function usePatchDryRun({
bumpedTag,
releaseBranchName,
project,
tagParts,
}: UsePatchDryRun) {
const pluginApiClient = useApi(gitReleaseManagerApiRef);
const { responseSteps, addStepToResponseSteps, asyncCatcher, abortIfError } =
useResponseSteps();
const tempPatchBranchName = `${releaseBranchName}-backstage-grm-patch-dry-run`;
/**
* (1) Get the release branch's most recent commit
*/
const [latestCommitOnReleaseBranchRes, run] = useAsyncFn(
async (selectedPatchCommit: GetRecentCommitsResultSingle) => {
try {
await pluginApiClient.deleteRef({
owner: project.owner,
repo: project.repo,
ref: `heads/${tempPatchBranchName}`,
});
} catch (error: any) {
if (error.message !== 'Reference does not exist') {
throw error;
}
}
const { commit: latestCommit } = await pluginApiClient
.getCommit({
owner: project.owner,
repo: project.repo,
ref: releaseBranchName,
})
.catch(asyncCatcher);
addStepToResponseSteps({
message: (
<PatchDryRunMessage
message={`Fetched latest commit from "${releaseBranchName}"`}
/>
),
});
return {
latestCommit,
selectedPatchCommit,
};
},
);
/**
* (2) Create temporary patch branch based on release branch's most recent sha
* to test if programmatic cherry pick patching is possible
*/
const createTempPatchBranchRes = useAsync(async () => {
abortIfError(latestCommitOnReleaseBranchRes.error);
if (!latestCommitOnReleaseBranchRes.value) return undefined;
const { reference: createdReleaseBranch } = await pluginApiClient
.createRef({
owner: project.owner,
repo: project.repo,
sha: latestCommitOnReleaseBranchRes.value.latestCommit.sha,
ref: `refs/heads/${tempPatchBranchName}`,
})
.catch(error => {
if (error?.body?.message === 'Reference already exists') {
throw new GitReleaseManagerError(
`Branch "${tempPatchBranchName}" already exists: .../tree/${tempPatchBranchName}`,
);
}
throw error;
})
.catch(asyncCatcher);
addStepToResponseSteps({
message: (
<PatchDryRunMessage
message={`Created temporary patch dry run branch "${tempPatchBranchName}"`}
/>
),
});
return {
...createdReleaseBranch,
selectedPatchCommit:
latestCommitOnReleaseBranchRes.value.selectedPatchCommit,
};
}, [
latestCommitOnReleaseBranchRes.value,
latestCommitOnReleaseBranchRes.error,
]);
/**
* (3) Here is the branch we want to cherry-pick to:
* > branch = GET /repos/$owner/$repo/branches/$branchName
* > branchSha = branch.commit.sha
* > branchTree = branch.commit.commit.tree.sha
*/
const tempPatchBranchRes = useAsync(async () => {
abortIfError(createTempPatchBranchRes.error);
if (!createTempPatchBranchRes.value) return undefined;
const { branch: releaseBranch } = await pluginApiClient
.getBranch({
owner: project.owner,
repo: project.repo,
branch: tempPatchBranchName,
})
.catch(asyncCatcher);
addStepToResponseSteps({
message: (
<PatchDryRunMessage
message={`Fetched release branch "${releaseBranch.name}"`}
/>
),
});
return {
releaseBranch,
selectedPatchCommit: createTempPatchBranchRes.value.selectedPatchCommit,
};
}, [createTempPatchBranchRes.value, createTempPatchBranchRes.error]);
/**
* (4) Create a temporary commit on the branch, which extends as a sibling of
* the commit we want but contains the current tree of the target branch:
* > parentSha = commit.parents.head // first parent -- there should only be one
* > tempCommit = POST /repos/$owner/$repo/git/commits { "message": "temp", "tree": branchTree, "parents": [parentSha] }
*/
const tempCommitRes = useAsync(async () => {
abortIfError(tempPatchBranchRes.error);
if (!tempPatchBranchRes.value) return undefined;
const { commit: tempCommit } = await pluginApiClient
.createCommit({
owner: project.owner,
repo: project.repo,
message: `Temporary commit for patch ${tagParts.patch}`,
parents: [
tempPatchBranchRes.value.selectedPatchCommit.firstParentSha ?? '',
],
tree: tempPatchBranchRes.value.releaseBranch.commit.commit.tree.sha,
})
.catch(asyncCatcher);
addStepToResponseSteps({
message: <PatchDryRunMessage message="Created temporary commit" />,
});
return {
...tempCommit,
};
}, [tempPatchBranchRes.value, tempPatchBranchRes.error]);
/**
* (5) Now temporarily force the branch over to that commit:
* > PATCH /repos/$owner/$repo/git/refs/heads/$refName { sha = tempCommit.sha, force = true }
*/
const forceBranchRes = useAsync(async () => {
abortIfError(tempCommitRes.error);
if (!tempCommitRes.value) return undefined;
await pluginApiClient
.updateRef({
owner: project.owner,
repo: project.repo,
sha: tempCommitRes.value.sha,
ref: `heads/${tempPatchBranchName}`,
force: true,
})
.catch(asyncCatcher);
addStepToResponseSteps({
message: (
<PatchDryRunMessage
message={`Forced branch "${tempPatchBranchName}" to temporary commit "${tempCommitRes.value.sha}"`}
/>
),
});
return {
trigger: 'next step 🚀 ',
};
}, [tempCommitRes.value, tempCommitRes.error]);
/**
* (6) Merge the commit we want into this mess:
* > merge = POST /repos/$owner/$repo/merges { "base": branchName, "head": commit.sha }
*/
const mergeRes = useAsync(async () => {
abortIfError(forceBranchRes.error);
if (!forceBranchRes.value || !tempPatchBranchRes.value) return undefined;
const { merge } = await pluginApiClient
.merge({
owner: project.owner,
repo: project.repo,
base: tempPatchBranchName,
head: tempPatchBranchRes.value.selectedPatchCommit.sha,
})
.catch(async error => {
if (error?.message === 'Merge conflict') {
try {
await pluginApiClient.deleteRef({
owner: project.owner,
repo: project.repo,
ref: `heads/${tempPatchBranchName}`,
});
} catch (_error) {
// swallow
}
throw new GitReleaseManagerError(
'Patching failed due to merge conflict. Will attempt to delete temporary patch dry run branch. Manual patching is recommended.',
);
}
throw error;
})
.catch(asyncCatcher);
addStepToResponseSteps({
message: (
<PatchDryRunMessage
message={`Merged temporary commit into "${tempPatchBranchName}"`}
/>
),
});
return {
...merge,
};
}, [forceBranchRes.value, forceBranchRes.error]);
/**
* (7) Now that we know what the tree should be, create the cherry-pick commit.
* Note that branchSha is the original from up at the top.
* > cherry = POST /repos/$owner/$repo/git/commits { "message": "looks good!", "tree": mergeTree, "parents": [branchSha] }
*/
const cherryPickRes = useAsync(async () => {
abortIfError(mergeRes.error);
if (!mergeRes.value || !tempPatchBranchRes.value) return undefined;
const releaseBranchSha = tempPatchBranchRes.value.releaseBranch.commit.sha;
const {
commit: { message },
sha: commitSha,
} = tempPatchBranchRes.value.selectedPatchCommit;
const { commit: cherryPickCommit } = await pluginApiClient.createCommit({
owner: project.owner,
repo: project.repo,
message: `[patch (dry run) ${bumpedTag}] ${message}
${getPatchCommitSuffix({ commitSha })}`,
parents: [releaseBranchSha],
tree: mergeRes.value.commit.tree.sha,
});
addStepToResponseSteps({
message: (
<PatchDryRunMessage
message={`Cherry-picked patch commit to "${releaseBranchSha}"`}
/>
),
});
return {
...cherryPickCommit,
};
}, [mergeRes.value, mergeRes.error]);
/**
* (8) Replace the temp commit with the real commit:
* > PATCH /repos/$owner/$repo/git/refs/heads/$refName { sha = cherry.sha, force = true }
*/
const updatedRefRes = useAsync(async () => {
abortIfError(cherryPickRes.error);
if (!cherryPickRes.value) return undefined;
const { reference: updatedReference } = await pluginApiClient
.updateRef({
owner: project.owner,
repo: project.repo,
ref: `heads/${tempPatchBranchName}`,
sha: cherryPickRes.value.sha,
force: true,
})
.catch(asyncCatcher);
addStepToResponseSteps({
message: (
<PatchDryRunMessage
message={`Updated reference "${updatedReference.ref}"`}
/>
),
});
return {
...updatedReference,
};
}, [cherryPickRes.value, cherryPickRes.error]);
/**
* (9) Delete temp patch branch
*/
const deleteTempPatchBranchRes = useAsync(async () => {
abortIfError(updatedRefRes.error);
if (!updatedRefRes.value) return undefined;
const { success: deletedReferenceSuccess } =
await pluginApiClient.deleteRef({
owner: project.owner,
repo: project.repo,
ref: `heads/${tempPatchBranchName}`,
});
addStepToResponseSteps({
message: (
<PatchDryRunMessage
message={`Deleted temporary patch prep branch "${tempPatchBranchName}"`}
/>
),
});
return {
deletedReferenceSuccess,
};
}, [updatedRefRes.value, updatedRefRes.error]);
const TOTAL_PATCH_PREP_STEPS = 9;
return {
TOTAL_PATCH_PREP_STEPS,
run,
runInvoked: Boolean(
deleteTempPatchBranchRes.loading ||
deleteTempPatchBranchRes.value ||
deleteTempPatchBranchRes.error,
),
lastCallRes: deleteTempPatchBranchRes,
responseSteps,
addStepToResponseSteps,
asyncCatcher,
abortIfError,
selectedPatchCommit: latestCommitOnReleaseBranchRes.value
?.selectedPatchCommit as GetRecentCommitsResultSingle,
};
} | the_stack |
import R from 'ramda';
import fs from 'fs-extra';
import { compact } from 'ramda-adjunct';
import { BitId, BitIds } from '../../bit-id';
import Component from '../component/consumer-component';
import { COMPONENT_ORIGINS, SUB_DIRECTORIES_GLOB_PATTERN } from '../../constants';
import ComponentMap from '../bit-map/component-map';
import { pathRelativeLinux } from '../../utils';
import Consumer from '../consumer';
import { pathNormalizeToLinux } from '../../utils/path';
import getNodeModulesPathOfComponent from '../../utils/bit/component-node-modules-path';
import { PathLinux, PathOsBasedAbsolute, PathRelative } from '../../utils/path';
import logger from '../../logger/logger';
import JSONFile from './sources/json-file';
import npmRegistryName from '../../utils/bit/npm-registry-name';
import componentIdToPackageName from '../../utils/bit/component-id-to-package-name';
import PackageJsonFile from './package-json-file';
import searchFilesIgnoreExt from '../../utils/fs/search-files-ignore-ext';
import ComponentVersion from '../../scope/component-version';
import BitMap from '../bit-map/bit-map';
import ShowDoctorError from '../../error/show-doctor-error';
import PackageJson from './package-json';
/**
* Add components as dependencies to root package.json
*/
export async function addComponentsToRoot(consumer: Consumer, components: Component[]): Promise<void> {
const componentsToAdd = components.reduce((acc, component) => {
const componentMap = consumer.bitMap.getComponent(component.id);
if (componentMap.origin !== COMPONENT_ORIGINS.IMPORTED) return acc;
if (!componentMap.rootDir) {
throw new ShowDoctorError(`rootDir is missing from an imported component ${component.id.toString()}`);
}
const locationAsUnixFormat = convertToValidPathForPackageManager(componentMap.rootDir);
const packageName = componentIdToPackageName(component.id, component.bindingPrefix, component.defaultScope);
acc[packageName] = locationAsUnixFormat;
return acc;
}, {});
if (R.isEmpty(componentsToAdd)) return;
await _addDependenciesPackagesIntoPackageJson(consumer.getPath(), componentsToAdd);
}
/**
* Add given components with their versions to root package.json
*/
export async function addComponentsWithVersionToRoot(consumer: Consumer, componentsVersions: ComponentVersion[]) {
const componentsToAdd = R.fromPairs(
componentsVersions.map(({ component, version }) => {
const packageName = componentIdToPackageName(component.toBitId(), component.bindingPrefix);
return [packageName, version];
})
);
await _addDependenciesPackagesIntoPackageJson(consumer.getPath(), componentsToAdd);
}
export async function changeDependenciesToRelativeSyntax(
consumer: Consumer,
components: Component[],
dependencies: Component[]
): Promise<JSONFile[]> {
const dependenciesIds = BitIds.fromArray(dependencies.map(dependency => dependency.id));
const updateComponentPackageJson = async (component: Component): Promise<JSONFile | null | undefined> => {
const componentMap = consumer.bitMap.getComponent(component.id);
const componentRootDir = componentMap.rootDir;
if (!componentRootDir) return null;
const packageJsonFile = await PackageJsonFile.load(consumer.getPath(), componentRootDir);
if (!packageJsonFile.fileExist) return null; // if package.json doesn't exist no need to update anything
const devDeps = getPackages(component.devDependencies.getAllIds(), componentMap);
const extensionDeps = getPackages(component.extensions.extensionsBitIds, componentMap);
packageJsonFile.addDependencies(getPackages(component.dependencies.getAllIds(), componentMap));
packageJsonFile.addDevDependencies({ ...devDeps, ...extensionDeps });
return packageJsonFile.toVinylFile();
};
const packageJsonFiles = await Promise.all(components.map(component => updateComponentPackageJson(component)));
// @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
return packageJsonFiles.filter(file => file);
function getPackages(deps: BitIds, componentMap: ComponentMap) {
return deps.reduce((acc, dependencyId: BitId) => {
const dependencyIdStr = dependencyId.toStringWithoutVersion();
if (dependenciesIds.searchWithoutVersion(dependencyId)) {
const dependencyComponent = dependencies.find(d => d.id.isEqualWithoutVersion(dependencyId));
if (!dependencyComponent) {
throw new Error('getDependenciesAsPackages, dependencyComponent is missing');
}
const dependencyComponentMap = consumer.bitMap.getComponentIfExist(dependencyComponent.id);
// @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
const dependencyPackageValue = getPackageDependencyValue(dependencyIdStr, componentMap, dependencyComponentMap);
if (dependencyPackageValue) {
const packageName = componentIdToPackageName(
dependencyId,
dependencyComponent.bindingPrefix,
dependencyComponent.defaultScope
);
acc[packageName] = dependencyPackageValue;
}
}
return acc;
}, {});
}
}
export function preparePackageJsonToWrite(
bitMap: BitMap,
component: Component,
bitDir: string,
override = true,
writeBitDependencies = false, // e.g. when it's a capsule
excludeRegistryPrefix?: boolean,
packageManager?: string
): { packageJson: PackageJsonFile; distPackageJson: PackageJsonFile | null | undefined } {
logger.debug(`package-json.preparePackageJsonToWrite. bitDir ${bitDir}. override ${override.toString()}`);
const getBitDependencies = (dependencies: BitIds) => {
if (!writeBitDependencies) return {};
return dependencies.reduce((acc, depId: BitId) => {
const packageDependency = getPackageDependency(bitMap, depId, component.id);
const packageName = componentIdToPackageName(depId, component.bindingPrefix, component.defaultScope);
acc[packageName] = packageDependency;
return acc;
}, {});
};
const bitDependencies = getBitDependencies(component.dependencies.getAllIds());
const bitDevDependencies = getBitDependencies(component.devDependencies.getAllIds());
const bitExtensionDependencies = getBitDependencies(component.extensions.extensionsBitIds);
const packageJson = PackageJsonFile.createFromComponent(bitDir, component, excludeRegistryPrefix);
const main = pathNormalizeToLinux(component.dists.calculateMainDistFile(component.mainFile));
packageJson.addOrUpdateProperty('main', main);
const addDependencies = (packageJsonFile: PackageJsonFile) => {
packageJsonFile.addDependencies(bitDependencies);
packageJsonFile.addDevDependencies({
...bitDevDependencies,
...bitExtensionDependencies
});
};
packageJson.setPackageManager(packageManager);
addDependencies(packageJson);
let distPackageJson;
if (!component.dists.isEmpty() && !component.dists.areDistsInsideComponentDir) {
const distRootDir = component.dists.distsRootDir;
if (!distRootDir) throw new Error('component.dists.distsRootDir is not defined yet');
distPackageJson = PackageJsonFile.createFromComponent(distRootDir, component, excludeRegistryPrefix);
const distMainFile = searchFilesIgnoreExt(component.dists.get(), component.mainFile, 'relative');
distPackageJson.addOrUpdateProperty('main', component.dists.getMainDistFile() || distMainFile);
addDependencies(distPackageJson);
}
return { packageJson, distPackageJson };
}
export async function updateAttribute(
consumer: Consumer,
componentDir: PathRelative,
attributeName: string,
attributeValue: string
): Promise<void> {
const packageJsonFile = await PackageJsonFile.load(consumer.getPath(), componentDir);
if (!packageJsonFile.fileExist) return; // package.json doesn't exist, that's fine, no need to update anything
packageJsonFile.addOrUpdateProperty(attributeName, attributeValue);
await packageJsonFile.write();
}
/**
* Adds workspace array to package.json - only if user wants to work with yarn workspaces
*/
export async function addWorkspacesToPackageJson(consumer: Consumer, customImportPath: string | null | undefined) {
if (
consumer.config._manageWorkspaces &&
consumer.config.packageManager === 'yarn' &&
consumer.config._useWorkspaces
) {
const rootDir = consumer.getPath();
const dependenciesDirectory = consumer.config._dependenciesDirectory;
const { componentsDefaultDirectory } = consumer.dirStructure;
await PackageJson.addWorkspacesToPackageJson(
rootDir,
componentsDefaultDirectory + SUB_DIRECTORIES_GLOB_PATTERN,
dependenciesDirectory + SUB_DIRECTORIES_GLOB_PATTERN,
customImportPath ? consumer.getPathRelativeToConsumer(customImportPath) : customImportPath
);
}
}
export async function removeComponentsFromWorkspacesAndDependencies(consumer: Consumer, componentIds: BitIds) {
const rootDir = consumer.getPath();
if (
consumer.config._manageWorkspaces &&
consumer.config.packageManager === 'yarn' &&
consumer.config._useWorkspaces
) {
const dirsToRemove = componentIds.map(id => consumer.bitMap.getComponent(id, { ignoreVersion: true }).rootDir);
if (dirsToRemove && dirsToRemove.length) {
const dirsToRemoveWithoutEmpty = compact(dirsToRemove);
await PackageJson.removeComponentsFromWorkspaces(rootDir, dirsToRemoveWithoutEmpty);
}
}
await PackageJson.removeComponentsFromDependencies(
rootDir, // @todo: fix. the registryPrefix should be retrieved from the component.
consumer.config._bindingPrefix || npmRegistryName(),
componentIds.map(id => id.toStringWithoutVersion())
);
await removeComponentsFromNodeModules(consumer, componentIds);
}
async function _addDependenciesPackagesIntoPackageJson(dir: PathOsBasedAbsolute, dependencies: Record<string, any>) {
const packageJsonFile = await PackageJsonFile.load(dir);
packageJsonFile.addDependencies(dependencies);
await packageJsonFile.write();
}
async function removeComponentsFromNodeModules(consumer: Consumer, componentIds: BitIds) {
logger.debug(`removeComponentsFromNodeModules: ${componentIds.map(c => c.toString()).join(', ')}`);
// @todo: fix. the registryPrefix should be retrieved from the component.
const registryPrefix = consumer.config._bindingPrefix || npmRegistryName();
// paths without scope name, don't have a symlink in node-modules
const pathsToRemove = componentIds
.map(id => {
return id.scope ? getNodeModulesPathOfComponent(registryPrefix, id) : null;
})
.filter(a => a); // remove null
logger.debug(`deleting the following paths: ${pathsToRemove.join('\n')}`);
// $FlowFixMe nulls were removed in the previous filter function
// @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
return Promise.all(pathsToRemove.map(componentPath => fs.remove(consumer.toAbsolutePath(componentPath))));
}
export function convertToValidPathForPackageManager(pathStr: PathLinux): string {
const prefix = 'file:'; // it works for both, Yarn and NPM
return prefix + (pathStr.startsWith('.') ? pathStr : `./${pathStr}`);
}
/**
* Only imported components should be saved with relative path in package.json
* If a component is nested or imported as a package dependency, it should be saved with the version
* If a component is authored, no need to save it as a dependency of the imported component because
* the root package.json takes care of it already.
*/
function getPackageDependencyValue(
dependencyId: BitId,
parentComponentMap: ComponentMap,
dependencyComponentMap?: ComponentMap | null | undefined,
capsuleMap?: any
): string | null | undefined {
if (capsuleMap && capsuleMap[dependencyId.toString()]) {
return capsuleMap[dependencyId.toString()].wrkdir;
}
if (!dependencyComponentMap || dependencyComponentMap.origin === COMPONENT_ORIGINS.NESTED) {
return dependencyId.version;
}
if (dependencyComponentMap.origin === COMPONENT_ORIGINS.AUTHORED) {
return null;
}
const dependencyRootDir = dependencyComponentMap.rootDir;
if (!dependencyRootDir) {
throw new Error(`rootDir is missing from an imported component ${dependencyId.toString()}`);
}
if (!parentComponentMap.rootDir) throw new Error('rootDir is missing from an imported component');
const rootDirRelative = pathRelativeLinux(parentComponentMap.rootDir, dependencyRootDir);
return convertToValidPathForPackageManager(rootDirRelative);
}
function getPackageDependency(bitMap: BitMap, dependencyId: BitId, parentId: BitId): string | null | undefined {
const parentComponentMap = bitMap.getComponent(parentId);
const dependencyComponentMap = bitMap.getComponentIfExist(dependencyId);
return getPackageDependencyValue(dependencyId, parentComponentMap, dependencyComponentMap);
} | the_stack |
import EventEmitter from 'eventemitter3';
import XHRLoader from './XHRLoader';
import M3U8Parser from '../Parser/M3u8Parser';
import LoaderEvent from './LoaderEvent';
import computeReloadInterval from '../Utils/computeReloadInterval';
import getGlobal from '../Utils/getGlobalObject';
import Level from '../Parser/Level';
import { AudioGroup } from '../Interfaces/Media-playlist';
import {
PlaylistLevelType,
SingleLevels,
XhrLoaderResponse,
FragLoaderContext,
LoaderConfiguration,
LoaderCallbacks,
XhrLoaderStats,
ErrorData
} from '../Interfaces/Loader';
import MediaConfig from '../Interfaces/MediaConfig';
import Logger from '../Utils/Logger';
const GlobalEnvironment = getGlobal();
enum PlaylistContextType {
'MANIFEST' = 'manifest',
'LEVEL' = 'level',
'AUDIO_TRACK' = 'audioTrack',
'SUBTITLE_TRACK' = 'subtitleTrack'
}
export default class PlaylistLoader {
private _emitter: EventEmitter = new EventEmitter()
/**
* 是否中断请求
*/
private _requestAbort: boolean = false
/**
* 拉直播M3U8的定时器
*/
private timer: number = 0
/**
* m3u8地址
*/
public url: string
/**
* 请求m3u8地址的配置
*/
public dataSource: MediaConfig
/**
* m3u8解析返回数据
*/
private currentPlaylist: Level | null = null
/**
* 最新的m3u8文档内容
*/
private lastestM3U8Content: string = ''
private Tag: string = 'PlayListLoader';
constructor(dataSource: MediaConfig) {
this.dataSource = dataSource;
this.url = dataSource.url;
}
/**
* 绑定事件
* @param { String } event
* @param { Function } listener
*/
on(event: string, listener: EventEmitter.ListenerFn): void {
this._emitter.addListener(event, listener);
}
/**
* 取消绑定事件
* @param { String } event
* @param { Function } listener
*/
off(event: string, listener: EventEmitter.ListenerFn): void {
this._emitter.removeListener(event, listener);
}
/**
* 初始化XHR对象, 加载M3U8文件;
*/
load() {
/**
* 加载m3u8文件配置参数
*/
const loaderConfig: LoaderConfiguration = {
maxRetry: 2,
maxRetryDelay: 1000,
retryDelay: 1000,
timeout: 10000
};
const loaderCallbacks: LoaderCallbacks<FragLoaderContext> = {
onSuccess: this.loadSuccess.bind(this),
onError: this.loadError.bind(this),
onTimeout: this.loadTimeout.bind(this)
};
const context: FragLoaderContext = {
url: this.url,
type: PlaylistContextType.MANIFEST,
level: 0,
id: null,
responseType: 'text'
};
const xhrLoader = new XHRLoader();
xhrLoader.load(context, loaderConfig, loaderCallbacks);
}
/**
* 停止,直播暂时没实现暂停
*/
stop() {}
/**
* 加载M3U8文件成功
*/
loadSuccess(
response: XhrLoaderResponse,
stats: XhrLoaderStats,
context: FragLoaderContext,
networkDetails:any = null
): void {
if(typeof response.data !== 'string') {
throw new Error('expected responseType of "text" for PlaylistLoader');
}
const string: string = response.data;
this.lastestM3U8Content = string;
stats.tload = performance.now();
if(string.indexOf('#EXTM3U') !== 0) {
this._handleManifestParsingError(
response,
context,
'no EXTM3U delimiter',
networkDetails
);
return;
}
if(string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {
this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
} else {
this._handleMasterPlaylist(response, stats, context, networkDetails);
}
}
/**
* 取消loader, 清除定时器, 移除自身绑定的事件
*/
abort() {
this._requestAbort = true;
clearInterval(this.timer);
this._emitter && this._emitter.removeAllListeners();
delete this._emitter;
delete this.dataSource;
delete this.currentPlaylist;
Logger.info(this.Tag, `${this.Tag} has been abort`);
}
/**
* 销毁功能
*/
destroy() {
this.abort();
Logger.info(this.Tag, `${this.Tag} has been destroy`);
}
/**
* 处理下载的M3U8文件(普通M3U8 ts文件列表)
*/
_handleTrackOrLevelPlaylist(
response: XhrLoaderResponse,
stats: XhrLoaderStats,
context: FragLoaderContext,
networkDetails: any
): void {
const { id, level, type } = context;
const url: string = this._getResponseUrl(response, context);
const levelUrlId: number = Number.isFinite(id as number) ? (id as number) : 0;
const levelId: number = Number.isFinite(level as number) ? (level as number) : levelUrlId;
const levelType: PlaylistLevelType = this.mapContextToLevelType(context);
const levelDetails: Level = M3U8Parser.parseLevelPlaylist(
response.data as string,
url,
levelId,
levelType,
levelUrlId
);
(levelDetails as any).tload = stats.tload;
if(type === PlaylistContextType.MANIFEST) {
const singleLevel = {
url,
details: levelDetails
};
this._emitter.emit(LoaderEvent.MANIFEST_PARSED, {
type: 'levelPlaylist',
levels: [singleLevel],
audioTracks: [],
url,
stats,
networkDetails
});
if(levelDetails.live === true && this._requestAbort === false) {
const reloadInterval = computeReloadInterval(
this.currentPlaylist,
levelDetails,
stats.trequest
);
this.timer = GlobalEnvironment.setTimeout(() => {
this.load();
}, reloadInterval);
}
this.currentPlaylist = levelDetails;
}
}
/**
* 处理下载的M3U8文件(清晰度选择)
*/
_handleMasterPlaylist(
response: XhrLoaderResponse,
stats: XhrLoaderStats,
context: FragLoaderContext,
networkDetails: any
): void {
const string: string = response.data as string;
const url: string = this._getResponseUrl(response, context);
const levels: SingleLevels[] = M3U8Parser.parseMasterPlaylist(string, url);
if(!levels.length) {
this._handleManifestParsingError(
response,
context,
'no level found in manifest',
networkDetails
);
return;
}
// multi level playlist, parse level info
const audioGroups: Array<AudioGroup> = levels.map((level) => ({
id: level.attrs.AUDIO,
codec: level.audioCodec
}));
const audioTracks = M3U8Parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
const subtitles = M3U8Parser.parseMasterPlaylistMedia(string, url, 'SUBTITLES');
if(audioTracks.length) {
// check if we have found an audio track embedded in main playlist (audio track without URI attribute)
let embeddedAudioFound = false;
audioTracks.forEach((audioTrack) => {
if(!audioTrack.url) {
embeddedAudioFound = true;
}
});
// if no embedded audio track defined, but audio codec signaled in quality level,
// we need to signal this main audio track this could happen with playlists with
// alt audio rendition in which quality levels (main)
// contains both audio+video. but with mixed audio track not signaled
if(embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
Logger.log(this.Tag, 'audio codec signaled in quality level, but no embedded audio track signaled, create one');
audioTracks.unshift({
type: 'main',
name: 'main',
default: false,
autoselect: false,
forced: false,
id: 0
});
}
}
levels.sort((a, b) => a.bitrate - b.bitrate);
this._emitter.emit(LoaderEvent.MANIFEST_PARSED, {
type: 'masterPlaylist',
levels,
audioTracks,
subtitles,
url,
stats,
networkDetails,
});
}
/**
* 处理解析M3U8文件解析错误
* @param response
* @param context
* @param reason
* @param networkDetails
* @private
*/
_handleManifestParsingError(
response: XhrLoaderResponse,
context: FragLoaderContext,
reason: string,
networkDetails: any
) {
this._emitter.emit(LoaderEvent.PARSE_ERROR, {
url: response.url,
reason,
fatal: true,
networkDetails
});
}
// 获得请求响应的URL
_getResponseUrl(response: XhrLoaderResponse, context: FragLoaderContext) {
let { url } = response;
// responseURL not supported on some browsers (it is used to detect URL redirection)
// data-uri mode also not supported (but no need to detect redirection)
if(url === undefined || url.indexOf('data:') === 0) {
// fallback to initial URL
({ url } = context);
}
return url;
}
mapContextToLevelType(context: FragLoaderContext): PlaylistLevelType {
const { type } = context;
switch(type) {
case PlaylistContextType.AUDIO_TRACK:
return PlaylistLevelType.AUDIO;
case PlaylistContextType.SUBTITLE_TRACK:
return PlaylistLevelType.SUBTITLE;
default:
return PlaylistLevelType.MAIN;
}
}
loadError(response: ErrorData, context: FragLoaderContext, xhr: XMLHttpRequest | null): void {
response.text = 'playlist not found';
this._emitter.emit(LoaderEvent.LOADING_ERROR, {
response,
context,
xhr
});
}
loadTimeout(
stats: XhrLoaderStats,
context: FragLoaderContext,
xhr: XMLHttpRequest | null
): void {
stats.text = 'download playlist timeout';
this._emitter.emit(LoaderEvent.LOADIND_TIMEOUT, {
stats,
context,
xhr
});
}
} | the_stack |
import { removeChildElements, refreshCanvasBarcode, exportAsImage } from '../barcode/utility/barcode-util';
import { Complex, Property, Component, INotifyPropertyChanged, L10n, Event, EmitType } from '@syncfusion/ej2-base';
import { ErrorCorrectionLevel, QRCodeVersion, RenderingMode, BarcodeEvent, BarcodeExportType } from '../barcode/enum/enum';
import { DisplayTextModel } from '../barcode/primitives/displaytext-model';
import { MarginModel } from '../barcode/primitives/margin-model';
import { DisplayText } from '../barcode/primitives/displaytext';
import { Margin } from '../barcode/primitives/margin';
import { QRCodeGeneratorModel } from './qrcode-model';
import { BarcodeRenderer } from '../barcode/rendering/renderer';
import { QRCode } from './qr-code-util';
import { ValidateEvent } from '../barcode';
/**
* Represents the Qrcode control
* ```
*/
export class QRCodeGenerator extends Component<HTMLElement> implements INotifyPropertyChanged {
/**
* Constructor for creating the widget
*
* @param {QRCodeGeneratorModel} options - Provide the instance.
* @param {HTMLElement} element - Provide the element .
*/
constructor(options?: QRCodeGeneratorModel, element?: HTMLElement | string) {
super(options, <HTMLElement | string>element);
}
/**
* Defines the height of the QR code model.
*
* @default '100%'
*/
@Property('100%')
public height: string | number;
/**
* Defines the width of the QR code model.
*
* @default '100%'
*/
@Property('100%')
public width: string | number;
/**
* Defines the QR code rendering mode.
*
* * SVG - Renders the bar-code objects as SVG elements
* * Canvas - Renders the bar-code in a canvas
*
* @default 'SVG'
*/
@Property('SVG')
public mode: RenderingMode;
/**
* Defines the xDimension of the QR code model.
*
*/
@Property(1)
public xDimension: number;
/**
* Defines the error correction level of the QR code.
*
* @aspDefaultValueIgnore
* @aspNumberEnum
* @default undefined
*/
@Property()
public errorCorrectionLevel: ErrorCorrectionLevel;
/**
* Defines the margin properties for the QR code.
*
* @default ''
*/
@Complex<MarginModel>({}, Margin)
public margin: MarginModel;
/**
* Defines the background color of the QR code.
*
* @default 'white'
*/
@Property('white')
public backgroundColor: string;
/**
* Triggers if you enter any invalid character.
* @event
*/
@Event()
public invalid: EmitType<Object>;
/**
* Defines the forecolor of the QR code.
*
* @default 'black'
*/
@Property('black')
public foreColor: string;
/**
* Defines the text properties for the QR code.
*
* @default ''
*/
@Complex<DisplayTextModel>({}, DisplayText)
public displayText: DisplayTextModel;
/**
* * Defines the version of the QR code.
*
* @aspDefaultValueIgnore
* @aspNumberEnum
* @default undefined
*/
@Property()
public version: QRCodeVersion;
private widthChange: boolean = false;
private heightChange: boolean = false;
private isSvgMode: boolean;
private barcodeRenderer: BarcodeRenderer;
/**
* Defines the type of barcode to be rendered.
*
* @default undefined
*/
@Property(undefined)
public value: string;
/** @private */
public localeObj: L10n;
/** @private */
// eslint-disable-next-line
private defaultLocale: Object;
private barcodeCanvas: HTMLElement;
/**
* Renders the barcode control .
*
* @returns {void}
*/
public render(): void {
this.notify('initial-load', {});
/**
* Used to load context menu
*/
this.trigger('load');
this.notify('initial-end', {});
this.renderElements();
this.renderComplete();
}
private triggerEvent(eventName: BarcodeEvent, message: string): void {
const arg: ValidateEvent = {
message: message
};
this.trigger(BarcodeEvent[eventName], arg);
}
private renderElements(): void {
const barCode: QRCode = new QRCode();
barCode.text = this.value;
barCode.XDimension = this.xDimension;
barCode.mIsUserMentionedErrorCorrectionLevel = (this.errorCorrectionLevel !== undefined) ? true : false;
barCode.mErrorCorrectionLevel = (this.errorCorrectionLevel !== undefined) ? this.errorCorrectionLevel : ErrorCorrectionLevel.Medium;
barCode.version = (this.version !== undefined) ? this.version : undefined;
barCode.mIsUserMentionedVersion = (this.version !== undefined) ? true : false;
const mode: boolean = (this.mode === 'SVG') ? true : false;
const validInput: boolean = barCode.draw(
this.value, this.barcodeCanvas, this.element.offsetHeight as number,
this.element.offsetWidth as number, this.margin, this.displayText, mode, this.foreColor);
if (this.mode === 'Canvas') {
(this.barcodeCanvas as HTMLCanvasElement).getContext('2d').setTransform(1, 0, 0, 1, 0, 0);
(this.barcodeCanvas as HTMLCanvasElement).getContext('2d').scale(1.5, 1.5);
}
if (!validInput) {
const encoding: string = 'Invalid Input';
this.triggerEvent(BarcodeEvent.invalid, encoding as string);
}
if (this.mode === 'Canvas') {
this.barcodeCanvas.style.transform = 'scale(' + (2 / 3) + ')';
this.barcodeCanvas.style.transformOrigin = '0 0';
}
}
private setCulture(): void {
this.localeObj = new L10n(this.getModuleName(), this.defaultLocale, this.locale);
}
// eslint-disable-next-line
private getElementSize(real: string | number, rulerSize?: number): string {
//this method will return the size of the qrcode
let value: string;
if (real.toString().indexOf('px') > 0 || real.toString().indexOf('%') > 0) {
value = real.toString();
} else {
value = real.toString() + 'px';
}
return value;
}
private initialize(): void {
//Initialize the height of qrcode generator
this.element.style.height = this.getElementSize(this.height);
//Initialize the width of qrcode generator
this.element.style.width = this.getElementSize(this.width);
this.barcodeCanvas = this.barcodeRenderer.renderRootElement(
{
id: this.element.id + 'content',
height: this.mode === 'SVG' ? this.element.offsetHeight : this.element.offsetHeight * 1.5,
width: this.mode === 'SVG' ? this.element.offsetWidth : this.element.offsetWidth * 1.5
},
this.backgroundColor, this.element.offsetWidth, this.element.offsetHeight) as HTMLElement;
this.element.appendChild(this.barcodeCanvas);
}
protected preRender(): void {
this.element.classList.add('e-qrcode');
this.barcodeRenderer = new BarcodeRenderer(this.element.id, this.mode === 'SVG');
this.initialize();
this.initializePrivateVariables();
this.setCulture();
}
/**
* Get the properties to be maintained in the persisted state.
*
* @returns {string} Get the properties to be maintained in the persisted state.
*/
public getPersistData(): string {
const keyEntity: string[] = ['loaded'];
return this.addOnPersist(keyEntity);
}
/**
* Returns the module name of the barcode
*
* @returns {string} Returns the module name of the barcode
*/
public getModuleName(): string {
return 'QRCodeGenerator';
}
/**
* It is used to destroy the Barcode component.
*
* @function destroy
* @returns {void}
*/
public destroy(): void {
this.notify('destroy', {});
super.destroy();
}
private initializePrivateVariables(): void {
this.defaultLocale = {
};
}
/**
* Export the barcode as an image in the specified image type and downloads it in the browser.
*
* @returns {void} Export the barcode as an image in the specified image type and downloads it in the browser.
* @param {string} filename - Specifies the filename of the barcode image to be download.
* @param {BarcodeExportType} barcodeExportType - Defines the format of the barcode to be exported
*/
public exportImage(filename: string, barcodeExportType: BarcodeExportType ): void {
exportAsImage(barcodeExportType, filename, this.element, false, this);
}
/**
* Export the barcode as an image in the specified image type and returns it as base64 string.
*
* @returns {string} Export the barcode as an image in the specified image type and returns it as base64 string.
* @param {BarcodeExportType} barcodeExportType - Defines the format of the barcode to be exported
*/
public exportAsBase64Image(barcodeExportType: BarcodeExportType): Promise<string> {
const returnValue: Promise<string> = exportAsImage(barcodeExportType, '', this.element, true, this);
return returnValue;
}
// eslint-disable-next-line
public onPropertyChanged(newProp: QRCodeGeneratorModel, oldProp: QRCodeGeneratorModel): void {
let width: number | string;
let height: number | string;
if (this.mode === 'Canvas' && newProp.mode !== 'Canvas') {
refreshCanvasBarcode(this, this.barcodeCanvas as HTMLCanvasElement);
} else {
this.barcodeRenderer = removeChildElements(newProp, this.barcodeCanvas, this.mode, this.element.id);
}
if (newProp.width) {
if (this.mode === 'Canvas' && newProp.mode !== 'Canvas') {
this.widthChange = true;
}
width = (this.mode === 'Canvas' && newProp.mode !== 'Canvas') ? (((newProp.width as number) * 1.5)) : newProp.width;
this.barcodeCanvas.setAttribute('width', String(width));
}
if (newProp.height) {
if (this.mode === 'Canvas' && newProp.mode !== 'Canvas') {
this.heightChange = true;
}
height = (this.mode === 'Canvas' && newProp.mode !== 'Canvas') ? (((newProp.height as number) * 1.5)) : newProp.height;
this.barcodeCanvas.setAttribute('height', String(height));
}
for (const prop of Object.keys(newProp)) {
switch (prop) {
case 'width':
this.element.style.width = this.getElementSize(width);
this.barcodeCanvas.setAttribute('width', String(this.element.offsetWidth));
break;
case 'height':
this.element.style.height = this.getElementSize(height);
this.barcodeCanvas.setAttribute('height', String(this.element.offsetHeight));
break;
case 'backgroundColor':
this.barcodeCanvas.setAttribute('style', 'background:' + newProp.backgroundColor);
break;
case 'mode':
this.initialize();
}
}
this.renderElements();
}
} | the_stack |
import { GithubAdapter, LocalAdapter } from '.';
import {
CdmContainerDefinition,
CdmCorpusContext,
CdmCorpusDefinition,
CdmFolderDefinition,
cdmLogCode,
CdmObject,
configObjectType,
StorageAdapterBase
} from '../internal';
import { Logger, enterScope } from '../Utilities/Logging/Logger';
import { StorageUtils } from '../Utilities/StorageUtils';
import { ADLSAdapter } from './ADLSAdapter';
import { CdmStandardsAdapter } from './CdmStandardsAdapter';
import { RemoteAdapter } from './RemoteAdapter';
import { ResourceAdapter } from './ResourceAdapter';
import { using } from "using-statement";
export class StorageManager {
private TAG: string = StorageManager.name;
/**
* @internal
*/
public readonly corpus: CdmCorpusDefinition;
// the map of registered namespace <-> adapters.
public namespaceAdapters: Map<string, StorageAdapterBase>;
/**
* @internal
*/
public namespaceFolders: Map<string, CdmFolderDefinition>;
public defaultNamespace: string;
/**
* Maximum number of documents read concurrently when loading imports.
*/
public get maxConcurrentReads(): number | undefined {
return this.corpus.documentLibrary.concurrentReadLock.permits;
}
/**
* Maximum number of documents read concurrently when loading imports.
*/
public set maxConcurrentReads(value: number | undefined) {
this.corpus.documentLibrary.concurrentReadLock.permits = value;
}
private readonly systemDefinedNamespaces: Set<string>;
private readonly registeredAdapterTypes: Map<string, any>;
/**
* @internal
*/
public get ctx(): CdmCorpusContext {
return this.corpus.ctx;
}
constructor(corpus: CdmCorpusDefinition) {
this.corpus = corpus;
this.namespaceAdapters = new Map<string, StorageAdapterBase>();
this.namespaceFolders = new Map<string, CdmFolderDefinition>();
this.systemDefinedNamespaces = new Set<string>();
this.registeredAdapterTypes = new Map<string, any>([
['cdm-standards', CdmStandardsAdapter.prototype],
['local', LocalAdapter.prototype],
['adls', ADLSAdapter.prototype],
['remote', RemoteAdapter.prototype],
['github', GithubAdapter.prototype]
]);
// set up default adapters
this.mount('local', new LocalAdapter(process.cwd()));
this.mount('cdm', new CdmStandardsAdapter());
this.systemDefinedNamespaces.add('local');
this.systemDefinedNamespaces.add('cdm');
}
/**
* Mounts a namespace to the specified adapter
*/
public mount(namespace: string, adapter: StorageAdapterBase): void {
return using(enterScope(StorageManager.name, this.ctx, this.mount.name), _ => {
if (!namespace) {
Logger.error(this.ctx, this.TAG, this.mount.name, null, cdmLogCode.ErrStorageNullNamespace);
return;
}
if (adapter) {
adapter.ctx = this.ctx;
this.namespaceAdapters.set(namespace, adapter);
const fd: CdmFolderDefinition = new CdmFolderDefinition(this.ctx, '');
fd.corpus = this.corpus;
fd.namespace = namespace;
fd.folderPath = '/';
this.namespaceFolders.set(namespace, fd);
this.systemDefinedNamespaces.delete(namespace);
} else {
Logger.error(this.ctx, this.TAG, this.mount.name, null, cdmLogCode.ErrStorageNullAdapter);
}
});
}
/**
* Mounts the config JSON to the storage manager/corpus.
* @param adapterConfig The adapters config in JSON.
* @param adapterOrDoesReturnErrorList A boolean value that denotes whether we want to return a list of adapters that were not found.
*/
public mountFromConfig(adapterConfig: string, doesReturnErrorList: boolean = false): string[] {
if (!adapterConfig) {
Logger.error(this.ctx, this.TAG, this.mountFromConfig.name, null, cdmLogCode.ErrStorageNullAdapterConfig);
return undefined;
}
let adapterConfigJson = JSON.parse(adapterConfig);
if (adapterConfigJson.appId) {
this.corpus.appId = adapterConfigJson.appId;
}
if (adapterConfigJson.defaultNamespace) {
this.defaultNamespace = adapterConfigJson.defaultNamespace;
}
const unrecognizedAdapters: string[] = [];
for (const item of adapterConfigJson.adapters) {
let nameSpace: string;
// Check whether the namespace exists.
if (item.namespace) {
nameSpace = item.namespace;
} else {
Logger.error(this.ctx, this.TAG, this.mountFromConfig.name, null, cdmLogCode.ErrStorageMissingNamespace);
continue;
}
let configs;
// Check whether the config exists.
if (item.config) {
configs = item.config;
} else {
Logger.error(this.ctx, this.TAG, this.mountFromConfig.name, null, cdmLogCode.ErrStorageMissingJsonConfig, nameSpace);
continue;
}
if (!item.type) {
Logger.error(this.ctx, this.TAG, this.mountFromConfig.name, null, cdmLogCode.ErrStorageMissingTypeJsonConfig, nameSpace);
continue;
}
const adapterType = this.registeredAdapterTypes.get(item.type);
if (!adapterType) {
unrecognizedAdapters.push(item);
} else {
const adapter: StorageAdapterBase = new adapterType.constructor();
adapter.updateConfig(JSON.stringify(configs));
this.mount(nameSpace, adapter);
}
}
return doesReturnErrorList ? unrecognizedAdapters : undefined;
}
/**
* Unmounts a namespace
*/
public unMount(nameSpace: string): boolean {
return using(enterScope(StorageManager.name, this.ctx, this.unMount.name), _ => {
if (!nameSpace) {
Logger.error(this.ctx, this.TAG, this.unMount.name, null, cdmLogCode.ErrStorageNullNamespace);
return false;
}
if (this.namespaceAdapters.has(nameSpace)) {
this.namespaceAdapters.delete(nameSpace);
this.namespaceFolders.delete(nameSpace);
this.systemDefinedNamespaces.delete(nameSpace);
// The special case, use Resource adapter.
if (nameSpace === 'cdm') {
this.mount(nameSpace, new ResourceAdapter());
}
return true;
} else {
Logger.warning(this.ctx, this.TAG, this.unMount.name, null, cdmLogCode.WarnStorageRemoveAdapterFailed, nameSpace);
}
});
}
/**
* @internal
* Allow replacing a storage adapter with another one for testing, leaving folders intact.
*/
public setAdapter(nameSpace: string, adapter: StorageAdapterBase): void {
if (!nameSpace) {
Logger.error(this.ctx, this.TAG, this.setAdapter.name, null, cdmLogCode.ErrStorageNullNamespace);
return;
}
if (adapter) {
this.namespaceAdapters.set(nameSpace, adapter);
} else {
Logger.error(this.ctx, this.TAG, this.setAdapter.name, null, cdmLogCode.ErrStorageNullAdapter);
}
}
/**
* Retrieves the adapter for the specified namespace.
*/
public fetchAdapter(namespace: string): StorageAdapterBase {
if (!namespace) {
Logger.error(this.ctx, this.TAG, this.fetchAdapter.name, null, cdmLogCode.ErrStorageNullNamespace);
return undefined;
}
if (this.namespaceFolders.has(namespace)) {
return this.namespaceAdapters.get(namespace);
}
Logger.error(this.ctx, this.TAG, this.fetchAdapter.name, null, cdmLogCode.ErrStorageAdapterNotFound, namespace);
return undefined;
}
/**
* Given the namespace of a registered storage adapter, returns the root folder containing the sub-folders and documents.
*/
public fetchRootFolder(namespace: string): CdmFolderDefinition {
return using(enterScope(StorageManager.name, this.ctx, this.fetchRootFolder.name), _ => {
if (!namespace) {
Logger.error(this.ctx, this.TAG, this.fetchRootFolder.name, null, cdmLogCode.ErrStorageNullNamespace);
return undefined;
}
let folder: CdmFolderDefinition;
if (this.namespaceFolders.has(namespace)) {
folder = this.namespaceFolders.get(namespace);
} else if (namespace === 'default') {
folder = this.namespaceFolders.get(this.defaultNamespace);
}
if (!folder) {
Logger.error(this.ctx, this.TAG, this.fetchRootFolder.name, null, cdmLogCode.ErrStorageAdapterNotFound, namespace);
}
return folder;
});
}
/**
* Takes a storage adapter domain path, figures out the right adapter to use and then returns a corpus path.
*/
public adapterPathToCorpusPath(adapterPath: string): string {
return using(enterScope(StorageManager.name, this.ctx, this.adapterPathToCorpusPath.name), _ => {
let result: string;
// keep trying adapters until one of them likes what it sees
if (this.namespaceAdapters) {
for (const pair of this.namespaceAdapters) {
if (result === undefined) {
result = pair[1].createCorpusPath(adapterPath);
if (result !== undefined) {
// got one, add the prefix
result = `${pair[0]}:${result}`;
}
}
}
}
if (result === undefined) {
Logger.error(this.ctx, this.TAG, this.adapterPathToCorpusPath.name, null, cdmLogCode.ErrStorageInvalidAdapterPath, adapterPath);
}
return result;
});
}
/**
* Takes a corpus path, figures out the right adapter to use and then returns an adapter domain path.
*/
public corpusPathToAdapterPath(corpusPath: string): string {
return using(enterScope(StorageManager.name, this.ctx, this.corpusPathToAdapterPath.name), _ => {
if (!corpusPath) {
Logger.error(this.ctx, this.TAG, this.corpusPathToAdapterPath.name, null, cdmLogCode.ErrStorageNullCorpusPath);
return undefined;
}
let result: string;
// break the corpus path into namespace and ... path
const pathTuple: [string, string] = StorageUtils.splitNamespacePath(corpusPath);
if (!pathTuple) {
Logger.error(this.ctx, this.TAG, this.corpusPathToAdapterPath.name, null, cdmLogCode.ErrStorageNullCorpusPath);
return undefined;
}
const namespace: string = pathTuple[0] || this.defaultNamespace;
// get the adapter registered for this namespace
const namespaceAdapter: StorageAdapterBase = this.fetchAdapter(namespace);
if (namespaceAdapter === undefined) {
Logger.error(this.ctx, this.TAG, this.corpusPathToAdapterPath.name, null, cdmLogCode.ErrStorageNamespaceNotRegistered, namespace);
} else {
// ask the storage adapter to 'adapt' this path
result = namespaceAdapter.createAdapterPath(pathTuple[1]);
}
return result;
});
}
public createAbsoluteCorpusPath(objectPath: string, obj?: CdmObject): string {
return using(enterScope(StorageManager.name, this.ctx, this.createAbsoluteCorpusPath.name), _ => {
if (!objectPath) {
Logger.error(this.ctx, this.TAG, this.createAbsoluteCorpusPath.name, null, cdmLogCode.ErrPathNullObjectPath);
return undefined;
}
if (this.containsUnsupportedPathFormat(objectPath)) {
// already called statusRpt when checking for unsupported path format.
return;
}
const pathTuple: [string, string] = StorageUtils.splitNamespacePath(objectPath);
if (!pathTuple) {
Logger.error(this.ctx, this.TAG, this.createAbsoluteCorpusPath.name, null, cdmLogCode.ErrPathNullObjectPath);
return undefined;
}
const nameSpace: string = pathTuple[0];
let newObjectPath: string = pathTuple[1];
let finalNamespace: string;
let prefix: string;
let namespaceFromObj: string;
if (obj && (obj as CdmContainerDefinition).namespace && (obj as CdmContainerDefinition).folderPath) {
prefix = (obj as CdmContainerDefinition).folderPath;
namespaceFromObj = (obj as CdmContainerDefinition).namespace;
} else if (obj && obj.inDocument) {
prefix = obj.inDocument.folderPath;
namespaceFromObj = obj.inDocument.namespace;
}
if (prefix && this.containsUnsupportedPathFormat(prefix)) {
// already called statusRpt when checking for unsupported path format.
return;
}
if (prefix && prefix.length > 0 && prefix[prefix.length - 1] !== '/') {
Logger.warning(this.ctx, this.TAG, this.createAbsoluteCorpusPath.name, null, cdmLogCode.WarnStorageExpectedPathPrefix, prefix);
prefix += '/';
}
// check if this is a relative path
if (newObjectPath && newObjectPath.charAt(0) !== '/') {
if (!obj) {
// relative path and no other info given, assume default and root
prefix = '/';
}
if (nameSpace && nameSpace !== namespaceFromObj) {
Logger.error(this.ctx, this.TAG, this.createAbsoluteCorpusPath.name, null, cdmLogCode.ErrStorageNamespaceMismatch, nameSpace);
return;
}
newObjectPath = `${prefix}${newObjectPath}`;
finalNamespace = namespaceFromObj || nameSpace || this.defaultNamespace;
} else {
finalNamespace = nameSpace || namespaceFromObj || this.defaultNamespace;
}
return `${finalNamespace ? `${finalNamespace}:` : ''}${newObjectPath}`;
});
}
/**
* Takes a corpus path (relative or absolute) and creates a valid relative corpus path with namespace.
* @param objectPath The path that should be made relative, if possible
* @param relativeTo The object that the path should be made relative with respect to.
*/
public createRelativeCorpusPath(objectPath: string, relativeTo?: CdmContainerDefinition): string {
return using(enterScope(StorageManager.name, this.ctx, this.createRelativeCorpusPath.name), _ => {
let newPath: string = this.createAbsoluteCorpusPath(objectPath, relativeTo);
const namespaceString: string = relativeTo ? `${relativeTo.namespace}:` : '';
if (namespaceString && newPath && newPath.startsWith(namespaceString)) {
newPath = newPath.slice(namespaceString.length);
if (newPath.startsWith(relativeTo.folderPath)) {
newPath = newPath.slice(relativeTo.folderPath.length);
}
}
return newPath;
});
}
/**
* @inheritdoc
*/
public fetchConfig(): string {
const adaptersArray = [];
// Construct the JObject for each adapter.
for (const namespaceAdapterTuple of this.namespaceAdapters) {
// Skip system-defined adapters and resource adapters.
if (this.systemDefinedNamespaces.has(namespaceAdapterTuple[0]) || namespaceAdapterTuple[1] instanceof ResourceAdapter) {
continue;
}
const config: string = namespaceAdapterTuple[1].fetchConfig();
if (!config) {
Logger.error(this.ctx, this.TAG, this.fetchConfig.name, null, cdmLogCode.ErrStorageNullAdapter);
continue;
}
const jsonConfig = JSON.parse(config);
jsonConfig.namespace = namespaceAdapterTuple[0];
adaptersArray.push(jsonConfig);
}
const resultConfig: configObjectType = {};
/// App ID might not be set.
if (this.corpus.appId) {
resultConfig.appId = this.corpus.appId;
}
resultConfig.defaultNamespace = this.defaultNamespace;
resultConfig.adapters = adaptersArray;
return JSON.stringify(resultConfig);
}
/**
* Saves adapters config into a file.
*/
public async saveAdaptersConfigAsync(name: string, adapter: StorageAdapterBase): Promise<void> {
await adapter.writeAsync(name, this.fetchConfig());
}
/**
* Checks whether the paths has an unsupported format, such as starting with ./ or containing ../ or /./
* In case unsupported path format is found, function calls statusRpt and returns true.
* Returns false if path seems OK.
* @param path The path to be checked.
* @returns True if an unsupported path format was found.
*/
private containsUnsupportedPathFormat(path: string): boolean {
let statusMessage: string;
if (path.startsWith('./') || path.startsWith('.\\')) {
statusMessage = 'The path starts with ./';
} else if (path.indexOf('../') !== -1 || path.indexOf('..\\') !== -1) {
statusMessage = 'The path contains ../';
} else if (path.indexOf('/./') !== -1 || path.indexOf('\\.\\') !== -1) {
statusMessage = 'The path contains /./';
} else {
return false;
}
Logger.error(this.ctx, this.TAG, this.containsUnsupportedPathFormat.name, null, cdmLogCode.ErrStorageInvalidPathFormat, statusMessage);
return true;
}
} | the_stack |
import * as path from 'path';
import * as fs from 'fs';
import { isObject, isArray, set, get } from 'lodash';
import { Context, ITaskConfig } from 'build-scripts';
import { InlineConfig, BuildOptions } from 'vite';
import type { ProcessOptions } from 'postcss';
type Option = BuildOptions & InlineConfig;
type Transformer = (
value: any,
ctx?: Context,
chain?: ITaskConfig['chainConfig']
) => any;
type ConfigMap = Record<string, string | string[] | {
name: string | string[]
transform: Transformer
}>
interface MinifierConfig {
type: 'esbuild' | 'swc' | 'terser';
options?: Record<string, any>;
}
interface PostcssOptions extends ProcessOptions {
plugins?: { [pluginName: string]: Record<string, any> };
}
/**
* 设置 vite 字段的值
*/
const setViteConfig = (acc: object, value: any, viteRow: string | string[], isTransform = false) => {
if (value === undefined) return;
const config = isArray(viteRow) ? viteRow : [viteRow];
config.forEach((cfg, index) => {
set(acc, cfg, isTransform && isArray(viteRow) ? value[index] : value);
});
};
const transformPlugin = (pluginName: string): Transformer => {
return (...[,,webpackChain]) => {
if (!webpackChain || !webpackChain.plugins.has(pluginName)) return;
const opts = webpackChain.plugin(pluginName).get('args') ?? [];
return opts[0];
};
};
const transformMinimizer = (minimizerName: string): Transformer => {
return (...[,,webpackChain]) => {
// @ts-ignore
if (!webpackChain || !webpackChain.optimization.minimizers.has(minimizerName)) return;
const opts = webpackChain.optimization.minimizer(minimizerName).get('args') ?? [];
return opts[0];
};
};
const transformPreProcess = (loaderName: string, rule: string): Transformer => {
// filter options for sassOptions and lessOptions
const optionsMap = {
scss: 'sassOptions',
less: 'lessOptions',
};
// additionalData is special option for pre processor
// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/plugins/css.ts#L1035
const pickOptions = ['additionalData'];
const optionsKey: string = optionsMap[rule];
return (...args) => {
const opt = args[2].module.rules.get(rule).use(loaderName).get('options');
const preProcessOptions = (optionsKey ? opt?.[optionsKey] : opt) || {};
pickOptions.forEach(pickKey => {
if (opt?.[pickKey]) {
preProcessOptions[pickKey] = opt[pickKey];
}
});
return preProcessOptions;
};
};
const mapWithBrowserField = (packageName: string, resolvePath: string): Record<string, string> => {
const aliasMap = {};
// check field `package.exports`, make sure `${packageName}/package.json` can be resolved
try {
const packagePath = require.resolve(`${resolvePath}/package.json`);
const data = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
if (isObject(data.browser)) {
Object.keys(data.browser).forEach((requirePath) => {
const pathExtname = path.extname(requirePath);
const aliasKey = path.join(packageName, pathExtname ? requirePath.replace(pathExtname, '') : requirePath);
aliasMap[aliasKey] = path.join(resolvePath, data.browser[requirePath]);
});
}
} catch (err) {
console.error(`[Error] fail to resolve alias {${packageName}: ${resolvePath}}`, err);
}
return aliasMap;
};
/**
* 常用简单配置转换
*/
const configMap: ConfigMap = {
'output.path': {
name: 'build.outDir',
transform: (value, ctx) => path.relative(ctx.rootDir, value),
},
'output.publicPath': 'base',
'resolve.alias': {
name: 'resolve.alias',
transform: (value, ctx) => {
const { rootDir } = ctx;
// webpack/hot is not necessary in mode vite
const blackList = ['webpack/hot'];
const packagesWithBrowserField = ['react-dom'];
const data: Record<string, any> = Object.keys(value).reduce(
(acc, key) => {
if (!blackList.some((word) => value[key]?.includes(word))) {
// TODO: if vite ssr disable resolve path with browser field
if (packagesWithBrowserField.includes(key)) {
const aliasMap = mapWithBrowserField(key, value[key]);
Object.keys(aliasMap).forEach((aliasKey) => {
acc[aliasKey] = aliasMap[aliasKey];
});
}
acc[key] = value[key];
}
return acc;
},
{}
);
// alias 到指向 ice runtime 入口
data.ice = path.resolve(rootDir, '.ice/index.ts');
// built-in alias for ~antd and ~@alifd/next which commonly unused in style files
['antd', '@alifd/next'].forEach((pkg) => {
data[`~${pkg}`] = pkg;
});
// Object to Array
return Object.entries(data).map(([find, replacement]) => {
return { find, replacement };
});
},
},
'resolve.extensions': {
name: 'resolve.extensions',
transform: (value) => ['.mjs', ...value],
},
// minify
'optimization.minimize': {
name: 'build.minify',
transform: (value, { userConfig }) => {
if (value) {
const { minify } = userConfig;
if (minify) {
const minifier = (minify as unknown as MinifierConfig).type
|| (typeof minify === 'boolean' ? 'terser' : minify) as string;
if (['esbuild', 'terser'].includes(minifier)) {
return minifier;
} else {
console.log(`minify '${minifier}' is not supported in vite mode, specify 'terser' as minifier`);
}
}
} else {
return false;
}
},
},
'devtool': {
name: 'build.sourcemap',
transform: (devtool) => {
// build.sourcemap of support inline | hidden
if (devtool) {
const sourcemap = ['inline', 'hidden'].find((mapType) => {
return !!devtool.match(new RegExp(mapType));
});
return sourcemap || !!devtool;
}
return false;
},
},
'devServer.watchOptions.static.watch': 'server.watch',
'devServer.proxy': {
name: 'server.proxy',
transform: (value: Record<string, any>[]) => {
// vite proxy do not support config of onProxyRes, onError, logLevel, pathRewrite
// transform devServer.proxy to server.proxy
let hasProxy = false;
const proxyConfig = {};
(value || []).forEach(({ context, enable, onProxyRes, onError, pathRewrite, ...rest }) => {
if (enable !== false) {
if (!hasProxy) {
hasProxy = true;
console.log('Proxy setting detected. HTTPS will be downgraded to TLS only (HTTP/2 will be disabled)');
}
proxyConfig[context] = {
...rest,
rewrite: (requestPath: string) => {
if (pathRewrite && isObject(pathRewrite)) {
return Object.keys(pathRewrite).reduce((acc, rewriteRule) => {
return acc.replace(new RegExp(rewriteRule), pathRewrite[rewriteRule]);
}, requestPath);
} else {
return requestPath;
}
},
configure: (proxy, options) => {
if (rest.configure) {
rest.configure(proxy, options);
}
if (onProxyRes) {
proxy.on('proxyRes', onProxyRes);
}
if (onError) {
proxy.on('error', onError);
}
},
};
}
});
return hasProxy ? proxyConfig : undefined;
},
},
'devServer.https': 'server.https',
'plugins.DefinePlugin': {
name: 'define',
transform: transformPlugin('DefinePlugin'),
},
'plugins.TerserPlugin': {
name: 'build.terserOptions',
transform: (...args) => {
const terserPluginOptions = transformMinimizer('TerserPlugin')(...args);
return terserPluginOptions?.terserOptions;
},
},
'plugin.ESBuild': {
name: 'build.target',
transform: (...args) => {
// build.target is performed with esbuild and the value should be a valid esbuild target option
const esbuildMinifyOptions = transformMinimizer('ESBuild')(...args);
return esbuildMinifyOptions?.target;
},
},
sass: {
name: 'css.preprocessorOptions.scss',
transform: transformPreProcess('sass-loader', 'scss'),
},
less: {
name: 'css.preprocessorOptions.less',
transform: transformPreProcess('less-loader', 'less'),
},
// 保证在 link 开发调试时引入的 react 是一个实例
dedupe: {
name: 'resolve.dedupe',
transform: () => ['react', 'react-dom'],
},
postcss: {
name: 'css.postcss',
transform: (e, { userConfig }) => {
if (userConfig?.postcssOptions) {
const postcssPlugins = (userConfig?.postcssOptions as PostcssOptions)?.plugins || {};
const normalizedPlugins = Object.keys(postcssPlugins)
.filter((pluginKey) => !!postcssPlugins[pluginKey])
// eslint-disable-next-line global-require,import/no-dynamic-require
.map(pluginKey => require(pluginKey)(postcssPlugins[pluginKey]));
return {
...(userConfig?.postcssOptions as PostcssOptions),
plugins: normalizedPlugins.length > 0 ? normalizedPlugins : [],
};
}
}
},
vendor: {
name: 'build.rollupOptions.output.manualChunks',
transform: (e, { userConfig }) => {
if (!userConfig.vendor) {
return false;
}
// Tips: userConfig.vendor === true 时不会去设置 manualChunks,正常导出 vendor
}
},
// hash & outputAssetsPath (OAP)
hashAndOAP: {
name: [
'build.rollupOptions.output.entryFileNames',
'build.rollupOptions.output.chunkFileNames',
'build.rollupOptions.output.assetFileNames',
],
transform: (e, { userConfig }) => {
const data = userConfig.outputAssetsPath as { css: string; js: string };
const hash = userConfig.hash === true ? 'hash' : userConfig.hash;
const hashStr = hash ? `.[${hash}]` : '';
const { js, css } = data;
const assetFileNames = (assetInfo: { name: string }) => {
if (path.extname(assetInfo.name) === '.css') {
return `${css}/[name]${hashStr}[extname]`;
}
return `[name]${hashStr}[extname]`;
};
return [
`${js}/[name]${hashStr}.js`,
`${js}/[name]${hashStr}.js`,
assetFileNames,
];
}
},
};
/**
* 配置转化函数
*/
export const recordMap = (
chain: ITaskConfig['chainConfig'],
ctx: Context
): Partial<Record<keyof Option, any>> => {
const cfg = chain.toConfig();
return Object.keys(configMap).reduce((acc, key) => {
const viteConfig = configMap[key];
const webpackValue = get(cfg, key);
// 如果后面接的是对象
if (isObject(viteConfig) && !isArray(viteConfig)) {
const value = viteConfig.transform(webpackValue, ctx, chain);
setViteConfig(acc, value, viteConfig.name, true);
return acc;
}
setViteConfig(acc, webpackValue, viteConfig);
return acc;
}, {});
}; | the_stack |
import { ParameterSchema, Schema } from '@taquito/michelson-encoder';
import { EntrypointsResponse, ScriptResponse } from '@taquito/rpc';
import { ChainIds, DefaultLambdaAddresses } from '../constants';
import { Wallet } from '../wallet';
import { ContractMethodFactory } from './contract-methods/contract-method-factory';
import { ContractMethod } from './contract-methods/contract-method-flat-param';
import { ContractMethodObject } from './contract-methods/contract-method-object-param';
import { InvalidParameterError, UndefinedLambdaContractError } from './errors';
import { ContractProvider, StorageProvider } from './interface';
import LambdaView from './lambda-view';
export const DEFAULT_SMART_CONTRACT_METHOD_NAME = 'default';
/**
* @description Utility class to retrieve data from a smart contract's storage without incurring fees via a contract's view method
*/
export class ContractView {
constructor(
private currentContract: ContractAbstraction<ContractProvider | Wallet>,
private provider: ContractProvider,
private name: string,
private chainId: string,
private callbackParametersSchema: ParameterSchema,
private parameterSchema: ParameterSchema,
private args: any[]
) { }
/**
*
* @description Find which lambda contract to use based on the current network,
* encode parameters to Michelson,
* create an instance of Lambdaview to retrive data, and
* Decode Michelson response
*
* @param Options Address of a lambda contract (sandbox users)
*/
async read(customLambdaAddress?: string) {
let lambdaAddress;
// TODO Verify if the 'customLambdaAdress' is a valid originated contract and if not, return an appropriate error message.
if (customLambdaAddress) {
lambdaAddress = customLambdaAddress
} else if (this.chainId === ChainIds.EDONET) {
lambdaAddress = DefaultLambdaAddresses.EDONET
} else if (this.chainId === ChainIds.FLORENCENET) {
lambdaAddress = DefaultLambdaAddresses.FLORENCENET
} else if (this.chainId === ChainIds.GRANADANET) {
lambdaAddress = DefaultLambdaAddresses.GRANADANET
} else if (this.chainId === ChainIds.HANGZHOUNET) {
lambdaAddress = DefaultLambdaAddresses.HANGZHOUNET
} else if (this.chainId === ChainIds.MAINNET) {
lambdaAddress = DefaultLambdaAddresses.MAINNET
} else {
throw new UndefinedLambdaContractError()
}
const lambdaContract = await this.provider.at(lambdaAddress);
const arg = this.parameterSchema.Encode(...this.args);
const lambdaView = new LambdaView(lambdaContract, this.currentContract, this.name, arg);
const failedWith = await lambdaView.execute();
const response = this.callbackParametersSchema.Execute(failedWith);
return response;
}
}
const validateArgs = (args: any[], schema: ParameterSchema, name: string) => {
const sigs = schema.ExtractSignatures();
if (!sigs.find((x: any[]) => x.length === args.length)) {
throw new InvalidParameterError(name, sigs, args);
}
};
const isView = (schema: ParameterSchema): boolean => {
let isView = false;
const sigs = schema.ExtractSignatures();
if ((sigs[0][sigs[0].length - 1] === 'contract')) {
isView = true;
}
return isView;
};
export type Contract = ContractAbstraction<ContractProvider>;
export type WalletContract = ContractAbstraction<Wallet>;
const isContractProvider = (variableToCheck: any): variableToCheck is ContractProvider =>
variableToCheck.contractProviderTypeSymbol !== undefined;
/**
* @description Smart contract abstraction
*/
export class ContractAbstraction<T extends ContractProvider | Wallet> {
private contractMethodFactory = new ContractMethodFactory<T>()
/**
* @description Contains methods that are implemented by the target Tezos Smart Contract, and offers the user to call the Smart Contract methods as if they were native TS/JS methods.
* NB: if the contract contains annotation it will include named properties; if not it will be indexed by a number.
*
*/
public methods: { [key: string]: (...args: any[]) => ContractMethod<T> } = {};
/**
* @description Contains methods that are implemented by the target Tezos Smart Contract, and offers the user to call the Smart Contract methods as if they were native TS/JS methods.
* `methodsObject` serves the exact same purpose as the `methods` member. The difference is that it allows passing the parameter in an object format when calling the smart contract method (instead of the flattened representation)
* NB: if the contract contains annotation it will include named properties; if not it will be indexed by a number.
*
*/
public methodsObject: { [key: string]: (args?: any) => ContractMethodObject<T> } = {};
public views: { [key: string]: (...args: any[]) => ContractView } = {};
public readonly schema: Schema;
public readonly parameterSchema: ParameterSchema;
constructor(
public readonly address: string,
public readonly script: ScriptResponse,
provider: T,
private storageProvider: StorageProvider,
public readonly entrypoints: EntrypointsResponse,
private chainId: string
) {
this.schema = Schema.fromRPCResponse({ script: this.script });
this.parameterSchema = ParameterSchema.fromRPCResponse({ script: this.script });
this._initializeMethods(this, address, provider, this.entrypoints.entrypoints, this.chainId);
}
private _initializeMethods(
currentContract: ContractAbstraction<T>,
address: string,
provider: T,
entrypoints: {
[key: string]: object;
},
chainId: string
) {
const parameterSchema = this.parameterSchema;
const keys = Object.keys(entrypoints);
if (parameterSchema.isMultipleEntryPoint) {
keys.forEach(smartContractMethodName => {
const smartContractMethodSchema = new ParameterSchema(
entrypoints[smartContractMethodName]
);
this.methods[smartContractMethodName] = function (...args: any[]) {
return currentContract.contractMethodFactory.createContractMethodFlatParams(
provider,
address,
smartContractMethodSchema,
smartContractMethodName,
args
);
};
this.methodsObject[smartContractMethodName] = function (args: any) {
return currentContract.contractMethodFactory.createContractMethodObjectParam(
provider,
address,
smartContractMethodSchema,
smartContractMethodName,
args
);
};
if (isContractProvider(provider)) {
if (isView(smartContractMethodSchema)) {
const view = function (...args: any[]) {
const entrypointParamWithoutCallback = (entrypoints[smartContractMethodName] as any).args[0];
const smartContractMethodSchemaWithoutCallback = new ParameterSchema(
entrypointParamWithoutCallback
);
const parametersCallback = (entrypoints[smartContractMethodName] as any).args[1].args[0];
const smartContractMethodCallbackSchema = new ParameterSchema(
parametersCallback
);
validateArgs(args, smartContractMethodSchemaWithoutCallback, smartContractMethodName);
return new ContractView(
currentContract,
provider,
smartContractMethodName,
chainId,
smartContractMethodCallbackSchema,
smartContractMethodSchemaWithoutCallback,
args
);
};
this.views[smartContractMethodName] = view;
}
}
});
// Deal with methods with no annotations which were not discovered by the RPC endpoint
// Methods with no annotations are discovered using parameter schema
const anonymousMethods = Object.keys(parameterSchema.ExtractSchema()).filter(
key => Object.keys(entrypoints).indexOf(key) === -1
);
anonymousMethods.forEach(smartContractMethodName => {
this.methods[smartContractMethodName] = function (...args: any[]) {
return currentContract.contractMethodFactory.createContractMethodFlatParams(
provider,
address,
parameterSchema,
smartContractMethodName,
args,
false,
true
);
};
this.methodsObject[smartContractMethodName] = function (args: any) {
return currentContract.contractMethodFactory.createContractMethodObjectParam(
provider,
address,
parameterSchema,
smartContractMethodName,
args,
false,
true
);
};
});
} else {
const smartContractMethodSchema = this.parameterSchema;
this.methods[DEFAULT_SMART_CONTRACT_METHOD_NAME] = function (...args: any[]) {
return currentContract.contractMethodFactory.createContractMethodFlatParams(
provider,
address,
smartContractMethodSchema,
DEFAULT_SMART_CONTRACT_METHOD_NAME,
args,
false
);
};
this.methodsObject[DEFAULT_SMART_CONTRACT_METHOD_NAME] = function (args: any) {
return currentContract.contractMethodFactory.createContractMethodObjectParam(
provider,
address,
smartContractMethodSchema,
DEFAULT_SMART_CONTRACT_METHOD_NAME,
args,
false
);
};
}
}
/**
* @description Return a friendly representation of the smart contract storage
*/
public storage<T>() {
return this.storageProvider.getStorage<T>(this.address, this.schema);
}
/**
*
* @description Return a friendly representation of the smart contract big map value
*
* @param key BigMap key to fetch
*
* @deprecated getBigMapKey has been deprecated in favor of getBigMapKeyByID
*
* @see https://tezos.gitlab.io/api/rpc.html#post-block-id-context-contracts-contract-id-big-map-get
*/
public bigMap(key: string) {
// tslint:disable-next-line: deprecation
return this.storageProvider.getBigMapKey(this.address, key, this.schema);
}
} | the_stack |
import {
Accessory,
CameraController,
CameraStreamingDelegate,
Categories,
H264Level,
H264Profile,
PrepareStreamCallback,
PrepareStreamRequest,
PrepareStreamResponse,
SnapshotRequest,
SnapshotRequestCallback,
SRTPCryptoSuites,
StreamingRequest,
StreamRequestCallback,
StreamRequestTypes,
StreamSessionIdentifier,
uuid,
VideoInfo
} from "..";
import { ChildProcess, spawn } from "child_process";
const cameraUUID = uuid.generate('hap-nodejs:accessories:ip-camera');
const camera = exports.accessory = new Accessory('IPCamera', cameraUUID);
// @ts-ignore
camera.username = "9F:B2:46:0C:40:DB";
// @ts-ignore
camera.pincode = "948-23-459";
camera.category = Categories.IP_CAMERA;
type SessionInfo = {
address: string, // address of the HAP controller
videoPort: number, // port of the controller
localVideoPort: number,
videoCryptoSuite: SRTPCryptoSuites, // should be saved if multiple suites are supported
videoSRTP: Buffer, // key and salt concatenated
videoSSRC: number, // rtp synchronisation source
/* Won't be save as audio is not supported by this example
audioPort: number,
audioCryptoSuite: SRTPCryptoSuites,
audioSRTP: Buffer,
audioSSRC: number,
*/
}
type OngoingSession = {
localVideoPort: number,
process: ChildProcess,
}
const FFMPEGH264ProfileNames = [
"baseline",
"main",
"high"
];
const FFMPEGH264LevelNames = [
"3.1",
"3.2",
"4.0"
];
const ports = new Set<number>();
function getPort(): number {
for (let i = 5011;; i++) {
if (!ports.has(i)) {
ports.add(i);
return i;
}
}
}
class ExampleCamera implements CameraStreamingDelegate {
private ffmpegDebugOutput: boolean = false;
controller?: CameraController;
// keep track of sessions
pendingSessions: Record<string, SessionInfo> = {};
ongoingSessions: Record<string, OngoingSession> = {};
handleSnapshotRequest(request: SnapshotRequest, callback: SnapshotRequestCallback): void {
const ffmpegCommand = `-f lavfi -i testsrc=s=${request.width}x${request.height} -vframes 1 -f mjpeg -`;
const ffmpeg = spawn("ffmpeg", ffmpegCommand.split(" "), {env: process.env});
const snapshotBuffers: Buffer[] = [];
ffmpeg.stdout.on('data', data => snapshotBuffers.push(data));
ffmpeg.stderr.on('data', data => {
if (this.ffmpegDebugOutput) {
console.log("SNAPSHOT: " + String(data));
}
});
ffmpeg.on('exit', (code, signal) => {
if (signal) {
console.log("Snapshot process was killed with signal: " + signal);
callback(new Error("killed with signal " + signal));
} else if (code === 0) {
console.log(`Successfully captured snapshot at ${request.width}x${request.height}`);
callback(undefined, Buffer.concat(snapshotBuffers));
} else {
console.log("Snapshot process exited with code " + code);
callback(new Error("Snapshot process exited with code " + code));
}
});
}
// called when iOS request rtp setup
prepareStream(request: PrepareStreamRequest, callback: PrepareStreamCallback): void {
const sessionId: StreamSessionIdentifier = request.sessionID;
const targetAddress = request.targetAddress;
const video = request.video;
const videoCryptoSuite = video.srtpCryptoSuite; // could be used to support multiple crypto suite (or support no suite for debugging)
const videoSrtpKey = video.srtp_key;
const videoSrtpSalt = video.srtp_salt;
const videoSSRC = CameraController.generateSynchronisationSource();
const localPort = getPort();
const sessionInfo: SessionInfo = {
address: targetAddress,
videoPort: video.port,
localVideoPort: localPort,
videoCryptoSuite: videoCryptoSuite,
videoSRTP: Buffer.concat([videoSrtpKey, videoSrtpSalt]),
videoSSRC: videoSSRC,
};
const response: PrepareStreamResponse = {
video: {
port: localPort,
ssrc: videoSSRC,
srtp_key: videoSrtpKey,
srtp_salt: videoSrtpSalt,
},
// audio is omitted as we do not support audio in this example
};
this.pendingSessions[sessionId] = sessionInfo;
callback(undefined, response);
}
// called when iOS device asks stream to start/stop/reconfigure
handleStreamRequest(request: StreamingRequest, callback: StreamRequestCallback): void {
const sessionId = request.sessionID;
switch (request.type) {
case StreamRequestTypes.START: {
const sessionInfo = this.pendingSessions[sessionId];
const video: VideoInfo = request.video;
const profile = FFMPEGH264ProfileNames[video.profile];
const level = FFMPEGH264LevelNames[video.level];
const width = video.width;
const height = video.height;
const fps = video.fps;
const payloadType = video.pt;
const maxBitrate = video.max_bit_rate;
const rtcpInterval = video.rtcp_interval; // usually 0.5
const mtu = video.mtu; // maximum transmission unit
const address = sessionInfo.address;
const videoPort = sessionInfo.videoPort;
const localVideoPort = sessionInfo.localVideoPort;
const ssrc = sessionInfo.videoSSRC;
const cryptoSuite = sessionInfo.videoCryptoSuite;
const videoSRTP = sessionInfo.videoSRTP.toString("base64");
console.log(`Starting video stream (${width}x${height}, ${fps} fps, ${maxBitrate} kbps, ${mtu} mtu)...`);
let videoffmpegCommand = `-re -f lavfi -i testsrc=s=${width}x${height}:r=${fps} -map 0:0 ` +
`-c:v h264 -pix_fmt yuv420p -r ${fps} -an -sn -dn -b:v ${maxBitrate}k ` +
`-profile:v ${profile} -level:v ${level} ` +
`-payload_type ${payloadType} -ssrc ${ssrc} -f rtp `;
if (cryptoSuite !== SRTPCryptoSuites.NONE) {
let suite: string;
switch (cryptoSuite) {
case SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80: // actually ffmpeg just supports AES_CM_128_HMAC_SHA1_80
suite = "AES_CM_128_HMAC_SHA1_80";
break;
case SRTPCryptoSuites.AES_CM_256_HMAC_SHA1_80:
suite = "AES_CM_256_HMAC_SHA1_80";
break;
}
videoffmpegCommand += `-srtp_out_suite ${suite} -srtp_out_params ${videoSRTP} s`;
}
videoffmpegCommand += `rtp://${address}:${videoPort}?rtcpport=${videoPort}&localrtcpport=${localVideoPort}&pkt_size=${mtu}`;
if (this.ffmpegDebugOutput) {
console.log("FFMPEG command: ffmpeg " + videoffmpegCommand);
}
const ffmpegVideo = spawn('ffmpeg', videoffmpegCommand.split(' '), {env: process.env});
let started = false;
ffmpegVideo.stderr.on('data', (data: Buffer) => {
console.log(data.toString("utf8"));
if (!started) {
started = true;
console.log("FFMPEG: received first frame");
callback(); // do not forget to execute callback once set up
}
if (this.ffmpegDebugOutput) {
console.log("VIDEO: " + String(data));
}
});
ffmpegVideo.on('error', error => {
console.log("[Video] Failed to start video stream: " + error.message);
callback(new Error("ffmpeg process creation failed!"));
});
ffmpegVideo.on('exit', (code, signal) => {
const message = "[Video] ffmpeg exited with code: " + code + " and signal: " + signal;
if (code == null || code === 255) {
console.log(message + " (Video stream stopped!)");
} else {
console.log(message + " (error)");
if (!started) {
callback(new Error(message));
} else {
this.controller!.forceStopStreamingSession(sessionId);
}
}
});
this.ongoingSessions[sessionId] = {
localVideoPort: localVideoPort,
process: ffmpegVideo,
};
delete this.pendingSessions[sessionId];
break;
}
case StreamRequestTypes.RECONFIGURE:
// not supported by this example
console.log("Received (unsupported) request to reconfigure to: " + JSON.stringify(request.video));
callback();
break;
case StreamRequestTypes.STOP:
const ongoingSession = this.ongoingSessions[sessionId];
ports.delete(ongoingSession.localVideoPort);
try {
ongoingSession.process.kill('SIGKILL');
} catch (e) {
console.log("Error occurred terminating the video process!");
console.log(e);
}
delete this.ongoingSessions[sessionId];
console.log("Stopped streaming session!");
callback();
break;
}
}
}
const streamDelegate = new ExampleCamera();
const cameraController = new CameraController({
cameraStreamCount: 2, // HomeKit requires at least 2 streams, but 1 is also just fine
delegate: streamDelegate,
streamingOptions: {
// srtp: true, // legacy option which will just enable AES_CM_128_HMAC_SHA1_80 (can still be used though)
supportedCryptoSuites: [SRTPCryptoSuites.NONE, SRTPCryptoSuites.AES_CM_128_HMAC_SHA1_80], // NONE is not supported by iOS just there for testing with Wireshark for example
video: {
codec: {
profiles: [H264Profile.BASELINE, H264Profile.MAIN, H264Profile.HIGH],
levels: [H264Level.LEVEL3_1, H264Level.LEVEL3_2, H264Level.LEVEL4_0],
},
resolutions: [
[1920, 1080, 30], // width, height, framerate
[1280, 960, 30],
[1280, 720, 30],
[1024, 768, 30],
[640, 480, 30],
[640, 360, 30],
[480, 360, 30],
[480, 270, 30],
[320, 240, 30],
[320, 240, 15], // Apple Watch requires this configuration (Apple Watch also seems to required OPUS @16K)
[320, 180, 30],
],
},
/* audio option is omitted, as it is not supported in this example; HAP-NodeJS will fake an appropriate audio codec
audio: {
comfort_noise: false, // optional, default false
codecs: [
{
type: AudioStreamingCodecType.OPUS,
audioChannels: 1, // optional, default 1
samplerate: [AudioStreamingSamplerate.KHZ_16, AudioStreamingSamplerate.KHZ_24], // 16 and 24 must be present for AAC-ELD or OPUS
},
],
},
// */
}
});
streamDelegate.controller = cameraController;
camera.configureController(cameraController); | the_stack |
// CodeSymbol 管理AST中的符号, 对上提供各种接口。
// 获取/刷新文件符号
//
import * as Tools from './codeTools';
import { CodeEditor } from './codeEditor';
import { DocSymbolProcessor } from './docSymbolProcessor';
import { Logger } from './codeLogManager';
import { CodeSettings } from './codeSettings';
let dir = require('path-reader');
export class CodeSymbol {
// 用 kv 结构保存所有用户文件以及对应符号结构(包含定义符号和AST,以及方法)
public static docSymbolMap = new Map<string, DocSymbolProcessor>(); // 用户代码中的lua文件
public static luaPreloadSymbolMap = new Map<string, DocSymbolProcessor>(); // lua预制文件(LuaPanda集成)
public static userPreloadSymbolMap = new Map<string, DocSymbolProcessor>(); // 用户的lua导出接口
// 已处理文件列表,这里是防止循环引用
private static alreadySearchList; //TODO 要标记一下这个变量被哪些函数使用了
// 获取指定文件中的chunk列表
public static getCretainDocChunkDic(uri){
let processor = this.getFileSymbolsFromCache(uri);
if(processor){
return processor.getChunksDic();
}
}
//-----------------------------------------------------------------------------
//-- 创建单文件、工作区、预加载区、特定文件符号
//-----------------------------------------------------------------------------
// 单文件内符号处理
// 指定文件的符号 [单文件创建] | 无返回 . 如文档的符号已建立则直接返回
public static createOneDocSymbols(uri: string, luaText?: string) {
if ( ! this.docSymbolMap.has(uri)) {
this.refreshOneDocSymbols(uri, luaText);
}
}
// 指定文件的符号 [单文件刷新] | 无返回, 强制刷新
public static refreshOneDocSymbols(uri: string, luaText?: string) {
if(luaText == undefined){
luaText = CodeEditor.getCode(uri);
}
this.createDocSymbol(uri, luaText);
}
// 创建指定后缀的lua文件的符号
public static createSymbolswithExt(luaExtname: string, rootpath: string) {
//记录此后缀代表lua
Tools.setLoadedExt(luaExtname);
//解析workSpace中同后缀文件
let exp = new RegExp(luaExtname + '$', "i");
dir.readFiles(rootpath, { match: exp }, function (err, content, filePath, next) {
if (!err) {
let uri = Tools.pathToUri(filePath);
if(!Tools.isinPreloadFolder(uri)){
CodeSymbol.createOneDocSymbols(uri, content);
}else{
CodeSymbol.refreshOneUserPreloadDocSymbols( Tools.uriToPath(uri));
}
}
next();
}, (err) => {
if (err) {
return;
}
});
}
// 获取指定文件的所有符号 , 返回Array形式
public static getOneDocSymbolsArray(uri: string, luaText?: string, range?:Tools.SearchRange): Tools.SymbolInformation[] {
let docSymbals: Tools.SymbolInformation[] = [];
this.createOneDocSymbols(uri, luaText);
switch(range){
case Tools.SearchRange.GlobalSymbols:
docSymbals = this.getFileSymbolsFromCache(uri).getGlobalSymbolsArray(); break;
case Tools.SearchRange.LocalSymbols:
docSymbals = this.getFileSymbolsFromCache(uri).getLocalSymbolsArray(); break;
case Tools.SearchRange.AllSymbols:
docSymbals = this.getFileSymbolsFromCache(uri).getAllSymbolsArray(); break;
}
return docSymbals;
}
// 获取指定文件的所有符号 , 返回Dictionary形式
public static getOneDocSymbolsDic(uri: string, luaText?: string, range?:Tools.SearchRange): Tools.SymbolInformation[] {
let docSymbals: Tools.SymbolInformation[] = [];
this.createOneDocSymbols(uri, luaText);
switch(range){
case Tools.SearchRange.GlobalSymbols:
docSymbals = this.getFileSymbolsFromCache(uri).getGlobalSymbolsDic(); break;
case Tools.SearchRange.LocalSymbols:
docSymbals = this.getFileSymbolsFromCache(uri).getLocalSymbolsDic(); break;
case Tools.SearchRange.AllSymbols:
docSymbals = this.getFileSymbolsFromCache(uri).getAllSymbolsDic(); break;
}
return docSymbals;
}
// 获取指定文件的返回值,如无返回null
public static getOneDocReturnSymbol(uri):string{
this.createOneDocSymbols(uri);
let docSymbals = this.docSymbolMap.get(uri);
if(docSymbals){
return docSymbals.getFileReturnArray();
}
else{
return null;
}
}
// 指定文件夹中的符号处理
// 创建指定文件夹中所有文件的符号 [批量创建]
public static createFolderSymbols(path: string){
if(path === undefined || path === ''){
return;
}
let filesArray = Tools.getDirFiles( path );
filesArray.forEach(pathArray => {
let uri = Tools.pathToUri(pathArray);
if(!this.docSymbolMap.has(uri)){
this.createDocSymbol( uri , pathArray );
}
});
}
// 刷新 指定文件夹中所有文件的符号 [批量刷新]
public static refreshFolderSymbols(path: string){
if(path === undefined || path === ''){
return;
}
let filesArray = Tools.getDirFiles( path );
filesArray.forEach(element => {
this.createDocSymbol( element );
});
}
// 创建 lua预制的符号表 参数是文件夹路径
public static createLuaPreloadSymbols(path: string){
if(path === undefined || path === ''){
return;
}
let filesArray = Tools.getDirFiles( path );
filesArray.forEach(pathElement => {
this.createPreLoadSymbals( Tools.pathToUri(pathElement), 0 );
});
}
// 刷新 用户PreLoad 所有文件的符号 [PreLoad批量刷新] 参数是文件夹路径
public static refreshUserPreloadSymbals(path: string){
if(path === undefined || path === ''){
return;
}
let filesArray = Tools.getDirFiles( path );
filesArray.forEach(pathElement => {
this.createPreLoadSymbals( Tools.pathToUri(pathElement), 1 );
});
}
// 刷新 PreLoad 单个文件的符号 [PreLoad刷新] 通常lua预制符号只需要创建,无需刷新。
public static refreshOneUserPreloadDocSymbols(filePath: string){
if(filePath === undefined || filePath === ''){
return;
}
this.createPreLoadSymbals(Tools.pathToUri(filePath), 1);
}
// 获取 workspace 中的全局符号, 以dictionary的形式返回
public static getWorkspaceSymbols(range? : Tools.SearchRange){
range = range || Tools.SearchRange.AllSymbols;
let filesMap = Tools.get_FileName_Uri_Cache();
let g_symb = {};
for (const fileUri in filesMap) {
if(!Tools.isinPreloadFolder(filesMap[fileUri])){
let g_s = this.getOneDocSymbolsDic( filesMap[fileUri], null, range);
for (const key in g_s) {
const element = g_s[key];
g_symb[key] = element;
}
}
}
return g_symb;
}
//reference处理
public static searchSymbolReferenceinDoc(searchSymbol) {
let uri = searchSymbol.containerURI;
let docSymbals = this.getFileSymbolsFromCache(uri);
return docSymbals.searchDocSymbolReference(searchSymbol);
}
//-----------------------------------------------------------------------------
//-- 搜索符号
//-----------------------------------------------------------------------------
// 在[指定文件]查找符号(模糊匹配,用作搜索符号)
// @return 返回值得到的排序:
// 如果是Equal搜索,从dic中检索,按照AST深度遍历顺序返回
public static searchSymbolinDoc(uri:string, symbolStr: string, searchMethod: Tools.SearchMode, range:Tools.SearchRange = Tools.SearchRange.AllSymbols): Tools.SymbolInformation[] {
if (symbolStr === '' || uri === '' ) {
return null;
}
let docSymbals = this.getFileSymbolsFromCache(uri);;
let retSymbols = docSymbals.searchMatchSymbal(symbolStr, searchMethod, range);
return retSymbols;
}
public static getFileSymbolsFromCache(uri){
let docSymbals = this.docSymbolMap.get(uri);
if(!docSymbals){
docSymbals = this.userPreloadSymbolMap.get(uri);
}
if(!docSymbals){
docSymbals = this.luaPreloadSymbolMap.get(uri);
}
return docSymbals;
}
// 在[工作空间]查找符号, 主要用于模糊搜索。搜索文件顺序完全随机( isSearchPreload = false 全局符号模糊查找默认不展示预制变量)
// useAlreadySearchList 是否使用已经搜索列表。需要使用一搜索列表的场景是 先进行了引用树搜素,之后进行全局搜索,为了避免重读降低效率,此项设置为true
public static searchSymbolinWorkSpace(symbolStr: string, searchMethod: Tools.SearchMode = Tools.SearchMode.FuzzyMatching, searchRange: Tools.SearchRange = Tools.SearchRange.AllSymbols, isSearchPreload = false , useAlreadySearchList = false): Tools.SymbolInformation[] {
if (symbolStr === '') {
return [];
}
let retSymbols: Tools.SymbolInformation[] = [];
for (let [ key , value] of this.docSymbolMap) {
if(useAlreadySearchList){
if(this.alreadySearchList[key]){
continue;
}
}
let docSymbals = value.searchMatchSymbal(symbolStr, searchMethod, searchRange);
retSymbols = retSymbols.concat(docSymbals);
}
if(isSearchPreload){
let preS = this.searchUserPreLoadSymbols(symbolStr, searchMethod);
retSymbols = retSymbols.concat(preS);
preS = this.searchLuaPreLoadSymbols(symbolStr, searchMethod);
retSymbols = retSymbols.concat(preS);
}
return retSymbols;
}
// 搜索全局变量的定义,查找顺序是本文件,引用树,全局
// 不优先搜全局,不搜预制
public static searchSymbolforGlobalDefinition (uri:string, symbolStr: string, searchMethod: Tools.SearchMode = Tools.SearchMode.ExactlyEqual, searchRange: Tools.SearchRange = Tools.SearchRange.GlobalSymbols): Tools.SymbolInformation[] {
if (symbolStr === '' || uri === '' ) {
return [];
}
let retSymbols: Tools.SymbolInformation[] = [];
//搜索顺序 用户 > 系统
CodeSymbol.alreadySearchList = new Object(); // 记录已经搜索过的文件。避免重复搜索耗时
let preS = this.recursiveSearchRequireTree(uri, symbolStr, searchMethod, searchRange);
if(preS){
retSymbols = retSymbols.concat(preS);
}
// 这里建议搜到了,就不查全局文件了,因为全局查找是无序的。 这里最好有一个记录措施,避免同一个文件被多次查找,降低效率。
if(retSymbols.length === 0){
// 全局查找, 不含预制文件
let preS0 = this.searchSymbolinWorkSpace(symbolStr, searchMethod, Tools.SearchRange.GlobalSymbols, CodeSettings.isAllowDefJumpPreload , true);
if(preS0){
retSymbols = retSymbols.concat(preS0);
}
}
return retSymbols;
}
// 在[本文件引用的其他文件]上搜索所有符合的符号,用于 [代码提示 auto completion]
// 一定会搜全局,搜预制. 比较通用的一种方式,但是比较慢。(因为加入了预制搜索)
public static searchSymbolforCompletion (uri:string, symbolStr: string, searchMethod: Tools.SearchMode = Tools.SearchMode.PrefixMatch, searchRange: Tools.SearchRange = Tools.SearchRange.AllSymbols): Tools.SymbolInformation[] {
if (symbolStr === '' || uri === '' ) {
return [];
}
let retSymbols: Tools.SymbolInformation[] = [];
//搜索顺序 用户 > 系统
CodeSymbol.alreadySearchList = new Object();
let preS = this.recursiveSearchRequireTree(uri, symbolStr, searchMethod, searchRange);
if(preS){
retSymbols = retSymbols.concat(preS);
}
// 全局, 含有预制文件
let preS0 = this.searchSymbolinWorkSpace(symbolStr, searchMethod, Tools.SearchRange.GlobalSymbols, true, true);
if(preS0){
retSymbols = retSymbols.concat(preS0);
}
return retSymbols;
}
//-----------------------------------------------------------------------------
//-- 私有方法
//-----------------------------------------------------------------------------
// 搜索预制lua符号
private static searchLuaPreLoadSymbols(symbolStr, searchMethod){
if(!symbolStr || symbolStr === ''){
return [];
}
let retSymbols = new Array<Tools.SymbolInformation>();
this.luaPreloadSymbolMap.forEach(element => {
let res = element.searchMatchSymbal(symbolStr, searchMethod, Tools.SearchRange.GlobalSymbols);
if(res.length > 0){
retSymbols = retSymbols.concat(res);
}
});
return retSymbols;
}
// 搜索用户预制符号
private static searchUserPreLoadSymbols(symbolStr, searchMethod){
if(!symbolStr || symbolStr === ''){
return [];
}
let retSymbols = new Array<Tools.SymbolInformation>();
this.userPreloadSymbolMap.forEach(element => {
let res = element.searchMatchSymbal(symbolStr, searchMethod, Tools.SearchRange.GlobalSymbols);
if(res.length > 0){
retSymbols = retSymbols.concat(res);
}
});
return retSymbols;
}
/**
* 重新分析文件后,根据require的文件的变动,更新本文件require的文件的reference,保留本文件的reference
* @param oldDocSymbol 上一次的docSymbol
* @param newDocSymbol 本次更新之后的docSymbol
*/
private static updateReference(oldDocSymbol: DocSymbolProcessor, newDocSymbol: DocSymbolProcessor) {
if (!oldDocSymbol) {
// 初次处理无需更新
return;
}
// 保留本文件的reference(create的时候会被清空)
newDocSymbol.setReferences(oldDocSymbol.getReferencesArray());
let lastRequireFileArray = oldDocSymbol.getRequiresArray();
let currentRequireFiles = newDocSymbol.getRequiresArray();
// 以下requireFile的含义均为本文件require的其他文件
lastRequireFileArray.forEach((lastRequireFile) => {
// 本次代码改动删除之前的require语句,需要删除对应的reference关系
let needDeleteReference = true;
currentRequireFiles.forEach((currentRequireFile) => {
if (currentRequireFile.reqName == lastRequireFile.reqName) {
needDeleteReference = false;
return;
}
});
if (needDeleteReference) {
let lastRequireFileUri = Tools.transFileNameToUri(lastRequireFile.reqName);
if(lastRequireFileUri.length === 0) return;
let lastRequireFileDocSymbol = this.docSymbolMap.get(lastRequireFileUri);
let lastRequireFileReference = lastRequireFileDocSymbol.getReferencesArray();
let index = lastRequireFileReference.indexOf(newDocSymbol.getUri());
// 删除本文件require的文件对本文件的reference
lastRequireFileReference.splice(index, 1);
}
});
}
// 创建某个lua文件的符号
// @uri 文件uri
// @text 文件内容
private static createDocSymbol(uri: string, luaText?: string){
if(uri == null) return;
if (luaText == undefined) {
luaText = Tools.getFileContent(Tools.uriToPath(uri));
}
let oldDocSymbol = this.getFileSymbolsFromCache(uri);
let newDocSymbol: DocSymbolProcessor = DocSymbolProcessor.create(luaText, uri);
if(newDocSymbol){
Tools.AddTo_FileName_Uri_Cache(Tools.getPathNameAndExt(uri)['name'] , uri)
if( newDocSymbol.docInfo.parseSucc ){
//解析无误,覆盖旧的
this.docSymbolMap.set(uri, newDocSymbol);
this.updateReference(oldDocSymbol, newDocSymbol);
}else{
//解析过程有误
if ( !this.getFileSymbolsFromCache(uri) ){
//map中还未解析过这个table,放入本次解析结果
this.docSymbolMap.set(uri, newDocSymbol);
}else{
//map中已有, 且之前保存的同样是解析失败,覆盖
if (!this.getFileSymbolsFromCache(uri).docInfo.parseSucc){
this.docSymbolMap.set(uri, newDocSymbol);
this.updateReference(oldDocSymbol, newDocSymbol);
}
}
}
}else{
return;
}
}
// 创建前置搜索文件的所有符号
// @uri 文件uri
// @type 0lua预制 1用户导出
private static createPreLoadSymbals(uri: string, type:number){
let path = Tools.uriToPath(uri);
let luaText = Tools.getFileContent(path);
let docSymbol: DocSymbolProcessor = DocSymbolProcessor.create(luaText, uri);
if(type === 0){
this.luaPreloadSymbolMap.set(uri, docSymbol);
}else{
this.userPreloadSymbolMap.set(uri, docSymbol);
}
}
private static deepCounter = 0;
// 递归搜索 引用树,查找符号
// @fileName 文件名
// @symbolStr 符号名
// @uri
private static recursiveSearchRequireTree(uri: string, symbolStr, searchMethod :Tools.SearchMode, searchRange:Tools.SearchRange = Tools.SearchRange.AllSymbols, isFirstEntry:boolean = true){
if(!uri || uri === ''){
return [];
}
if(!symbolStr || symbolStr === ''){
return [];
}
let retSymbArray = new Array<Tools.SymbolInformation>();
if(isFirstEntry){
// 首次进入
this.deepCounter = 0;
}else{
//递归中
this.deepCounter++;
if(this.deepCounter >= 50){
return retSymbArray;
}
}
//如果 uri 的符号列表不存在,创建
if (!this.docSymbolMap.has(uri)) {
Logger.log("createDocSymbals : "+ uri);
let luaText = CodeEditor.getCode(uri);
this.createDocSymbol(uri, luaText);
}
//开始递归
//如果uri所在文件存在错误,则无法创建成功。这里docProcesser == null
let docProcessor = this.docSymbolMap.get(uri);
if(docProcessor == null || docProcessor.getRequiresArray == null){
Logger.log("get docProcessor or getRequireFiles error!");
return [];
}
//当前文件已经在递归处理中了
if(this.alreadySearchList[uri] == 1){
return [];
}else{
this.alreadySearchList[uri] = 1;
}
// Logger.log("recursiveSearchRequireTree process :" + uri);
// 在引用树上搜索符号,搜索的原则为优先搜索最近的定义,即先搜本文件,然后逆序搜索require的文件,再逆序搜索reference
// 分析自身文件的符号. 本文件,要查找所有符号,引用文件,仅查找global符号。这里要求符号分析分清楚局部和全局符号
let docS = this.docSymbolMap.get(uri);
let retSymbols = docS.searchMatchSymbal(symbolStr, searchMethod, searchRange);
if(retSymbols.length > 0){
//找到了,查找全部符号,压入数组
retSymbArray = retSymbArray.concat(retSymbols);
}
// 逆序搜索require
let reqFiles = docProcessor.getRequiresArray();
for(let idx = reqFiles.length -1; idx >= 0; idx--){
let newuri = Tools.transFileNameToUri(reqFiles[idx]['reqName']);
if(newuri.length === 0) return retSymbArray;
let retSymbols = this.recursiveSearchRequireTree(newuri, symbolStr, searchMethod, searchRange, false);
if(retSymbols != null && retSymbols.length > 0){
retSymbArray = retSymbArray.concat(retSymbols);
}
}
// 逆序搜索reference
let refFiles = docProcessor.getReferencesArray();
for(let idx = refFiles.length -1; idx >= 0; idx--){
let newuri = refFiles[idx];
let retSymbols = this.recursiveSearchRequireTree(newuri, symbolStr, searchMethod, searchRange, false);
if (retSymbols != null && retSymbols.length > 0) {
retSymbArray = retSymbArray.concat(retSymbols);
}
}
return retSymbArray;
}
} | the_stack |
import gp from "./generated-parser";
export = peg;
export as namespace peg;
declare namespace peg {
type Grammar = ast.Grammar;
type GeneratedParser<T = any> = gp.API<T>;
type SyntaxError = gp.SyntaxErrorConstructor;
type SourceLocation = gp.SourceLocation;
/**
* PEG.js version (uses semantic versioning).
*/
const VERSION: string;
/**
* Thrown when the grammar contains an error.
*/
class GrammarError {
name: string;
message: string;
location?: SourceLocation;
constructor( message: string, location?: SourceLocation );
}
/**
* PEG.js AST
*/
namespace ast {
/**
* PEG.js node constructor, used internally by the PEG.js parser to create nodes.
*/
class Node {
type: string;
location: SourceLocation;
constructor( type: string, location: SourceLocation );
}
/**
* The main PEG.js AST class returned by the parser.
*/
class Grammar extends Node {
// Default properties and methods
private readonly _alwaysConsumesOnSuccess: any;
type: "grammar";
comments?: CommentMap;
initializer?: Initializer;
rules: Rule[];
constructor(
initializer: void | Initializer,
rules: Rule[],
comments: void | CommentMap,
location: SourceLocation,
);
findRule( name: string ): Rule | void;
indexOfRule( name: string ): number;
alwaysConsumesOnSuccess( node: Object ): boolean;
// Added by Bytecode generator
literals?: string[];
classes?: string[];
expectations?: string[];
functions?: string[];
// Added by JavaScript generator
code?: string;
}
interface CommentMap {
[ offset: number ]: {
text: string;
multiline: boolean;
location: SourceLocation;
};
}
interface INode extends peg.ast.Node { }
/**
* This type represent's all PEG.js AST node's.
*/
type Object
= Grammar
| Initializer
| Rule
| Named
| Expression;
interface Initializer extends INode {
type: "initializer";
code: string;
}
interface Rule extends INode {
// Default properties
type: "rule",
name: string;
expression: Named | Expression;
// Added by calc-report-failures pass
reportFailures?: boolean;
// Added by inference-match-result pass
match?: number;
// Added by generate-bytecode pass
bytecode?: number[];
}
interface Named extends INode {
type: "named";
name: string;
expression: Expression;
}
type Expression
= ChoiceExpression
| ActionExpression
| SequenceExpression
| LabeledExpression
| PrefixedExpression
| SuffixedExpression
| PrimaryExpression;
interface ChoiceExpression extends INode {
type: "choice";
alternatives: (
ActionExpression
| SequenceExpression
| LabeledExpression
| PrefixedExpression
| SuffixedExpression
| PrimaryExpression
)[];
}
interface ActionExpression extends INode {
type: "action";
expression: (
SequenceExpression
| LabeledExpression
| PrefixedExpression
| SuffixedExpression
| PrimaryExpression
);
code: string;
}
interface SequenceExpression extends INode {
type: "sequence",
elements: (
LabeledExpression
| PrefixedExpression
| SuffixedExpression
| PrimaryExpression
)[];
}
interface LabeledExpression extends INode {
type: "labeled";
pick?: true;
label: string;
expression: (
PrefixedExpression
| SuffixedExpression
| PrimaryExpression
);
}
interface PrefixedExpression extends INode {
type: "text" | "simple_and" | "simple_not";
expression: SuffixedExpression | PrimaryExpression;
}
interface SuffixedExpression extends INode {
type: "optional" | "zero_or_more" | "one_or_more";
expression: PrimaryExpression;
}
type PrimaryExpression
= LiteralMatcher
| CharacterClassMatcher
| AnyMatcher
| RuleReferenceExpression
| SemanticPredicateExpression
| GroupExpression;
interface LiteralMatcher extends INode {
type: "literal";
value: string;
ignoreCase: boolean;
}
interface CharacterClassMatcher extends INode {
type: "class";
parts: ( string[] | string )[];
inverted: boolean;
ignoreCase: boolean;
}
interface AnyMatcher extends INode {
type: "any";
}
interface RuleReferenceExpression extends INode {
type: "rule_ref";
name: string;
}
interface SemanticPredicateExpression extends INode {
type: "semantic_and" | "semantic_not";
code: string;
}
interface GroupExpression extends INode {
type: "group";
expression: LabeledExpression | SequenceExpression;
}
namespace visitor {
interface IVisitorMap<U = void> {
[ key: string ]: any;
grammar?<R = U>( node: Grammar, ...args ): R;
initializer?<R = U>( node: Initializer, ...args ): R;
rule?<R = U>( node: Rule, ...args ): R;
named?<R = U>( node: Named, ...args ): R;
choice?<R = U>( node: ChoiceExpression, ...args ): R;
action?<R = U>( node: ActionExpression, ...args ): R;
sequence?<R = U>( node: SequenceExpression, ...args ): R;
labeled?<R = U>( node: LabeledExpression, ...args ): R;
text?<R = U>( node: PrefixedExpression, ...args ): R;
simple_and?<R = U>( node: PrefixedExpression, ...args ): R;
simple_not?<R = U>( node: PrefixedExpression, ...args ): R;
optional?<R = U>( node: SuffixedExpression, ...args ): R;
zero_or_more?<R = U>( node: SuffixedExpression, ...args ): R;
one_or_more?<R = U>( node: SuffixedExpression, ...args ): R;
literal?<R = U>( node: LiteralMatcher, ...args ): R;
class?<R = U>( node: CharacterClassMatcher, ...args ): R;
any?<R = U>( node: AnyMatcher, ...args ): R;
rule_ref?<R = U>( node: RuleReferenceExpression, ...args ): R;
semantic_and?<R = U>( node: SemanticPredicateExpression, ...args ): R;
semantic_not?<R = U>( node: SemanticPredicateExpression, ...args ): R;
group?<R = U>( node: GroupExpression, ...args ): R;
}
interface IVisitor<R = any> {
( node: Object, ...args ): R;
}
class ASTVisitor implements IVisitorMap {
visit: IVisitor;
}
interface IVisitorBuilder<T = void, R = any> {
( functions: IVisitorMap<T> ): IVisitor<R>;
}
interface IOn {
property( name: string ): IVisitor;
children( name: string ): IVisitor;
}
const build: IVisitorBuilder;
const on: IOn;
}
interface visitor {
ASTVisitor: visitor.ASTVisitor;
build: visitor.IVisitorBuilder;
on: visitor.IOn;
}
}
/**
* A generated PEG.js parser to parse PEG.js grammar source's.
*/
namespace parser {
interface IOptions extends gp.IOptions {
extractComments?: boolean;
reservedWords?: string[];
}
const SyntaxError: SyntaxError;
function parse( input: string, options?: IOptions ): Grammar;
}
/**
* The PEG.js compiler.
*/
namespace compiler {
type FormatOptions = "amd" | "bare" | "commonjs" | "es" | "globals" | "umd";
type OptimizeOptions = "size" | "speed";
type OutputOptions = "parser" | "source";
interface ICompilerOptions<T = OutputOptions> {
[ key: string ]: any;
allowedStartRules?: string[];
cache?: boolean;
context?: { [ name: string ]: any; };
dependencies?: { [ name: string ]: string; };
exportVar?: string;
features?: IGeneratedParserFeatures;
format?: FormatOptions;
header?: string | string[];
optimize?: OptimizeOptions;
output?: T;
trace?: boolean;
}
interface ICompilerPassOptions extends ICompilerOptions {
allowedStartRules: string[];
cache: boolean;
context: { [ name: string ]: any; };
dependencies: { [ name: string ]: string; };
exportVar: string;
features: IGeneratedParserFeatures;
format: FormatOptions;
header: string | string[];
optimize: OptimizeOptions;
output: OutputOptions;
trace: boolean;
}
interface IGeneratedParserFeatures {
[ key: string ]: boolean;
text: boolean;
offset: boolean;
range: boolean;
location: boolean;
expected: boolean;
error: boolean;
filename: boolean;
DefaultTracer: boolean;
}
interface ICompilerPass {
( node: Grammar ): void;
( node: Grammar, session: Session ): void;
( node: Grammar, session: Session, options: ICompilerPassOptions ): void;
}
interface IPassesMap {
[ type: string ]: ICompilerPass[];
}
interface IOpcodes {
[ name: string ]: number;
}
interface ISessionVM {
evalModule( code: string, context?: { [ name: string ]: any; } ): any;
}
interface ISessionMessageEmitter {
( message: string, location: SourceLocation ): any;
}
interface ISessionConfig {
[ key: string ]: any;
opcodes?: IOpcodes;
parser?: GeneratedParser<Grammar>;
passes?: IPassesMap;
visitor?: ast.visitor;
vm?: ISessionVM;
warn?: ISessionMessageEmitter;
error?: ISessionMessageEmitter;
}
class Session implements ISessionConfig {
constructor( config?: ISessionConfig );
parse( input: string, options?: parser.IOptions ): Grammar;
buildVisitor: ast.visitor.IVisitorBuilder;
warn: ISessionMessageEmitter;
error: ISessionMessageEmitter;
fatal: ISessionMessageEmitter;
}
namespace passes {
namespace check {
function reportUndefinedRules( ast: Grammar, session: Session, options: ICompilerPassOptions ): void;
function reportDuplicateRules( ast: Grammar, session: Session ): void;
function reportUnusedRules( ast: Grammar, session: Session, options: ICompilerPassOptions ): void;
function reportDuplicateLabels( ast: Grammar, session: Session ): void;
function reportInfiniteRecursion( ast: Grammar, session: Session ): void;
function reportInfiniteRepetition( ast: Grammar, session: Session ): void;
function reportIncorrectPlucking( ast: Grammar, session: Session ): void;
}
namespace transform {
function removeProxyRules( ast: Grammar, session: Session, options: ICompilerPassOptions ): void;
}
namespace generate {
function calcReportFailures( ast: Grammar, session: Session, options: ICompilerPassOptions ): void;
function inferenceMatchResult( ast: Grammar, session: Session ): void;
function generateBytecode( ast: Grammar, session: Session ): void;
function generateJS( ast: Grammar, session: Session, options: ICompilerPassOptions ): void;
}
}
/**
* Generate's a parser from the PEG.js AST and returns it.
*/
function compile( ast: Grammar, session: Session, options?: ICompilerOptions ): GeneratedParser | string;
/**
* Generate's a parser from the PEG.js AST, then evaluates's the source before returning the parser object.
*/
function compile( ast: Grammar, session: Session, options?: ICompilerOptions<"parser"> ): GeneratedParser;
/**
* Generate's a parser from the PEG.js AST and returns the JavaScript based source.
*/
function compile( ast: Grammar, session: Session, options?: ICompilerOptions<"source"> ): string;
}
// peg.util
interface IStageMap {
[ stage: string ]
: compiler.ICompilerPass[]
| { [ pass: string ]: compiler.ICompilerPass };
}
interface IIterator<R = any> {
( value: any ): R;
( value: any, key: string ): R;
}
interface IArrayUtils {
findIndex( array: any[], condition: IIterator ): number;
find( array: any[], condition: IIterator ): any;
}
interface IJavaScriptUtils {
stringEscape( s: string ): string;
regexpEscape( s: string ): string;
reservedWords: string[];
}
interface IObjectUtils {
clone( source: {} ): {};
each( object: {}, iterator: IIterator<void> ): void;
extend( target: {}, source: {} ): {};
map( object: {}, transformer: IIterator ): {};
values( object: {}, transformer?: IIterator ): any[];
enforceFastProperties( o: {} ): {};
}
interface util extends IArrayUtils, IJavaScriptUtils, IObjectUtils, compiler.ISessionVM {
noop(): void;
convertPasses( stages: IStageMap ): compiler.IPassesMap;
processOptions( options: {}, defaults: {} ): {};
}
const util: util;
// peg.generate
interface IPlugin<T = compiler.OutputOptions> {
[ key: string ]: any;
use( session: compiler.Session ): void;
use( session: compiler.Session, options: IBuildOptions<T> ): void;
}
interface IBuildOptions<T = compiler.OutputOptions> extends compiler.ICompilerOptions<T> {
plugins?: IPlugin<T>[];
parser?: parser.IOptions;
}
/**
* Generate's a parser from the PEG.js grammar and returns it.
*/
function generate( grammar: string, options?: IBuildOptions ): GeneratedParser | string;
/**
* Generate's a parser from the PEG.js grammar, then evaluates's the source before returning the parser object.
*/
function generate( grammar: string, options?: IBuildOptions<"parser"> ): GeneratedParser;
/**
* Generate's a parser from the PEG.js grammar and returns the JavaScript based source.
*/
function generate( grammar: string, options?: IBuildOptions<"source"> ): string;
} | the_stack |
import { DeepPartial, EntityMap, PickWhere, UnknownObject } from '@jovotech/common';
import { JovoResponse, NormalizedOutputTemplate, OutputTemplate } from '@jovotech/output';
import _cloneDeep from 'lodash.clonedeep';
import _merge from 'lodash.merge';
import _set from 'lodash.set';
import { App, AppConfig } from './App';
import { HandleRequest } from './HandleRequest';
import {
BaseComponent,
BaseOutput,
ComponentConfig,
ComponentConstructor,
ComponentData,
DbPluginStoredElementsConfig,
I18NextAutoPath,
I18NextResourcesLanguageKeys,
I18NextResourcesNamespaceKeysOfLanguage,
I18NextTFunctionOptions,
I18NextTFunctionResult,
I18NextTOptions,
I18NextValueAt,
JovoInput,
MetadataStorage,
OutputConstructor,
PersistableSessionData,
PersistableUserData,
Server,
StateStackItem,
} from './index';
import { RequestData } from './interfaces';
import { JovoDevice } from './JovoDevice';
import { JovoHistory, JovoHistoryItem, PersistableHistoryData } from './JovoHistory';
import { JovoRequest } from './JovoRequest';
import { JovoSession } from './JovoSession';
import { JovoUser } from './JovoUser';
import { Platform } from './Platform';
import { JovoRoute } from './plugins/RouterPlugin';
import { forEachDeep } from './utilities';
export type JovoConstructor<
REQUEST extends JovoRequest,
RESPONSE extends JovoResponse,
JOVO extends Jovo<REQUEST, RESPONSE, JOVO, USER, DEVICE, PLATFORM>,
USER extends JovoUser<JOVO>,
DEVICE extends JovoDevice<JOVO>,
PLATFORM extends Platform<REQUEST, RESPONSE, JOVO, USER, DEVICE, PLATFORM>,
> = new (app: App, handleRequest: HandleRequest, platform: PLATFORM, ...args: unknown[]) => JOVO;
export interface JovoPersistableData {
user?: PersistableUserData;
session?: PersistableSessionData;
history?: PersistableHistoryData;
createdAt?: string;
updatedAt?: string;
}
export interface JovoComponentInfo<
DATA extends ComponentData = ComponentData,
CONFIG extends UnknownObject = UnknownObject,
> {
data: DATA;
config?: CONFIG;
}
export interface DelegateOptions<
CONFIG extends UnknownObject | undefined = UnknownObject | undefined,
EVENTS extends string = string,
> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
resolve: Record<EVENTS, string | ((this: BaseComponent, ...args: any[]) => any)>;
config?: CONFIG;
}
export function registerPlatformSpecificJovoReference<
KEY extends keyof Jovo,
REQUEST extends JovoRequest,
RESPONSE extends JovoResponse,
JOVO extends Jovo<REQUEST, RESPONSE, JOVO, USER, DEVICE, PLATFORM>,
USER extends JovoUser<JOVO>,
DEVICE extends JovoDevice<JOVO>,
PLATFORM extends Platform<REQUEST, RESPONSE, JOVO, USER, DEVICE, PLATFORM>,
>(key: KEY, jovoClass: JovoConstructor<REQUEST, RESPONSE, JOVO, USER, DEVICE, PLATFORM>): void {
Object.defineProperty(Jovo.prototype, key, {
get(): Jovo[KEY] | undefined {
return this instanceof jovoClass ? this : undefined;
},
});
}
export abstract class Jovo<
REQUEST extends JovoRequest = JovoRequest,
RESPONSE extends JovoResponse = JovoResponse,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
JOVO extends Jovo<REQUEST, RESPONSE, JOVO, USER, DEVICE, PLATFORM> = any,
USER extends JovoUser<JOVO> = JovoUser<JOVO>,
DEVICE extends JovoDevice<JOVO> = JovoDevice<JOVO>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
PLATFORM extends Platform<REQUEST, RESPONSE, JOVO, USER, DEVICE, PLATFORM> = any,
> {
$request: REQUEST;
$input: JovoInput;
$output: OutputTemplate[];
$response?: RESPONSE | RESPONSE[];
$data: RequestData;
$device: DEVICE;
$entities: EntityMap;
$history: JovoHistory;
$route?: JovoRoute;
$session: JovoSession;
$user: USER;
$cms: UnknownObject;
constructor(
readonly $app: App,
readonly $handleRequest: HandleRequest,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
readonly $platform: PLATFORM,
) {
this.$request = this.$platform.createRequestInstance($handleRequest.server.getRequestObject());
this.$input = this.$request.getInput();
this.$output = [];
this.$data = {};
this.$device = this.$platform.createDeviceInstance(this as unknown as JOVO);
this.$entities = this.getEntityMap();
this.$history = new JovoHistory();
this.$session = this.getSession();
this.$user = this.$platform.createUserInstance(this as unknown as JOVO);
this.$cms = {};
}
get $config(): AppConfig {
return this.$handleRequest.config;
}
get $server(): Server {
return this.$handleRequest.server;
}
get $plugins(): HandleRequest['plugins'] {
return this.$handleRequest.plugins;
}
get $state(): JovoSession['state'] {
return this.$session.state;
}
get $subState(): string | undefined {
if (!this.$state?.length) return;
return this.$state[this.$state.length - 1]?.subState;
}
set $subState(value: string | undefined) {
if (!this.$state?.length) return;
this.$state[this.$state.length - 1].subState = value;
}
get $component(): JovoComponentInfo {
// global components should not have component-data
if (!this.$state?.length) {
return {
data: {},
};
}
const latestStateStackItem = this.$state[this.$state.length - 1];
return {
get data(): ComponentData {
if (!latestStateStackItem.data) {
latestStateStackItem.data = {};
}
return latestStateStackItem.data;
},
set data(value: ComponentData) {
if (!latestStateStackItem.data) {
latestStateStackItem.data = {};
}
latestStateStackItem.data = value;
},
get config(): UnknownObject | undefined {
const deserializedStateConfig = _cloneDeep(latestStateStackItem.config);
if (deserializedStateConfig) {
// deserialize all found Output-constructors
forEachDeep(deserializedStateConfig, (value, path) => {
// TODO: check restriction
if (
typeof value === 'object' &&
value.type === 'output' &&
value.name &&
Object.keys(value).length === 2
) {
const outputMetadata = MetadataStorage.getInstance().getOutputMetadataByName(
value.name,
);
if (!outputMetadata) {
// TODO determine what to do!
return;
}
_set(deserializedStateConfig, path, outputMetadata.target);
}
});
}
return deserializedStateConfig;
},
set config(value: UnknownObject | undefined) {
latestStateStackItem.config = value;
},
};
}
$t<
PATH extends string,
LANGUAGE extends I18NextResourcesLanguageKeys | string = I18NextResourcesLanguageKeys,
NAMESPACE extends
| I18NextResourcesNamespaceKeysOfLanguage<LANGUAGE>
| string = I18NextResourcesNamespaceKeysOfLanguage<LANGUAGE>,
>(
path:
| I18NextAutoPath<PATH, LANGUAGE, NAMESPACE>
| PATH
| Array<I18NextAutoPath<PATH, LANGUAGE, NAMESPACE> | PATH>,
options?: I18NextTOptions<LANGUAGE, NAMESPACE>,
): I18NextValueAt<PATH, LANGUAGE, NAMESPACE>;
$t<FORCED_RESULT>(path: string | string[], options?: I18NextTFunctionOptions): FORCED_RESULT;
$t(path: string | string[], options?: I18NextTFunctionOptions): I18NextTFunctionResult {
if (!options) {
options = {};
}
if (!options.lng) {
options.lng = this.$request.getLocale();
}
if (!options.platform) {
options.platform = this.$platform.id;
}
return this.$app.i18n.t(path, options);
}
async $send(outputTemplateOrMessage: OutputTemplate | OutputTemplate[] | string): Promise<void>;
async $send<OUTPUT extends BaseOutput>(
outputConstructor: OutputConstructor<OUTPUT, REQUEST, RESPONSE, this>,
options?: DeepPartial<OUTPUT['options']>,
): Promise<void>;
async $send<OUTPUT extends BaseOutput>(
outputConstructorOrTemplateOrMessage:
| string
| OutputConstructor<OUTPUT, REQUEST, RESPONSE, this>
| OutputTemplate
| OutputTemplate[],
options?: DeepPartial<OUTPUT['options']>,
): Promise<void> {
let newOutput: OutputTemplate | OutputTemplate[];
if (typeof outputConstructorOrTemplateOrMessage === 'function') {
const outputInstance = new outputConstructorOrTemplateOrMessage(this, options);
const output = await outputInstance.build();
// overwrite reserved properties of the built object i.e. message
NormalizedOutputTemplate.getKeys().forEach((key) => {
if (options?.[key]) {
if (Array.isArray(output)) {
output[output.length - 1][key] =
key === 'platforms'
? _merge({}, output[output.length - 1].platforms || {}, options[key])
: options[key];
} else {
output[key] =
key === 'platforms' ? _merge({}, output[key] || {}, options[key]) : options[key];
}
}
});
newOutput = output;
} else if (typeof outputConstructorOrTemplateOrMessage === 'string') {
newOutput = {
message: outputConstructorOrTemplateOrMessage,
};
} else {
newOutput = outputConstructorOrTemplateOrMessage;
}
// push the new OutputTemplate(s) to $output
Array.isArray(newOutput) ? this.$output.push(...newOutput) : this.$output.push(newOutput);
}
async $redirect<
COMPONENT extends BaseComponent,
HANDLER extends Exclude<
// eslint-disable-next-line @typescript-eslint/ban-types
keyof PickWhere<COMPONENT, Function>,
keyof BaseComponent
>,
>(constructor: ComponentConstructor<COMPONENT>, handler?: HANDLER): Promise<void>;
async $redirect(
constructorOrName: ComponentConstructor | string,
handler?: string,
): Promise<void>;
async $redirect(
constructorOrName: ComponentConstructor | string,
handler?: string,
): Promise<void> {
const componentName =
typeof constructorOrName === 'function' ? constructorOrName.name : constructorOrName;
// get the node with the given name relative to the currently active component-node
const componentNode = this.$handleRequest.componentTree.getNodeRelativeToOrFail(
componentName,
this.$handleRequest.activeComponentNode?.path,
);
// update the state-stack if the component is not global
if (!componentNode.metadata.isGlobal) {
const stackItem: StateStackItem = {
component: componentNode.path.join('.'),
};
if (!this.$state?.length) {
// initialize the state-stack if it is empty or does not exist
this.$session.state = [stackItem];
} else {
// replace last item in stack
this.$state[this.$state.length - 1] = stackItem;
}
}
// update the active component node in handleRequest to keep track of the state
this.$handleRequest.activeComponentNode = componentNode;
// execute the component's handler
await componentNode.executeHandler({
jovo: this.getJovoReference(),
handler,
});
}
async $delegate<COMPONENT extends BaseComponent>(
constructor: ComponentConstructor<COMPONENT>,
options: DelegateOptions<ComponentConfig<COMPONENT>>,
): Promise<void>;
async $delegate(
constructorOrName: ComponentConstructor | string,
options: DelegateOptions,
): Promise<void>;
async $delegate(
constructorOrName: ComponentConstructor | string,
options: DelegateOptions,
): Promise<void> {
const componentName =
typeof constructorOrName === 'function' ? constructorOrName.name : constructorOrName;
// get the node with the given name relative to the currently active component-node
const componentNode = this.$handleRequest.componentTree.getNodeRelativeToOrFail(
componentName,
this.$handleRequest.activeComponentNode?.path,
);
// if the component that is currently being executed is global
if (this.$handleRequest.activeComponentNode?.metadata?.isGlobal) {
// make sure there is a stack
if (!this.$session.state) {
this.$session.state = [];
}
// add the current component
this.$session.state.push({
component: this.$handleRequest.activeComponentNode.path.join('.'),
});
}
// serialize all values in 'resolve'
const serializableResolve: Record<string, string> = {};
for (const key in options.resolve) {
if (options.resolve.hasOwnProperty(key)) {
const value = options.resolve[key];
serializableResolve[key] = typeof value === 'string' ? value : value.name;
}
}
// serialize the whole config
const serializableConfig = _cloneDeep(options.config);
if (serializableConfig) {
forEachDeep(serializableConfig, (value, path) => {
// serialize all passed Output-constructors
if (value?.prototype instanceof BaseOutput) {
const outputMetadata = MetadataStorage.getInstance().getOutputMetadata(value);
if (!outputMetadata) {
// TODO determine what to do!
return;
}
_set(serializableConfig, path, { type: 'output', name: outputMetadata.name });
}
});
}
// push the delegating component to the state-stack
if (!this.$session.state) {
this.$session.state = [];
}
this.$session.state.push({
resolve: serializableResolve,
config: serializableConfig,
component: componentNode.path.join('.'),
});
// update the active component node in handleRequest to keep track of the state
this.$handleRequest.activeComponentNode = componentNode;
// execute the component's handler
await componentNode.executeHandler({
jovo: this.getJovoReference(),
});
}
// TODO determine whether an error should be thrown if $resolve is called from a context outside a delegation
async $resolve<ARGS extends unknown[]>(eventName: string, ...eventArgs: ARGS): Promise<void> {
if (!this.$state) {
return;
}
const currentStateStackItem = this.$state[this.$state.length - 1];
const previousStateStackItem = this.$state[this.$state.length - 2];
// make sure the state-stack exists and it long enough
if (!currentStateStackItem?.resolve || !previousStateStackItem) {
return;
}
const resolvedHandler = currentStateStackItem.resolve[eventName];
const previousComponentPath = previousStateStackItem.component.split('.');
// get the previous node
const previousComponentNode =
this.$handleRequest.componentTree.getNodeAtOrFail(previousComponentPath);
// if previous component is global, remove another item from the stack to remove the global component
if (previousComponentNode.metadata.isGlobal) {
this.$state.pop();
}
// remove the latest item from the state-stack
this.$state.pop();
// update the active component node in handleRequest to keep track of the state
this.$handleRequest.activeComponentNode = previousComponentNode;
// execute the component's handler
await previousComponentNode.executeHandler({
jovo: this.getJovoReference(),
handler: resolvedHandler,
callArgs: eventArgs,
});
}
getSession(): JovoSession {
const session = this.$request.getSession();
return session instanceof JovoSession ? session : new JovoSession(session);
}
getEntityMap(): EntityMap {
return this.$input.entities || this.$input.nlu?.entities || {};
}
getPersistableData(): JovoPersistableData {
return {
user: this.$user.getPersistableData(),
session: this.$session.getPersistableData(),
history: this.$history.getPersistableData(),
createdAt: new Date(this.$user.createdAt).toISOString(),
updatedAt: new Date().toISOString(),
};
}
setPersistableData(data: JovoPersistableData, config?: DbPluginStoredElementsConfig): void {
const isStoredElementEnabled = (key: 'user' | 'session' | 'history') => {
const value = config?.[key];
return typeof value === 'object' ? value.enabled !== false : !!value;
};
if (isStoredElementEnabled('user')) {
this.$user.setPersistableData(data.user);
}
if (isStoredElementEnabled('session')) {
this.$session.setPersistableData(data.session, config?.session);
}
if (isStoredElementEnabled('history')) {
this.$history.setPersistableData(data.history);
}
this.$user.createdAt = new Date(data?.createdAt || new Date());
this.$user.updatedAt = new Date(data?.updatedAt || new Date());
}
getCurrentHistoryItem(): JovoHistoryItem {
return {
request: this.$request,
input: this.$input,
state: this.$state,
entities: this.$entities,
output: this.$output,
response: this.$response,
};
}
protected getJovoReference(): Jovo {
return (this as { jovo?: Jovo })?.jovo || (this as unknown as Jovo);
}
} | the_stack |
import {
builder,
BuilderComponent,
BuilderContent,
Image,
} from '@builder.io/react';
import React from 'react';
import Head from 'next/head';
import { renderLink, RenderLink } from '../../functions/render-link';
import { TextLink } from '../../components/text-link';
import { theme } from '../../constants/theme';
import { mediumBreakpointMediaQuery } from '../../constants/breakpoints';
import { ReadProgress } from '../../components/read-progress';
import AtvImg from '../../components/atv-image';
import { footerBuilderEntryId } from '../../constants/footer-builder-entry-id';
import { GetStaticPaths, GetStaticProps, GetStaticPropsContext } from 'next';
builder.init('YJIGb4i01jvw0SRdL5Bt');
function BlogArticle(
{ article, header, articles, footer, isEditing }: any /* TODO: types */,
) {
const cellWidth = 350;
const cellSpace = 20;
const cellAspectRatio = 3 / 4;
const cellImageHeight = cellWidth * cellAspectRatio;
return (
<div
css={{
display: 'flex',
flexDirection: 'column',
backgroundColor: '#f5f4ed',
fontSize: 16,
code: {
fontSize: 14,
lineHeight: '0.9em',
},
}}
>
{header && (
<BuilderComponent
renderLink={renderLink}
name="docs-header"
content={header}
/>
)}
{!article && !isEditing ? (
<>
<div
css={{
textAlign: 'center',
padding: 50,
marginTop: 50,
marginBottom: 50,
}}
>
<div>
Article not found.{' '}
<TextLink href="/blog">Back to the blog</TextLink>
</div>
<div css={{ marginTop: 30 }}>
<img
css={{
maxWidth: '80vw',
borderRadius: 4,
overflow: 'hidden',
boxShadow:
'0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0,0,0,0.22)',
}}
src="https://media.giphy.com/media/RHzqdZJztOu7S/giphy.gif"
/>
</div>
</div>
</>
) : (
<BuilderContent
key={article?.id}
modelName="blog-article"
content={article}
>
{(data, loading, article) => (
<>
{!article && (
<Head>
<meta key="robots" name="robots" content="noindex" />
</Head>
)}
{article && (
<Head>
<title>{article.data.title}</title>
<meta name="description" content={article.data.blurb} />
<meta key="og:type" property="og:type" content="article" />
<meta
key="og:title"
property="og:title"
content={article.data.title}
/>
<meta
key="og:description"
property="og:description"
content={article.data.blurb}
/>
<meta
key="og:image"
property="og:image"
content={article.data.image}
/>
<meta
key="twitter:card"
property="twitter:card"
content="summary_large_image"
/>
<meta
key="twitter:title"
property="twitter:title"
content={article.data.title}
/>
<meta
key="twitter:description"
property="twitter:description"
content={article.data.blurb}
/>
<meta
key="twitter:image"
property="twitter:image"
content={article.data.image}
/>
</Head>
)}
<ReadProgress containerSelector=".blog-article-container" />
<div
css={{
padding: 50,
width: '100%',
maxWidth: 800,
margin: '0 auto',
[mediumBreakpointMediaQuery]: {
padding: 15,
},
'.builder-text': {
lineHeight: '1.7em',
},
}}
>
{article && !article.data.fullPage && (
<div>
<TextLink
css={{
color: '#999',
}}
href="/blog"
>
‹ Back to blog
</TextLink>
<div css={{ display: 'flex', alignItems: 'center' }}>
<div>
<h1
css={{
fontSize: 40,
marginTop: 30,
[mediumBreakpointMediaQuery]: {
fontSize: 32,
},
}}
>
{article.data.title}
</h1>
<div css={{ marginTop: 10 }}>
<span css={{ opacity: 0.7 }}>By</span>{' '}
<a
target="_blank"
rel="noopenner"
href={article.data.author.value?.data.url}
css={{
color: theme.colors.primary,
}}
>
{article.data.author.value?.data.fullName}
</a>
</div>
</div>
</div>
</div>
)}
<div
css={{
borderRadius: 4,
marginTop: article?.data.fullPage ? undefined : 30,
}}
>
<div className="blog-article-container">
<BuilderComponent
renderLink={renderLink}
name="blog-article"
content={article}
/>
</div>
<TextLink
css={{
color: theme.colors.primary,
marginTop: 60,
fontWeight: 500,
fontSize: 18,
display: 'block',
textAlign: 'center',
}}
href="/blog"
>
Read more on the blog
</TextLink>
<div
css={{
width: '100vw',
marginLeft: 'calc(50% - 50vw)',
display: 'flex',
flexDirection: 'column',
}}
>
<div
css={{
width: '100%',
alignSelf: 'stretch',
flexGrow: 1,
maxWidth: 1200,
display: 'flex',
justifyContent: 'center',
flexWrap: 'wrap',
alignItems: 'stretch',
marginLeft: 'auto',
marginRight: 'auto',
marginTop: 80,
marginBottom: 20,
textAlign: 'center',
paddingBottom: 50,
[mediumBreakpointMediaQuery]: {
marginLeft: 0,
marginRight: 0,
},
}}
>
{articles.map((item: any, index: number) => {
const makeBig = index === 0;
return (
<RenderLink
css={{
cursor: 'pointer',
display: 'inline-block',
}}
key={item.id}
href={`/blog/${item.data.handle}`}
>
<AtvImg
css={{
maxWidth: 'calc(100vw - 30px)',
marginRight: cellSpace,
marginBottom: cellSpace,
width: cellWidth,
}}
widthMultiple={
makeBig ? cellWidth / 2 : cellWidth
}
heightMultiple={
makeBig ? cellWidth / 2 : cellWidth
}
>
<div
css={{
display: 'block',
height: cellImageHeight,
position: 'relative',
overflow: 'hidden',
}}
>
<Image
aspectRatio={0.5}
backgroundSize="cover"
image={item.data.image}
lazy
/>
</div>
<div
css={{
padding: 20,
textAlign: 'center',
}}
>
<div
css={{
fontSize: 16,
paddingLeft: 5,
paddingRight: 5,
}}
>
{item.data.title}
</div>
</div>
</AtvImg>
</RenderLink>
);
})}
</div>
</div>
</div>
</div>
</>
)}
</BuilderContent>
)}
<div css={{ maxWidth: 1200, width: '100%', margin: 'auto' }}>
<BuilderComponent name="symbol" content={footer} />
</div>
</div>
);
}
export const getStaticPaths: GetStaticPaths = async () => {
const results = await builder.getAll('blog-article', {
key: 'articles:all',
fields: 'data.handle',
});
return {
paths: results
.map((item) => ({ params: { article: item.data!.handle || '' } }))
.concat([{ params: { article: '_' /* For previewing and editing */ } }]),
fallback: true,
};
};
export const getStaticProps: GetStaticProps = async (context) => {
const props = await getContent(context);
return { revalidate: 1, props, notFound: !props.article };
};
const getContent = async (context: GetStaticPropsContext) => {
// Don't target on url and device for better cache efficiency
const targeting = { urlPath: '/blog', device: '_' } as any;
const [article, header, footer, articles] = await Promise.all([
builder
.get('blog-article', {
userAttributes: targeting,
key: context.params!.article as string,
query: {
// Get the specific article by handle
'data.handle': context.params!.article,
},
...{
options: {
includeRefs: true,
} as any,
},
})
.promise(),
builder.get('docs-header', { userAttributes: targeting }).promise(),
builder
.get('symbol', {
userAttributes: { ...targeting },
entry: footerBuilderEntryId,
})
.promise(),
builder.getAll('blog-article', {
key: `blog-articles:all:_:4`,
fields: 'data.image,data.handle,data.title',
limit: 5,
userAttributes: targeting,
options: {
noTargeting: true,
},
query: {
'data.hideFromList': { $ne: true },
},
}),
]);
return {
article: article || null,
header: header || null,
footer: footer || null,
isEditing: context.params!.article === '_',
articles: articles
.filter(
(item: any) => item.data && item.data?.handle !== article?.data.handle,
)
.slice(0, 3),
};
};
export default BlogArticle; | the_stack |
export const rules = [
{
title: 'Break long queries into multiple lines',
explanation: `What is considered too long depends on your application.
When breaking the query, not all parts of the traversal have to be broken up. First, divide the query into logical groups, based on which steps belong naturally together. For instance, every set of steps which end with an as()-step often belong together, as they together form a new essential step in the query.
If anoymous traversals are passed as arguments to another step, like a filter()-step, and it's causing the line to be too long, first split the line at the commas. Only if the traversal arguments are still too long, consider splitting them further.`,
example: `// Good (80 characters max width)
g.V().hasLabel('person').where(outE("created").count().is(P.gte(2))).count()
// Good (50 characters max width)
g.V().
hasLabel('person').
where(outE("created").count().is(P.gte(2))).
count()
// Good (30 characters max width)
g.V().
hasLabel('person').
where(
outE("created").
count().
is(P.gte(2))).
count()`,
},
{
title: 'Use soft tabs (spaces) for indentation',
explanation: 'This ensures that your code looks the same for anyone, regardless of their text editor settings.',
example: `// Bad - indented using hard tabs
g.V().
hasLabel('person').as('person').
properties('location').as('location').
select('person','location').
by('name').
by(valueMap())
// Good - indented using spaces
g.V().
∙∙hasLabel('person').as('person').
∙∙properties('location').as('location').
∙∙select('person','location').
∙∙∙∙by('name').
∙∙∙∙by(valueMap())`,
},
{
title: 'Use two spaces for indentation',
explanation:
'Two spaces makes the intent of the indent clear, but does not waste too much space. Of course, more spaces are allowed when indenting from an already indented block of code.',
example: `// Bad - Indented using four spaces
g.V().
hasLabel('person').as('person').
properties('location').as('location').
select('person','location').
by('name').
by(valueMap())
// Good - Indented using two spaces
g.V().
hasLabel('person').as('person').
properties('location').as('location').
select('person','location').
by('name').
by(valueMap())`,
},
{
title: 'Use indents wisely',
explanation: `No newline should ever have the same indent as the line starting with the traversal source g.
Use indents when the step in the new line is a modulator of a previous line.
Use indents when the content in the new line is an argument of a previous step.
If multiple anonymous traversals are passed as arguments to a function, each newline which is not the first step of the traversal should be indented to make it more clear where the distinction between each argument goes. If this is the case, but the newline would already be indented because the step in the content in the new line is the argument of a previous step, there is no need to double-indent.
Don't be tempted to add extra indentation to vertically align a step with a step in a previous line.`,
example: `// Bad - No newline should have the same indent as the line starting with the traversal source g
g.V().
group().
by().
by(bothE().count())
// Bad - Modulators of a step on a previous line should be indented
g.V().
group().
by().
by(bothE().count())
// Good
g.V().
group().
by().
by(bothE().count())
// Bad - You have ignored the indent rules to achieve the temporary satisfaction of vertical alignment
g.V().local(union(identity(),
bothE().count()).
fold())
// Good
g.V().
local(
union(
identity(),
bothE().count()).
fold())
// Bad - When multiple anonymous traversals are passed as arguments to a function, each newline which is not the first of line of the step should be indented to make it more clear where the distinction between each argument goes.
g.V().
has('person','name','marko').
fold().
coalesce(
unfold(),
addV('person').
property('name','marko').
property('age',29))
// Good - We make it clear that the coalesce step takes two traversals as arguments
g.V().
has('person','name','marko').
fold().
coalesce(
unfold(),
addV('person').
property('name','marko').
property('age',29))`,
},
{
title: 'Keep as()-steps at the end of each line',
explanation: `The end of the line is a natural place to assign a label to a step. It's okay if the as()-step is in the middle of the line if there are multiple consecutive label assignments, or if the line is so short that a newline doesn't make sense. Maybe a better way to put it is to not start a line with an as()-step, unless you're using it inside a match()-step of course.`,
example: `// Bad
g.V().
as('a').
out('created').
as('b').
select('a','b')
// Good
g.V().as('a').
out('created').as('b').
select('a','b')
// Good
g.V().as('a').out('created').as('b').select('a','b')`,
},
{
title: 'Add linebreak after punctuation, not before',
explanation: `While adding the linebreak before the punctuation looks good in most cases, it introduces alignment problems when not all lines start with a punctuation. You never know if the next line should be indented relative to the punctuation of the previous line or the method of the previous line. Switching between having the punctuation at the start or the end of the line depending on whether it works in a particular case requires much brainpower (which we don't have), so it's better to be consistent. Adding the punctuation before the linebreak also means that you can know if you have reached the end of the query without reading the next line.`,
example: `// Bad - Looks okay, though
g.V().has('name','marko')
.out('knows')
.has('age', gt(29))
.values('name')
// Good
g.V().
has('name','marko').
out('knows').
has('age', gt(29)).
values('name')
// Bad - Punctuation at the start of the line makes the transition from filter to select to count too smooth
g.V()
.hasLabel("person")
.group()
.by(values("name", "age").fold())
.unfold()
.filter(
select(values)
.count(local)
.is(gt(1)))
// Good - Keeping punctuation at the end of each line, more clearly shows the query structure
g.V().
hasLabel("person").
group().
by(values("name", "age").fold()).
unfold().
filter(
select(values).
count(local).
is(gt(1)))`,
},
{
title: 'Add linebreak and indentation for nested traversals which are long enough to span multiple lines',
explanation: '',
example: `// Bad - Not newlining the first argument of a function whose arguments span over multipe lines causes the arguments to not align.
g.V().
hasLabel("person").
groupCount().
by(values("age").
choose(is(lt(28)),
constant("young"),
choose(is(lt(30)),
constant("old"),
constant("very old"))))
// Bad - We talked about this in the indentation section, didn't we?
g.V().
hasLabel("person").
groupCount().
by(values("age").
choose(is(lt(28)),
constant("young"),
choose(is(lt(30)),
constant("old"),
constant("very old"))))
// Good
g.V().
hasLabel("person").
groupCount().
by(
values("age").
choose(
is(lt(28)),
constant("young"),
choose(
is(lt(30)),
constant("old"),
constant("very old"))))`,
},
{
title: 'Place all trailing parentheses on a single line instead of distinct lines',
explanation:
'Aligning the end parenthesis with the step to which the start parenthesis belongs might make it easier to check that the number of parentheses is correct, but looks ugly and wastes a lot of space.',
example: `// Bad
g.V().
hasLabel("person").
groupCount().
by(
values("age").
choose(
is(lt(28)),
constant("young"),
choose(
is(lt(30)),
constant("old"),
constant("very old")
)
)
)
// Good
g.V().
hasLabel("person").
groupCount().
by(
values("age").
choose(
is(lt(28)),
constant("young"),
choose(
is(lt(30)),
constant("old"),
constant("very old"))))`,
},
{
title: 'Use // for single line comments. Place single line comments on a newline above the subject of the comment.',
explanation: '',
example: `// Bad
g.V().
has('name','alice').out('bought'). // Find everything that Alice has bought
in('bought').dedup().values('name') // Find everyone who have bought some of the same things as Alice
// Good
g.V().
// Find everything that Alice has bought
has('name','alice').out('bought').
// Find everyone who have bought some of the same things as Alice
in('bought').dedup().values('name')`,
},
{
title: 'Use single quotes for strings',
explanation:
'Use single quotes for literal string values. If the string contains double quotes or single quotes, surround the string with the type of quote which creates the fewest escaped characters.',
example: `// Bad - Use single quotes where possible
g.V().has("Movie", "name", "It's a wonderful life")
// Bad - Escaped single quotes are even worse than double quotes
g.V().has('Movie', 'name', 'It\\'s a wonderful life')
// Good
g.V().has('Movie', 'name', "It's a wonderful life")`,
},
{
title: 'Write idiomatic Gremlin code',
explanation: `If there is a simpler way, do it the simpler way. Use the Gremlin methods for what they're worth.`,
example: `// Bad
g.V().outE().inV()
// Good
g.V().out()
// Bad
g.V().
has('name', 'alice').
outE().hasLabel('bought').inV().
values('name')
// Good
g.V().
has('name','alice').
out('bought').
values('name')
// Bad
g.V().hasLabel('person').has('name', 'alice')
// Good
g.V().has('person', 'name', 'alice')`,
},
]; | the_stack |
namespace LiteMol.Plugin.Views.Entity {
"use strict";
import BEntity = Bootstrap.Entity
export const VisibilityControl = (props: { entity: BEntity.Any }) => {
let e = props.entity;
let command = () => {
Bootstrap.Command.Entity.SetVisibility.dispatch(e.tree!.context, { entity: e, visible: e.state.visibility === BEntity.Visibility.Full ? false : true} );
}
let state = e.state.visibility;
let cls: string, title: string;
if (state === BEntity.Visibility.Full) { cls = 'full'; title = 'Hide' }
else if (state === BEntity.Visibility.None) { cls = 'none'; title = 'Show' }
else { cls = 'partial'; title = 'Show' }
return <Controls.Button title={title} onClick={command} icon='visual-visibility' style='link'
customClass={`lm-entity-tree-entry-toggle-visible lm-entity-tree-entry-toggle-visible-${cls}` } />;
}
class Entity extends ObserverView<{ node: BEntity.Any, tree: Tree }, {}> {
private renderedVersion = -1;
private ctx: Bootstrap.Context;
private root: HTMLDivElement | undefined = void 0;
private ensureVisible() {
if (this.ctx.currentEntity === this.props.node) {
if (this.root) this.props.tree.scrollIntoView(this.root);
}
}
componentDidMount() {
this.ensureVisible();
}
componentDidUpdate() {
this.ensureVisible();
}
get node() {
return this.props.node;
}
shouldComponentUpdate(nextProps: { node: BEntity.Any, tree: Tree }, nextState: { version: number }, nextContext: any) {
return this.node.version !== this.renderedVersion;
}
componentWillMount() {
this.ctx = this.props.node.tree!.context;
let node = this.node;
//this.state.version = node.version;
this.subscribe(Bootstrap.Event.Tree.NodeUpdated.getStream(this.ctx), e => {
if (e.data === node) {
if (node.version !== this.renderedVersion) this.forceUpdate();
if (this.ctx.currentEntity === node && this.isFullyBound()) {
setTimeout(Bootstrap.Command.Entity.SetCurrent.dispatch(this.ctx, node.children[0]), 0);
}
}
});
}
private highlight(isOn: boolean) {
let node = this.node;
Bootstrap.Command.Entity.Highlight.dispatch(this.ctx, { entities: this.ctx.select(Bootstrap.Tree.Selection.byValue(node).subtree()), isOn: isOn });
}
private row(childCount: number) {
let entity = this.props.node;
let props = entity.props;
let isRoot = entity.parent === entity;
let title = props.label;
if (props.description) title += ' (' + props.description + ')';
return <div className={'lm-entity-tree-entry-body' + (this.ctx.currentEntity === entity ? ' lm-entity-tree-entry-current' : '') + (this.isOnCurrentPath() ? ' lm-entity-tree-entry-current-path' : '')}
ref={root => this.root = root!}>
<Badge type={entity.type.info} />
<div className='lm-entity-tree-entry-label-wrap'>
<Controls.Button onClick={() => Bootstrap.Command.Entity.SetCurrent.dispatch(this.ctx, entity) }
customClass='lm-entity-tree-entry-label' style='link' title={title}>
<span>
{props.label}
<span className='lm-entity-tree-entry-label-tag'>
{props.description ? ' ' + props.description : void 0}
</span>
</span>
</Controls.Button>
</div>
{ !isRoot || childCount
? <Controls.Button title='Remove' onClick={() => Bootstrap.Command.Tree.RemoveNode.dispatch(entity.tree!.context, entity) } icon='remove' style='link' customClass='lm-entity-tree-entry-remove' />
: void 0 }
{ isRoot && !childCount ? void 0 : <VisibilityControl entity={entity} /> }
</div>;
//<RemoveEntityControl entity={entity} />
}
private renderFlat() {
let node = this.node;
let children: any[] = [];
for (let c of node.children) {
children.push(<Entity key={c.id} node={c} tree={this.props.tree} />);
}
return <div key={node.id}>
{children}
</div>;
}
private isFullyBound() {
let isFullyBound = true;
for (let c of this.node.children) {
if (!c.transform.props.isBinding) {
isFullyBound = false;
break;
}
}
return isFullyBound && this.node.children.length === 1;
}
private isOnCurrentPath() {
if (!this.ctx.currentEntity) return false;
let n = this.ctx.currentEntity.parent;
let node = this.node;
while (n.parent !== n) {
if (n === node) return true;
n = n.parent;
}
return false;
}
render() {
let node = this.node;
this.renderedVersion = node.version;
let isRoot = node.parent === node;
if (this.isFullyBound()) return this.renderFlat();
let state = node.state;
let childCount = 0;
let children: any[] = [];
for (let c of node.children) {
if (c.isHidden) continue;
if (!isRoot) children.push(<Entity key={c.id} node={c} tree={this.props.tree} />);
childCount++;
}
let expander: any;
if (children.length) {
expander = state.isCollapsed
? <Controls.Button style='link' title='Expand' onClick={() => Bootstrap.Command.Entity.ToggleExpanded.dispatch(this.ctx, node) } icon='expand' customClass='lm-entity-tree-entry-toggle-group' />
: <Controls.Button style='link' title='Collapse' onClick={() => Bootstrap.Command.Entity.ToggleExpanded.dispatch(this.ctx, node) } icon='collapse' customClass='lm-entity-tree-entry-toggle-group' />;
} else {
if (/*BEntity.isVisual(node) &&*/ node.state.visibility === BEntity.Visibility.Full && node.type.info.traits.isFocusable) {
expander = <Controls.Button style='link' icon='focus-on-visual' title='Focus'
onClick={() => Bootstrap.Command.Entity.Focus.dispatch(this.ctx, this.ctx.select(node) ) }
customClass='lm-entity-tree-entry-toggle-group' />
}
}
let main = <div className={'lm-entity-tree-entry'}
onMouseEnter={() => this.highlight(true)}
onMouseLeave={() => this.highlight(false)}
onTouchStart={() => setTimeout(() => this.highlight(true), 1000 / 30) }
onTouchCancel={() => setTimeout(() => this.highlight(false), 1000 / 30) }
onTouchEnd={() => setTimeout(() => this.highlight(false), 1000 / 30) } >
{expander}
{this.row(childCount)}
</div>;
return <div key={node.id} className={(isRoot ? 'lm-entity-tree-root' : '')}>
{main}
<div className='lm-entity-tree-children-wrap' style={{ display: state.isCollapsed ? 'none' : 'block' }}>
{children}
</div>
</div>
}
}
export class Tree extends View<Bootstrap.Components.Component<{}>, {}, {}> {private renderedVersion = -1;
private root: HTMLDivElement | undefined = void 0;
scrollIntoView(element: Element) {
const node = this.root;
if (!node || !element) return;
try {
const parent = node.getBoundingClientRect();
const rect = element.getBoundingClientRect();
const scrollTop = node.scrollTop;
if (rect.top < parent.top) {
const d = parent.top - rect.top;
node.scrollTop = scrollTop - d;
} else if (rect.bottom > parent.bottom) {
const d = rect.bottom - parent.bottom;
node.scrollTop = scrollTop + d;
}
} catch(e) {
}
}
componentWillMount() {
const node = this.controller.context.tree.root;
const ctx = node.tree!.context;
//this.state.version = node.version;
this.subscribe(Bootstrap.Event.Tree.NodeUpdated.getStream(ctx), e => {
if (e.data === node) {
if (node.version !== this.renderedVersion) this.forceUpdate();
}
});
}
private splash = SplashInfo.Info()
render() {
let root = this.controller.context.tree.root;
this.renderedVersion = root.version;
let children: any[] = [];
for (let c of root.children) {
if (c.isHidden) continue;
children.push(<Entity key={c.id} node={c} tree={this} />);
}
return <div className='lm-entity-tree' ref={root => this.root = root!}>
<Entity key={root.id} node={root} tree={this} />
<div className='lm-entity-tree-children'>
{children.length ? children : this.splash }
</div>
</div>;
}
}
} | the_stack |
import { FilePlanBodyUpdate } from '../model/filePlanBodyUpdate';
import { FilePlanEntry } from '../model/filePlanEntry';
import { RecordCategoryEntry } from '../model/recordCategoryEntry';
import { RecordCategoryPaging } from '../model/recordCategoryPaging';
import { RootCategoryBodyCreate } from '../model/rootCategoryBodyCreate';
import { BaseApi } from './base.api';
import { buildCollectionParam } from '../../../alfrescoApiClient';
import { throwIfNotDefined } from '../../../assert';
/**
* Fileplans service.
* @module FilePlansApi
*/
export class FilePlansApi extends BaseApi {
/**
* Create record categories for a file plan
*
* Creates a record category as a primary child of **filePlanId**.
You can set the **autoRename** boolean field to automatically resolve name clashes. If there is a name clash, then
the API method tries to create
a unique name using an integer suffix.
This API method also supports record category creation using application/json.
You must specify at least a **name**.
You can create a category like this:
JSON
{
\"name\":\"My Record Category\"
}
You can set properties when creating a record category:
JSON
{
\"name\":\"My Record Category\",
\"properties\":
{
\"rma:vitalRecordIndicator\":\"true\",
\"rma:reviewPeriod\":\"month|1\"
}
}
Any missing aspects are applied automatically. You can set aspects explicitly, if needed, using an **aspectNames** field.
If you specify a list as input, then a paginated list rather than an entry is returned in the response body. For example:
JSON
{
\"list\": {
\"pagination\": {
\"count\": 2,
\"hasMoreItems\": false,
\"totalItems\": 2,
\"skipCount\": 0,
\"maxItems\": 100
},
\"entries\": [
{
\"entry\": {
...
}
},
{
\"entry\": {
...
}
}
]
}
}
*
* @param filePlanId The identifier of a file plan. You can also use the -filePlan- alias.
* @param nodeBodyCreate The node information to create.
* @param opts Optional parameters
* @param opts.autoRename If true, then a name clash will cause an attempt to auto rename by finding a unique name using an integer suffix.
* @param opts.include Returns additional information about the record category. Any optional field from the response model can be requested. For example:
* allowableOperations
* hasRetentionSchedule
* path
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<RecordCategoryEntry>
*/
createFilePlanCategories(filePlanId: string, nodeBodyCreate: RootCategoryBodyCreate, opts?: any): Promise<RecordCategoryEntry> {
throwIfNotDefined(filePlanId, 'filePlanId');
throwIfNotDefined(nodeBodyCreate, 'nodeBodyCreate');
opts = opts || {};
let postBody = nodeBodyCreate;
let pathParams = {
'filePlanId': filePlanId
};
let queryParams = {
'autoRename': opts['autoRename'],
'include': buildCollectionParam(opts['include'], 'csv'),
'fields': buildCollectionParam(opts['fields'], 'csv')
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json', 'multipart/form-data'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/file-plans/{filePlanId}/categories', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, RecordCategoryEntry);
}
/**
* Get a file plan
*
* Gets information for file plan **filePlanId**
Mandatory fields and the file plan's aspects and properties are returned by default.
You can use the **include** parameter (include=allowableOperations) to return additional information.
*
* @param filePlanId The identifier of a file plan. You can also use the -filePlan- alias.
* @param opts Optional parameters
* @param opts.include Returns additional information about the file plan. Any optional field from the response model can be requested. For example:
* allowableOperations
* path
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<FilePlanEntry>
*/
getFilePlan(filePlanId: string, opts?: any): Promise<FilePlanEntry> {
throwIfNotDefined(filePlanId, 'filePlanId');
opts = opts || {};
let postBody = null;
let pathParams = {
'filePlanId': filePlanId
};
let queryParams = {
'include': buildCollectionParam(opts['include'], 'csv'),
'fields': buildCollectionParam(opts['fields'], 'csv')
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/file-plans/{filePlanId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, FilePlanEntry);
}
/**
* List file plans's children
*
* Returns a list of record categories.
Minimal information for each child is returned by default.
You can use the **include** parameter (include=allowableOperations) to return additional information.
*
* @param filePlanId The identifier of a file plan. You can also use the -filePlan- alias.
* @param opts Optional parameters
* @param opts.skipCount The number of entities that exist in the collection before those included in this list.
* @param opts.maxItems The maximum number of items to return in the list.
* @param opts.include Returns additional information about the record category. Any optional field from the response model can be requested. For example:
* allowableOperations
* aspectNames
* hasRetentionSchedule
* path
* properties
* @param opts.includeSource Also include **source** (in addition to **entries**) with folder information on the parent node – the specified parent **filePlanId**
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<RecordCategoryPaging>
*/
getFilePlanCategories(filePlanId: string, opts?: any): Promise<RecordCategoryPaging> {
throwIfNotDefined(filePlanId, 'filePlanId');
opts = opts || {};
let postBody = null;
let pathParams = {
'filePlanId': filePlanId
};
let queryParams = {
'skipCount': opts['skipCount'],
'maxItems': opts['maxItems'],
'include': buildCollectionParam(opts['include'], 'csv'),
'includeSource': opts['includeSource'],
'fields': buildCollectionParam(opts['fields'], 'csv')
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/file-plans/{filePlanId}/categories', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, RecordCategoryPaging);
}
/**
* Update a file plan
*
* Updates file plan **filePlanId**.
You can only set or update description and title properties:
JSON
{
\"properties\":
{
\"cm:description\": \"New Description\",
\"cm:title\":\"New Title\"
}
}
**Note:** Currently there is no optimistic locking for updates, so they are applied in \"last one wins\" order.
*
* @param filePlanId The identifier of a file plan. You can also use the -filePlan- alias.
* @param filePlanBodyUpdate The file plan information to update.
* @param opts Optional parameters
* @param opts.include Returns additional information about the file plan. Any optional field from the response model can be requested. For example:
* allowableOperations
* path
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<FilePlanEntry>
*/
updateFilePlan(filePlanId: string, filePlanBodyUpdate: FilePlanBodyUpdate, opts?: any): Promise<FilePlanEntry> {
throwIfNotDefined(filePlanId, 'filePlanId');
throwIfNotDefined(filePlanBodyUpdate, 'filePlanBodyUpdate');
opts = opts || {};
let postBody = filePlanBodyUpdate;
let pathParams = {
'filePlanId': filePlanId
};
let queryParams = {
'include': buildCollectionParam(opts['include'], 'csv'),
'fields': buildCollectionParam(opts['fields'], 'csv')
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/file-plans/{filePlanId}', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, FilePlanEntry);
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs, enums } from "../types";
import * as utilities from "../utilities";
/**
* Provides an Amazon Lex Bot resource. For more information see
* [Amazon Lex: How It Works](https://docs.aws.amazon.com/lex/latest/dg/how-it-works.html)
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const orderFlowersBot = new aws.lex.Bot("order_flowers_bot", {
* abortStatement: {
* messages: [{
* content: "Sorry, I am not able to assist at this time",
* contentType: "PlainText",
* }],
* },
* childDirected: false,
* clarificationPrompt: {
* maxAttempts: 2,
* messages: [{
* content: "I didn't understand you, what would you like to do?",
* contentType: "PlainText",
* }],
* },
* createVersion: false,
* description: "Bot to order flowers on the behalf of a user",
* idleSessionTtlInSeconds: 600,
* intents: [{
* intentName: "OrderFlowers",
* intentVersion: "1",
* }],
* locale: "en-US",
* name: "OrderFlowers",
* processBehavior: "BUILD",
* voiceId: "Salli",
* });
* ```
*
* ## Import
*
* Bots can be imported using their name.
*
* ```sh
* $ pulumi import aws:lex/bot:Bot order_flowers_bot OrderFlowers
* ```
*/
export class Bot extends pulumi.CustomResource {
/**
* Get an existing Bot 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?: BotState, opts?: pulumi.CustomResourceOptions): Bot {
return new Bot(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:lex/bot:Bot';
/**
* Returns true if the given object is an instance of Bot. 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 Bot {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Bot.__pulumiType;
}
/**
* The message that Amazon Lex uses to abort a conversation. Attributes are documented under statement.
*/
public readonly abortStatement!: pulumi.Output<outputs.lex.BotAbortStatement>;
public /*out*/ readonly arn!: pulumi.Output<string>;
/**
* Checksum identifying the version of the bot that was created. The checksum is not
* included as an argument because the resource will add it automatically when updating the bot.
*/
public /*out*/ readonly checksum!: pulumi.Output<string>;
/**
* By specifying true, you confirm that your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. For more information see the [Amazon Lex FAQ](https://aws.amazon.com/lex/faqs#data-security) and the [Amazon Lex PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-childDirected).
*/
public readonly childDirected!: pulumi.Output<boolean>;
/**
* The message that Amazon Lex uses when it doesn't understand the user's request. Attributes are documented under prompt.
*/
public readonly clarificationPrompt!: pulumi.Output<outputs.lex.BotClarificationPrompt | undefined>;
/**
* Determines if a new bot version is created when the initial resource is created and on each update. Defaults to `false`.
*/
public readonly createVersion!: pulumi.Output<boolean | undefined>;
/**
* The date when the bot version was created.
*/
public /*out*/ readonly createdDate!: pulumi.Output<string>;
/**
* A description of the bot. Must be less than or equal to 200 characters in length.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* When set to true user utterances are sent to Amazon Comprehend for sentiment analysis. If you don't specify detectSentiment, the default is `false`.
*/
public readonly detectSentiment!: pulumi.Output<boolean | undefined>;
/**
* Set to `true` to enable access to natural language understanding improvements. When you set the `enableModelImprovements` parameter to true you can use the `nluIntentConfidenceThreshold` parameter to configure confidence scores. For more information, see [Confidence Scores](https://docs.aws.amazon.com/lex/latest/dg/confidence-scores.html). You can only set the `enableModelImprovements` parameter in certain Regions. If you set the parameter to true, your bot has access to accuracy improvements. For more information see the [Amazon Lex Bot PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-enableModelImprovements).
*/
public readonly enableModelImprovements!: pulumi.Output<boolean | undefined>;
/**
* If status is FAILED, Amazon Lex provides the reason that it failed to build the bot.
*/
public /*out*/ readonly failureReason!: pulumi.Output<string>;
/**
* The maximum time in seconds that Amazon Lex retains the data gathered in a conversation. Default is `300`. Must be a number between 60 and 86400 (inclusive).
*/
public readonly idleSessionTtlInSeconds!: pulumi.Output<number | undefined>;
/**
* A set of Intent objects. Each intent represents a command that a user can express. Attributes are documented under intent. Can have up to 100 Intent objects.
*/
public readonly intents!: pulumi.Output<outputs.lex.BotIntent[]>;
/**
* The date when the $LATEST version of this bot was updated.
*/
public /*out*/ readonly lastUpdatedDate!: pulumi.Output<string>;
/**
* Specifies the target locale for the bot. Any intent used in the bot must be compatible with the locale of the bot. For available locales, see [Amazon Lex Bot PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-locale). Default is `en-US`.
*/
public readonly locale!: pulumi.Output<string | undefined>;
/**
* The name of the bot that you want to create, case sensitive. Must be between 2 and 50 characters in length.
*/
public readonly name!: pulumi.Output<string>;
/**
* Determines the threshold where Amazon Lex will insert the AMAZON.FallbackIntent, AMAZON.KendraSearchIntent, or both when returning alternative intents in a PostContent or PostText response. AMAZON.FallbackIntent and AMAZON.KendraSearchIntent are only inserted if they are configured for the bot. For more information see [Amazon Lex Bot PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-nluIntentConfidenceThreshold) This value requires `enableModelImprovements` to be set to `true` and the default is `0`. Must be a float between 0 and 1.
*/
public readonly nluIntentConfidenceThreshold!: pulumi.Output<number | undefined>;
/**
* If you set the `processBehavior` element to `BUILD`, Amazon Lex builds the bot so that it can be run. If you set the element to `SAVE` Amazon Lex saves the bot, but doesn't build it. Default is `SAVE`.
*/
public readonly processBehavior!: pulumi.Output<string | undefined>;
/**
* When you send a request to create or update a bot, Amazon Lex sets the status response
* element to BUILDING. After Amazon Lex builds the bot, it sets status to READY. If Amazon Lex can't
* build the bot, it sets status to FAILED. Amazon Lex returns the reason for the failure in the
* failureReason response element.
*/
public /*out*/ readonly status!: pulumi.Output<string>;
/**
* The version of the bot.
*/
public /*out*/ readonly version!: pulumi.Output<string>;
/**
* The Amazon Polly voice ID that you want Amazon Lex to use for voice interactions with the user. The locale configured for the voice must match the locale of the bot. For more information, see [Available Voices](http://docs.aws.amazon.com/polly/latest/dg/voicelist.html) in the Amazon Polly Developer Guide.
*/
public readonly voiceId!: pulumi.Output<string>;
/**
* Create a Bot 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: BotArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: BotArgs | BotState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as BotState | undefined;
inputs["abortStatement"] = state ? state.abortStatement : undefined;
inputs["arn"] = state ? state.arn : undefined;
inputs["checksum"] = state ? state.checksum : undefined;
inputs["childDirected"] = state ? state.childDirected : undefined;
inputs["clarificationPrompt"] = state ? state.clarificationPrompt : undefined;
inputs["createVersion"] = state ? state.createVersion : undefined;
inputs["createdDate"] = state ? state.createdDate : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["detectSentiment"] = state ? state.detectSentiment : undefined;
inputs["enableModelImprovements"] = state ? state.enableModelImprovements : undefined;
inputs["failureReason"] = state ? state.failureReason : undefined;
inputs["idleSessionTtlInSeconds"] = state ? state.idleSessionTtlInSeconds : undefined;
inputs["intents"] = state ? state.intents : undefined;
inputs["lastUpdatedDate"] = state ? state.lastUpdatedDate : undefined;
inputs["locale"] = state ? state.locale : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["nluIntentConfidenceThreshold"] = state ? state.nluIntentConfidenceThreshold : undefined;
inputs["processBehavior"] = state ? state.processBehavior : undefined;
inputs["status"] = state ? state.status : undefined;
inputs["version"] = state ? state.version : undefined;
inputs["voiceId"] = state ? state.voiceId : undefined;
} else {
const args = argsOrState as BotArgs | undefined;
if ((!args || args.abortStatement === undefined) && !opts.urn) {
throw new Error("Missing required property 'abortStatement'");
}
if ((!args || args.childDirected === undefined) && !opts.urn) {
throw new Error("Missing required property 'childDirected'");
}
if ((!args || args.intents === undefined) && !opts.urn) {
throw new Error("Missing required property 'intents'");
}
inputs["abortStatement"] = args ? args.abortStatement : undefined;
inputs["childDirected"] = args ? args.childDirected : undefined;
inputs["clarificationPrompt"] = args ? args.clarificationPrompt : undefined;
inputs["createVersion"] = args ? args.createVersion : undefined;
inputs["description"] = args ? args.description : undefined;
inputs["detectSentiment"] = args ? args.detectSentiment : undefined;
inputs["enableModelImprovements"] = args ? args.enableModelImprovements : undefined;
inputs["idleSessionTtlInSeconds"] = args ? args.idleSessionTtlInSeconds : undefined;
inputs["intents"] = args ? args.intents : undefined;
inputs["locale"] = args ? args.locale : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["nluIntentConfidenceThreshold"] = args ? args.nluIntentConfidenceThreshold : undefined;
inputs["processBehavior"] = args ? args.processBehavior : undefined;
inputs["voiceId"] = args ? args.voiceId : undefined;
inputs["arn"] = undefined /*out*/;
inputs["checksum"] = undefined /*out*/;
inputs["createdDate"] = undefined /*out*/;
inputs["failureReason"] = undefined /*out*/;
inputs["lastUpdatedDate"] = undefined /*out*/;
inputs["status"] = undefined /*out*/;
inputs["version"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Bot.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Bot resources.
*/
export interface BotState {
/**
* The message that Amazon Lex uses to abort a conversation. Attributes are documented under statement.
*/
abortStatement?: pulumi.Input<inputs.lex.BotAbortStatement>;
arn?: pulumi.Input<string>;
/**
* Checksum identifying the version of the bot that was created. The checksum is not
* included as an argument because the resource will add it automatically when updating the bot.
*/
checksum?: pulumi.Input<string>;
/**
* By specifying true, you confirm that your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. For more information see the [Amazon Lex FAQ](https://aws.amazon.com/lex/faqs#data-security) and the [Amazon Lex PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-childDirected).
*/
childDirected?: pulumi.Input<boolean>;
/**
* The message that Amazon Lex uses when it doesn't understand the user's request. Attributes are documented under prompt.
*/
clarificationPrompt?: pulumi.Input<inputs.lex.BotClarificationPrompt>;
/**
* Determines if a new bot version is created when the initial resource is created and on each update. Defaults to `false`.
*/
createVersion?: pulumi.Input<boolean>;
/**
* The date when the bot version was created.
*/
createdDate?: pulumi.Input<string>;
/**
* A description of the bot. Must be less than or equal to 200 characters in length.
*/
description?: pulumi.Input<string>;
/**
* When set to true user utterances are sent to Amazon Comprehend for sentiment analysis. If you don't specify detectSentiment, the default is `false`.
*/
detectSentiment?: pulumi.Input<boolean>;
/**
* Set to `true` to enable access to natural language understanding improvements. When you set the `enableModelImprovements` parameter to true you can use the `nluIntentConfidenceThreshold` parameter to configure confidence scores. For more information, see [Confidence Scores](https://docs.aws.amazon.com/lex/latest/dg/confidence-scores.html). You can only set the `enableModelImprovements` parameter in certain Regions. If you set the parameter to true, your bot has access to accuracy improvements. For more information see the [Amazon Lex Bot PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-enableModelImprovements).
*/
enableModelImprovements?: pulumi.Input<boolean>;
/**
* If status is FAILED, Amazon Lex provides the reason that it failed to build the bot.
*/
failureReason?: pulumi.Input<string>;
/**
* The maximum time in seconds that Amazon Lex retains the data gathered in a conversation. Default is `300`. Must be a number between 60 and 86400 (inclusive).
*/
idleSessionTtlInSeconds?: pulumi.Input<number>;
/**
* A set of Intent objects. Each intent represents a command that a user can express. Attributes are documented under intent. Can have up to 100 Intent objects.
*/
intents?: pulumi.Input<pulumi.Input<inputs.lex.BotIntent>[]>;
/**
* The date when the $LATEST version of this bot was updated.
*/
lastUpdatedDate?: pulumi.Input<string>;
/**
* Specifies the target locale for the bot. Any intent used in the bot must be compatible with the locale of the bot. For available locales, see [Amazon Lex Bot PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-locale). Default is `en-US`.
*/
locale?: pulumi.Input<string>;
/**
* The name of the bot that you want to create, case sensitive. Must be between 2 and 50 characters in length.
*/
name?: pulumi.Input<string>;
/**
* Determines the threshold where Amazon Lex will insert the AMAZON.FallbackIntent, AMAZON.KendraSearchIntent, or both when returning alternative intents in a PostContent or PostText response. AMAZON.FallbackIntent and AMAZON.KendraSearchIntent are only inserted if they are configured for the bot. For more information see [Amazon Lex Bot PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-nluIntentConfidenceThreshold) This value requires `enableModelImprovements` to be set to `true` and the default is `0`. Must be a float between 0 and 1.
*/
nluIntentConfidenceThreshold?: pulumi.Input<number>;
/**
* If you set the `processBehavior` element to `BUILD`, Amazon Lex builds the bot so that it can be run. If you set the element to `SAVE` Amazon Lex saves the bot, but doesn't build it. Default is `SAVE`.
*/
processBehavior?: pulumi.Input<string>;
/**
* When you send a request to create or update a bot, Amazon Lex sets the status response
* element to BUILDING. After Amazon Lex builds the bot, it sets status to READY. If Amazon Lex can't
* build the bot, it sets status to FAILED. Amazon Lex returns the reason for the failure in the
* failureReason response element.
*/
status?: pulumi.Input<string>;
/**
* The version of the bot.
*/
version?: pulumi.Input<string>;
/**
* The Amazon Polly voice ID that you want Amazon Lex to use for voice interactions with the user. The locale configured for the voice must match the locale of the bot. For more information, see [Available Voices](http://docs.aws.amazon.com/polly/latest/dg/voicelist.html) in the Amazon Polly Developer Guide.
*/
voiceId?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Bot resource.
*/
export interface BotArgs {
/**
* The message that Amazon Lex uses to abort a conversation. Attributes are documented under statement.
*/
abortStatement: pulumi.Input<inputs.lex.BotAbortStatement>;
/**
* By specifying true, you confirm that your use of Amazon Lex is related to a website, program, or other application that is directed or targeted, in whole or in part, to children under age 13 and subject to COPPA. For more information see the [Amazon Lex FAQ](https://aws.amazon.com/lex/faqs#data-security) and the [Amazon Lex PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-childDirected).
*/
childDirected: pulumi.Input<boolean>;
/**
* The message that Amazon Lex uses when it doesn't understand the user's request. Attributes are documented under prompt.
*/
clarificationPrompt?: pulumi.Input<inputs.lex.BotClarificationPrompt>;
/**
* Determines if a new bot version is created when the initial resource is created and on each update. Defaults to `false`.
*/
createVersion?: pulumi.Input<boolean>;
/**
* A description of the bot. Must be less than or equal to 200 characters in length.
*/
description?: pulumi.Input<string>;
/**
* When set to true user utterances are sent to Amazon Comprehend for sentiment analysis. If you don't specify detectSentiment, the default is `false`.
*/
detectSentiment?: pulumi.Input<boolean>;
/**
* Set to `true` to enable access to natural language understanding improvements. When you set the `enableModelImprovements` parameter to true you can use the `nluIntentConfidenceThreshold` parameter to configure confidence scores. For more information, see [Confidence Scores](https://docs.aws.amazon.com/lex/latest/dg/confidence-scores.html). You can only set the `enableModelImprovements` parameter in certain Regions. If you set the parameter to true, your bot has access to accuracy improvements. For more information see the [Amazon Lex Bot PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-enableModelImprovements).
*/
enableModelImprovements?: pulumi.Input<boolean>;
/**
* The maximum time in seconds that Amazon Lex retains the data gathered in a conversation. Default is `300`. Must be a number between 60 and 86400 (inclusive).
*/
idleSessionTtlInSeconds?: pulumi.Input<number>;
/**
* A set of Intent objects. Each intent represents a command that a user can express. Attributes are documented under intent. Can have up to 100 Intent objects.
*/
intents: pulumi.Input<pulumi.Input<inputs.lex.BotIntent>[]>;
/**
* Specifies the target locale for the bot. Any intent used in the bot must be compatible with the locale of the bot. For available locales, see [Amazon Lex Bot PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-locale). Default is `en-US`.
*/
locale?: pulumi.Input<string>;
/**
* The name of the bot that you want to create, case sensitive. Must be between 2 and 50 characters in length.
*/
name?: pulumi.Input<string>;
/**
* Determines the threshold where Amazon Lex will insert the AMAZON.FallbackIntent, AMAZON.KendraSearchIntent, or both when returning alternative intents in a PostContent or PostText response. AMAZON.FallbackIntent and AMAZON.KendraSearchIntent are only inserted if they are configured for the bot. For more information see [Amazon Lex Bot PutBot API Docs](https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html#lex-PutBot-request-nluIntentConfidenceThreshold) This value requires `enableModelImprovements` to be set to `true` and the default is `0`. Must be a float between 0 and 1.
*/
nluIntentConfidenceThreshold?: pulumi.Input<number>;
/**
* If you set the `processBehavior` element to `BUILD`, Amazon Lex builds the bot so that it can be run. If you set the element to `SAVE` Amazon Lex saves the bot, but doesn't build it. Default is `SAVE`.
*/
processBehavior?: pulumi.Input<string>;
/**
* The Amazon Polly voice ID that you want Amazon Lex to use for voice interactions with the user. The locale configured for the voice must match the locale of the bot. For more information, see [Available Voices](http://docs.aws.amazon.com/polly/latest/dg/voicelist.html) in the Amazon Polly Developer Guide.
*/
voiceId?: pulumi.Input<string>;
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Creates and manages service account keys, which allow the use of a service account outside of Google Cloud.
*
* * [API documentation](https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts.keys)
* * How-to Guides
* * [Official Documentation](https://cloud.google.com/iam/docs/creating-managing-service-account-keys)
*
* ## Example Usage
* ### Creating A New Key
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const myaccount = new gcp.serviceaccount.Account("myaccount", {
* accountId: "myaccount",
* displayName: "My Service Account",
* });
* const mykey = new gcp.serviceaccount.Key("mykey", {
* serviceAccountId: myaccount.name,
* publicKeyType: "TYPE_X509_PEM_FILE",
* });
* ```
*
* ## Import
*
* This resource does not support import.
*/
export class Key extends pulumi.CustomResource {
/**
* Get an existing Key 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?: KeyState, opts?: pulumi.CustomResourceOptions): Key {
return new Key(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:serviceAccount/key:Key';
/**
* Returns true if the given object is an instance of Key. 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 Key {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Key.__pulumiType;
}
/**
* Arbitrary map of values that, when changed, will trigger a new key to be generated.
*/
public readonly keepers!: pulumi.Output<{[key: string]: any} | undefined>;
/**
* The algorithm used to generate the key. KEY_ALG_RSA_2048 is the default algorithm.
* Valid values are listed at
* [ServiceAccountPrivateKeyType](https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts.keys#ServiceAccountKeyAlgorithm)
* (only used on create)
*/
public readonly keyAlgorithm!: pulumi.Output<string | undefined>;
/**
* The name used for this key pair
*/
public /*out*/ readonly name!: pulumi.Output<string>;
/**
* The private key in JSON format, base64 encoded. This is what you normally get as a file when creating
* service account keys through the CLI or web console. This is only populated when creating a new key.
*/
public /*out*/ readonly privateKey!: pulumi.Output<string>;
/**
* The output format of the private key. TYPE_GOOGLE_CREDENTIALS_FILE is the default output format.
*/
public readonly privateKeyType!: pulumi.Output<string | undefined>;
/**
* The public key, base64 encoded
*/
public /*out*/ readonly publicKey!: pulumi.Output<string>;
/**
* Public key data to create a service account key for given service account. The expected format for this field is a base64 encoded X509_PEM and it conflicts with `publicKeyType` and `privateKeyType`.
*/
public readonly publicKeyData!: pulumi.Output<string | undefined>;
/**
* The output format of the public key requested. TYPE_X509_PEM_FILE is the default output format.
*/
public readonly publicKeyType!: pulumi.Output<string | undefined>;
/**
* The Service account id of the Key. This can be a string in the format
* `{ACCOUNT}` or `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}`, where `{ACCOUNT}` is the email address or
* unique id of the service account. If the `{ACCOUNT}` syntax is used, the project will be inferred from the account.
*/
public readonly serviceAccountId!: pulumi.Output<string>;
/**
* The key can be used after this timestamp. A timestamp in RFC3339 UTC "Zulu" format, accurate to nanoseconds. Example: "2014-10-02T15:01:23.045123456Z".
*/
public /*out*/ readonly validAfter!: pulumi.Output<string>;
/**
* The key can be used before this timestamp.
* A timestamp in RFC3339 UTC "Zulu" format, accurate to nanoseconds. Example: "2014-10-02T15:01:23.045123456Z".
*/
public /*out*/ readonly validBefore!: pulumi.Output<string>;
/**
* Create a Key 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: KeyArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: KeyArgs | KeyState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as KeyState | undefined;
inputs["keepers"] = state ? state.keepers : undefined;
inputs["keyAlgorithm"] = state ? state.keyAlgorithm : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["privateKey"] = state ? state.privateKey : undefined;
inputs["privateKeyType"] = state ? state.privateKeyType : undefined;
inputs["publicKey"] = state ? state.publicKey : undefined;
inputs["publicKeyData"] = state ? state.publicKeyData : undefined;
inputs["publicKeyType"] = state ? state.publicKeyType : undefined;
inputs["serviceAccountId"] = state ? state.serviceAccountId : undefined;
inputs["validAfter"] = state ? state.validAfter : undefined;
inputs["validBefore"] = state ? state.validBefore : undefined;
} else {
const args = argsOrState as KeyArgs | undefined;
if ((!args || args.serviceAccountId === undefined) && !opts.urn) {
throw new Error("Missing required property 'serviceAccountId'");
}
inputs["keepers"] = args ? args.keepers : undefined;
inputs["keyAlgorithm"] = args ? args.keyAlgorithm : undefined;
inputs["privateKeyType"] = args ? args.privateKeyType : undefined;
inputs["publicKeyData"] = args ? args.publicKeyData : undefined;
inputs["publicKeyType"] = args ? args.publicKeyType : undefined;
inputs["serviceAccountId"] = args ? args.serviceAccountId : undefined;
inputs["name"] = undefined /*out*/;
inputs["privateKey"] = undefined /*out*/;
inputs["publicKey"] = undefined /*out*/;
inputs["validAfter"] = undefined /*out*/;
inputs["validBefore"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Key.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Key resources.
*/
export interface KeyState {
/**
* Arbitrary map of values that, when changed, will trigger a new key to be generated.
*/
keepers?: pulumi.Input<{[key: string]: any}>;
/**
* The algorithm used to generate the key. KEY_ALG_RSA_2048 is the default algorithm.
* Valid values are listed at
* [ServiceAccountPrivateKeyType](https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts.keys#ServiceAccountKeyAlgorithm)
* (only used on create)
*/
keyAlgorithm?: pulumi.Input<string>;
/**
* The name used for this key pair
*/
name?: pulumi.Input<string>;
/**
* The private key in JSON format, base64 encoded. This is what you normally get as a file when creating
* service account keys through the CLI or web console. This is only populated when creating a new key.
*/
privateKey?: pulumi.Input<string>;
/**
* The output format of the private key. TYPE_GOOGLE_CREDENTIALS_FILE is the default output format.
*/
privateKeyType?: pulumi.Input<string>;
/**
* The public key, base64 encoded
*/
publicKey?: pulumi.Input<string>;
/**
* Public key data to create a service account key for given service account. The expected format for this field is a base64 encoded X509_PEM and it conflicts with `publicKeyType` and `privateKeyType`.
*/
publicKeyData?: pulumi.Input<string>;
/**
* The output format of the public key requested. TYPE_X509_PEM_FILE is the default output format.
*/
publicKeyType?: pulumi.Input<string>;
/**
* The Service account id of the Key. This can be a string in the format
* `{ACCOUNT}` or `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}`, where `{ACCOUNT}` is the email address or
* unique id of the service account. If the `{ACCOUNT}` syntax is used, the project will be inferred from the account.
*/
serviceAccountId?: pulumi.Input<string>;
/**
* The key can be used after this timestamp. A timestamp in RFC3339 UTC "Zulu" format, accurate to nanoseconds. Example: "2014-10-02T15:01:23.045123456Z".
*/
validAfter?: pulumi.Input<string>;
/**
* The key can be used before this timestamp.
* A timestamp in RFC3339 UTC "Zulu" format, accurate to nanoseconds. Example: "2014-10-02T15:01:23.045123456Z".
*/
validBefore?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Key resource.
*/
export interface KeyArgs {
/**
* Arbitrary map of values that, when changed, will trigger a new key to be generated.
*/
keepers?: pulumi.Input<{[key: string]: any}>;
/**
* The algorithm used to generate the key. KEY_ALG_RSA_2048 is the default algorithm.
* Valid values are listed at
* [ServiceAccountPrivateKeyType](https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts.keys#ServiceAccountKeyAlgorithm)
* (only used on create)
*/
keyAlgorithm?: pulumi.Input<string>;
/**
* The output format of the private key. TYPE_GOOGLE_CREDENTIALS_FILE is the default output format.
*/
privateKeyType?: pulumi.Input<string>;
/**
* Public key data to create a service account key for given service account. The expected format for this field is a base64 encoded X509_PEM and it conflicts with `publicKeyType` and `privateKeyType`.
*/
publicKeyData?: pulumi.Input<string>;
/**
* The output format of the public key requested. TYPE_X509_PEM_FILE is the default output format.
*/
publicKeyType?: pulumi.Input<string>;
/**
* The Service account id of the Key. This can be a string in the format
* `{ACCOUNT}` or `projects/{PROJECT_ID}/serviceAccounts/{ACCOUNT}`, where `{ACCOUNT}` is the email address or
* unique id of the service account. If the `{ACCOUNT}` syntax is used, the project will be inferred from the account.
*/
serviceAccountId: pulumi.Input<string>;
} | the_stack |
import * as Common from '../../core/common/common.js';
import * as i18n from '../../core/i18n/i18n.js';
import type * as SDK from '../../core/sdk/sdk.js';
import * as DataGrid from '../../ui/legacy/components/data_grid/data_grid.js';
import * as Components from '../../ui/legacy/components/utils/utils.js';
import * as UI from '../../ui/legacy/legacy.js';
import type {NetworkNode} from './NetworkDataGridNode.js';
import {NetworkRequestNode} from './NetworkDataGridNode.js';
import type {NetworkLogView} from './NetworkLogView.js';
import {NetworkManageCustomHeadersView} from './NetworkManageCustomHeadersView.js';
import type {NetworkTimeCalculator, NetworkTransferDurationCalculator, NetworkTransferTimeCalculator} from './NetworkTimeCalculator.js';
import {NetworkWaterfallColumn} from './NetworkWaterfallColumn.js';
import {RequestInitiatorView} from './RequestInitiatorView.js';
const UIStrings = {
/**
*@description Data grid name for Network Log data grids
*/
networkLog: 'Network Log',
/**
*@description Inner element text content in Network Log View Columns of the Network panel
*/
waterfall: 'Waterfall',
/**
*@description A context menu item in the Network Log View Columns of the Network panel
*/
responseHeaders: 'Response Headers',
/**
*@description Text in Network Log View Columns of the Network panel
*/
manageHeaderColumns: 'Manage Header Columns…',
/**
*@description Text for the start time of an activity
*/
startTime: 'Start Time',
/**
*@description Text in Network Log View Columns of the Network panel
*/
responseTime: 'Response Time',
/**
*@description Text in Network Log View Columns of the Network panel
*/
endTime: 'End Time',
/**
*@description Text in Network Log View Columns of the Network panel
*/
totalDuration: 'Total Duration',
/**
*@description Text for the latency of a task
*/
latency: 'Latency',
/**
*@description Text for the name of something
*/
name: 'Name',
/**
*@description Text that refers to a file path
*/
path: 'Path',
/**
*@description Text in Timeline UIUtils of the Performance panel
*/
url: 'Url',
/**
*@description Text for one or a group of functions
*/
method: 'Method',
/**
*@description Text for the status of something
*/
status: 'Status',
/**
*@description Generic label for any text
*/
text: 'Text',
/**
*@description Text for security or network protocol
*/
protocol: 'Protocol',
/**
*@description Text in Network Log View Columns of the Network panel
*/
scheme: 'Scheme',
/**
*@description Text for the domain of a website
*/
domain: 'Domain',
/**
*@description Text in Network Log View Columns of the Network panel
*/
remoteAddress: 'Remote Address',
/**
*@description Text that refers to some types
*/
type: 'Type',
/**
*@description Text for the initiator of something
*/
initiator: 'Initiator',
/**
*@description Column header in the Network log view of the Network panel
*/
initiatorAddressSpace: 'Initiator Address Space',
/**
*@description Text for web cookies
*/
cookies: 'Cookies',
/**
*@description Text in Network Log View Columns of the Network panel
*/
setCookies: 'Set Cookies',
/**
*@description Text for the size of something
*/
size: 'Size',
/**
*@description Text in Network Log View Columns of the Network panel
*/
content: 'Content',
/**
*@description Text that refers to the time
*/
time: 'Time',
/**
*@description Text to show the priority of an item
*/
priority: 'Priority',
/**
*@description Text in Network Log View Columns of the Network panel
*/
connectionId: 'Connection ID',
/**
*@description Text in Network Log View Columns of the Network panel
*/
remoteAddressSpace: 'Remote Address Space',
};
const str_ = i18n.i18n.registerUIStrings('panels/network/NetworkLogViewColumns.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
const i18nLazyString = i18n.i18n.getLazilyComputedLocalizedString.bind(undefined, str_);
export class NetworkLogViewColumns {
private networkLogView: NetworkLogView;
private readonly persistantSettings: Common.Settings.Setting<{
[x: string]: {
visible: boolean,
title: string,
},
}>;
private readonly networkLogLargeRowsSetting: Common.Settings.Setting<boolean>;
private readonly eventDividers: Map<string, number[]>;
private eventDividersShown: boolean;
private gridMode: boolean;
private columns: Descriptor[];
private waterfallRequestsAreStale: boolean;
private waterfallScrollerWidthIsStale: boolean;
private readonly popupLinkifier: Components.Linkifier.Linkifier;
private calculatorsMap: Map<string, NetworkTimeCalculator>;
private lastWheelTime: number;
private dataGridInternal!: DataGrid.SortableDataGrid.SortableDataGrid<NetworkNode>;
private splitWidget!: UI.SplitWidget.SplitWidget;
private waterfallColumn!: NetworkWaterfallColumn;
private activeScroller!: Element;
private dataGridScroller!: HTMLElement;
private waterfallScroller!: HTMLElement;
private waterfallScrollerContent!: HTMLDivElement;
private waterfallHeaderElement!: HTMLElement;
private waterfallColumnSortIcon!: UI.Icon.Icon;
private activeWaterfallSortId!: string;
private popoverHelper?: UI.PopoverHelper.PopoverHelper;
private hasScrollerTouchStarted?: boolean;
private scrollerTouchStartPos?: number;
constructor(
networkLogView: NetworkLogView, timeCalculator: NetworkTransferTimeCalculator,
durationCalculator: NetworkTransferDurationCalculator,
networkLogLargeRowsSetting: Common.Settings.Setting<boolean>) {
this.networkLogView = networkLogView;
this.persistantSettings = Common.Settings.Settings.instance().createSetting('networkLogColumns', {});
this.networkLogLargeRowsSetting = networkLogLargeRowsSetting;
this.networkLogLargeRowsSetting.addChangeListener(this.updateRowsSize, this);
this.eventDividers = new Map();
this.eventDividersShown = false;
this.gridMode = true;
this.columns = [];
this.waterfallRequestsAreStale = false;
this.waterfallScrollerWidthIsStale = true;
this.popupLinkifier = new Components.Linkifier.Linkifier();
this.calculatorsMap = new Map();
this.calculatorsMap.set(_calculatorTypes.Time, timeCalculator);
this.calculatorsMap.set(_calculatorTypes.Duration, durationCalculator);
this.lastWheelTime = 0;
this.setupDataGrid();
this.setupWaterfall();
}
private static convertToDataGridDescriptor(columnConfig: Descriptor): DataGrid.DataGrid.ColumnDescriptor {
const title = columnConfig.title instanceof Function ? columnConfig.title() : columnConfig.title;
return /** @type {!DataGrid.DataGrid.ColumnDescriptor} */ {
id: columnConfig.id,
title,
sortable: columnConfig.sortable,
align: columnConfig.align,
nonSelectable: columnConfig.nonSelectable,
weight: columnConfig.weight,
allowInSortByEvenWhenHidden: columnConfig.allowInSortByEvenWhenHidden,
} as DataGrid.DataGrid.ColumnDescriptor;
}
wasShown(): void {
this.updateRowsSize();
}
willHide(): void {
if (this.popoverHelper) {
this.popoverHelper.hidePopover();
}
}
reset(): void {
if (this.popoverHelper) {
this.popoverHelper.hidePopover();
}
this.eventDividers.clear();
}
private setupDataGrid(): void {
const defaultColumns = _defaultColumns;
const defaultColumnConfig = _defaultColumnConfig;
this.columns = ([] as Descriptor[]);
for (const currentConfigColumn of defaultColumns) {
const descriptor = Object.assign({}, defaultColumnConfig, currentConfigColumn);
const columnConfig = (descriptor as Descriptor);
columnConfig.id = columnConfig.id;
if (columnConfig.subtitle) {
const title = columnConfig.title instanceof Function ? columnConfig.title() : columnConfig.title;
const subtitle = columnConfig.subtitle instanceof Function ? columnConfig.subtitle() : columnConfig.subtitle;
columnConfig.titleDOMFragment = this.makeHeaderFragment(title, subtitle);
}
this.columns.push(columnConfig);
}
this.loadCustomColumnsAndSettings();
this.popoverHelper =
new UI.PopoverHelper.PopoverHelper(this.networkLogView.element, this.getPopoverRequest.bind(this));
this.popoverHelper.setHasPadding(true);
this.popoverHelper.setTimeout(300, 300);
this.dataGridInternal = new DataGrid.SortableDataGrid.SortableDataGrid<NetworkNode>(({
displayName: (i18nString(UIStrings.networkLog) as string),
columns: this.columns.map(NetworkLogViewColumns.convertToDataGridDescriptor),
editCallback: undefined,
deleteCallback: undefined,
refreshCallback: undefined,
}));
this.dataGridInternal.element.addEventListener('mousedown', event => {
if (!this.dataGridInternal.selectedNode && event.button) {
event.consume();
}
}, true);
this.dataGridScroller = (this.dataGridInternal.scrollContainer as HTMLDivElement);
this.updateColumns();
this.dataGridInternal.addEventListener(DataGrid.DataGrid.Events.SortingChanged, this.sortHandler, this);
this.dataGridInternal.setHeaderContextMenuCallback(this.innerHeaderContextMenu.bind(this));
this.activeWaterfallSortId = WaterfallSortIds.StartTime;
this.dataGridInternal.markColumnAsSortedBy(_initialSortColumn, DataGrid.DataGrid.Order.Ascending);
this.splitWidget = new UI.SplitWidget.SplitWidget(true, true, 'networkPanelSplitViewWaterfall', 200);
const widget = this.dataGridInternal.asWidget();
widget.setMinimumSize(150, 0);
this.splitWidget.setMainWidget(widget);
}
private setupWaterfall(): void {
this.waterfallColumn = new NetworkWaterfallColumn(this.networkLogView.calculator());
this.waterfallColumn.element.addEventListener('contextmenu', handleContextMenu.bind(this));
this.waterfallColumn.element.addEventListener('wheel', this.onMouseWheel.bind(this, false), {passive: true});
this.waterfallColumn.element.addEventListener('touchstart', this.onTouchStart.bind(this));
this.waterfallColumn.element.addEventListener('touchmove', this.onTouchMove.bind(this));
this.waterfallColumn.element.addEventListener('touchend', this.onTouchEnd.bind(this));
this.dataGridScroller.addEventListener('wheel', this.onMouseWheel.bind(this, true), true);
this.dataGridScroller.addEventListener('touchstart', this.onTouchStart.bind(this));
this.dataGridScroller.addEventListener('touchmove', this.onTouchMove.bind(this));
this.dataGridScroller.addEventListener('touchend', this.onTouchEnd.bind(this));
this.waterfallScroller =
(this.waterfallColumn.contentElement.createChild('div', 'network-waterfall-v-scroll') as HTMLDivElement);
this.waterfallScrollerContent =
(this.waterfallScroller.createChild('div', 'network-waterfall-v-scroll-content') as HTMLDivElement);
this.dataGridInternal.addEventListener(DataGrid.DataGrid.Events.PaddingChanged, () => {
this.waterfallScrollerWidthIsStale = true;
this.syncScrollers();
});
this.dataGridInternal.addEventListener(
DataGrid.ViewportDataGrid.Events.ViewportCalculated, this.redrawWaterfallColumn.bind(this));
this.createWaterfallHeader();
this.waterfallColumn.contentElement.classList.add('network-waterfall-view');
this.waterfallColumn.setMinimumSize(100, 0);
this.splitWidget.setSidebarWidget(this.waterfallColumn);
this.switchViewMode(false);
function handleContextMenu(this: NetworkLogViewColumns, ev: Event): void {
const event = (ev as MouseEvent);
const node = this.waterfallColumn.getNodeFromPoint(event.offsetX, event.offsetY);
if (!node) {
return;
}
const request = node.request();
if (!request) {
return;
}
const contextMenu = new UI.ContextMenu.ContextMenu(event);
this.networkLogView.handleContextMenuForRequest(contextMenu, request);
contextMenu.show();
}
}
private onMouseWheel(shouldConsume: boolean, ev: Event): void {
if (shouldConsume) {
ev.consume(true);
}
const event = (ev as WheelEvent);
const hasRecentWheel = Date.now() - this.lastWheelTime < 80;
this.activeScroller.scrollBy({top: event.deltaY, behavior: hasRecentWheel ? 'auto' : 'smooth'});
this.syncScrollers();
this.lastWheelTime = Date.now();
}
private onTouchStart(ev: Event): void {
const event = (ev as TouchEvent);
this.hasScrollerTouchStarted = true;
this.scrollerTouchStartPos = event.changedTouches[0].pageY;
}
private onTouchMove(ev: Event): void {
if (!this.hasScrollerTouchStarted) {
return;
}
const event = (ev as TouchEvent);
const currentPos = event.changedTouches[0].pageY;
const delta = (this.scrollerTouchStartPos as number) - currentPos;
this.activeScroller.scrollBy({top: delta, behavior: 'auto'});
this.syncScrollers();
this.scrollerTouchStartPos = currentPos;
}
private onTouchEnd(): void {
this.hasScrollerTouchStarted = false;
}
private syncScrollers(): void {
if (!this.waterfallColumn.isShowing()) {
return;
}
this.waterfallScrollerContent.style.height = this.dataGridScroller.scrollHeight + 'px';
this.updateScrollerWidthIfNeeded();
this.dataGridScroller.scrollTop = this.waterfallScroller.scrollTop;
}
private updateScrollerWidthIfNeeded(): void {
if (this.waterfallScrollerWidthIsStale) {
this.waterfallScrollerWidthIsStale = false;
this.waterfallColumn.setRightPadding(
this.waterfallScroller.offsetWidth - this.waterfallScrollerContent.offsetWidth);
}
}
private redrawWaterfallColumn(): void {
if (!this.waterfallRequestsAreStale) {
this.updateScrollerWidthIfNeeded();
this.waterfallColumn.update(
this.activeScroller.scrollTop, this.eventDividersShown ? this.eventDividers : undefined);
return;
}
this.syncScrollers();
const nodes = this.networkLogView.flatNodesList();
this.waterfallColumn.update(this.activeScroller.scrollTop, this.eventDividers, nodes);
}
private createWaterfallHeader(): void {
this.waterfallHeaderElement =
(this.waterfallColumn.contentElement.createChild('div', 'network-waterfall-header') as HTMLElement);
this.waterfallHeaderElement.addEventListener('click', waterfallHeaderClicked.bind(this));
this.waterfallHeaderElement.addEventListener(
'contextmenu', event => this.innerHeaderContextMenu(new UI.ContextMenu.ContextMenu(event)));
const innerElement = this.waterfallHeaderElement.createChild('div');
innerElement.textContent = i18nString(UIStrings.waterfall);
this.waterfallColumnSortIcon = UI.Icon.Icon.create('', 'sort-order-icon');
this.waterfallHeaderElement.createChild('div', 'sort-order-icon-container')
.appendChild(this.waterfallColumnSortIcon);
function waterfallHeaderClicked(this: NetworkLogViewColumns): void {
const sortOrders = DataGrid.DataGrid.Order;
const wasSortedByWaterfall = this.dataGridInternal.sortColumnId() === 'waterfall';
const wasSortedAscending = this.dataGridInternal.isSortOrderAscending();
const sortOrder = wasSortedByWaterfall && wasSortedAscending ? sortOrders.Descending : sortOrders.Ascending;
this.dataGridInternal.markColumnAsSortedBy('waterfall', sortOrder);
this.sortHandler();
}
}
setCalculator(x: NetworkTimeCalculator): void {
this.waterfallColumn.setCalculator(x);
}
scheduleRefresh(): void {
this.waterfallColumn.scheduleDraw();
}
private updateRowsSize(): void {
const largeRows = Boolean(this.networkLogLargeRowsSetting.get());
this.dataGridInternal.element.classList.toggle('small', !largeRows);
this.dataGridInternal.scheduleUpdate();
this.waterfallScrollerWidthIsStale = true;
this.waterfallColumn.setRowHeight(largeRows ? 41 : 21);
this.waterfallScroller.classList.toggle('small', !largeRows);
this.waterfallHeaderElement.classList.toggle('small', !largeRows);
// Request an animation frame because under certain conditions
// (see crbug.com/1019723) this.waterfallScroller.offsetTop does
// not return the value it's supposed to return as of the applied
// css classes.
window.requestAnimationFrame(() => {
this.waterfallColumn.setHeaderHeight(this.waterfallScroller.offsetTop);
this.waterfallColumn.scheduleDraw();
});
}
show(element: Element): void {
this.splitWidget.show(element);
}
setHidden(value: boolean): void {
UI.ARIAUtils.setHidden(this.splitWidget.element, value);
}
dataGrid(): DataGrid.SortableDataGrid.SortableDataGrid<NetworkNode> {
return this.dataGridInternal;
}
sortByCurrentColumn(): void {
this.sortHandler();
}
private sortHandler(): void {
const columnId = this.dataGridInternal.sortColumnId();
this.networkLogView.removeAllNodeHighlights();
this.waterfallRequestsAreStale = true;
if (columnId === 'waterfall') {
if (this.dataGridInternal.sortOrder() === DataGrid.DataGrid.Order.Ascending) {
this.waterfallColumnSortIcon.setIconType('smallicon-triangle-up');
} else {
this.waterfallColumnSortIcon.setIconType('smallicon-triangle-down');
}
const sortFunction =
(NetworkRequestNode.RequestPropertyComparator.bind(null, this.activeWaterfallSortId) as
(arg0: DataGrid.SortableDataGrid.SortableDataGridNode<NetworkNode>,
arg1: DataGrid.SortableDataGrid.SortableDataGridNode<NetworkNode>) => number);
this.dataGridInternal.sortNodes(sortFunction, !this.dataGridInternal.isSortOrderAscending());
this.dataGridSortedForTest();
return;
}
this.waterfallColumnSortIcon.setIconType('');
const columnConfig = this.columns.find(columnConfig => columnConfig.id === columnId);
if (!columnConfig || !columnConfig.sortingFunction) {
return;
}
const sortingFunction =
(columnConfig.sortingFunction as
((arg0: DataGrid.SortableDataGrid.SortableDataGridNode<NetworkNode>,
arg1: DataGrid.SortableDataGrid.SortableDataGridNode<NetworkNode>) => number) |
undefined);
if (!sortingFunction) {
return;
}
this.dataGridInternal.sortNodes(sortingFunction, !this.dataGridInternal.isSortOrderAscending());
this.dataGridSortedForTest();
}
private dataGridSortedForTest(): void {
}
private updateColumns(): void {
if (!this.dataGridInternal) {
return;
}
const visibleColumns = new Set<string>();
if (this.gridMode) {
for (const columnConfig of this.columns) {
if (columnConfig.visible) {
visibleColumns.add(columnConfig.id);
}
}
} else {
// Find the first visible column from the path group
const visibleColumn = this.columns.find(c => c.hideableGroup === 'path' && c.visible);
if (visibleColumn) {
visibleColumns.add(visibleColumn.id);
} else {
// This should not happen because inside a hideableGroup
// there should always be at least one column visible
// This is just in case.
visibleColumns.add('name');
}
}
this.dataGridInternal.setColumnsVisiblity(visibleColumns);
}
switchViewMode(gridMode: boolean): void {
if (this.gridMode === gridMode) {
return;
}
this.gridMode = gridMode;
if (gridMode) {
this.splitWidget.showBoth();
this.activeScroller = this.waterfallScroller;
this.waterfallScroller.scrollTop = this.dataGridScroller.scrollTop;
this.dataGridInternal.setScrollContainer(this.waterfallScroller);
} else {
this.networkLogView.removeAllNodeHighlights();
this.splitWidget.hideSidebar();
this.activeScroller = this.dataGridScroller;
this.dataGridInternal.setScrollContainer(this.dataGridScroller);
}
this.networkLogView.element.classList.toggle('brief-mode', !gridMode);
this.updateColumns();
this.updateRowsSize();
}
private toggleColumnVisibility(columnConfig: Descriptor): void {
this.loadCustomColumnsAndSettings();
columnConfig.visible = !columnConfig.visible;
this.saveColumnsSettings();
this.updateColumns();
}
private saveColumnsSettings(): void {
const saveableSettings: {
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[x: string]: any,
} = {};
for (const columnConfig of this.columns) {
saveableSettings[columnConfig.id] = {visible: columnConfig.visible, title: columnConfig.title};
}
this.persistantSettings.set(saveableSettings);
}
private loadCustomColumnsAndSettings(): void {
const savedSettings = this.persistantSettings.get();
const columnIds = Object.keys(savedSettings);
for (const columnId of columnIds) {
const setting = savedSettings[columnId];
let columnConfig = this.columns.find(columnConfig => columnConfig.id === columnId);
if (!columnConfig) {
columnConfig = this.addCustomHeader(setting.title, columnId) || undefined;
}
if (columnConfig && columnConfig.hideable && typeof setting.visible === 'boolean') {
columnConfig.visible = Boolean(setting.visible);
}
if (columnConfig && typeof setting.title === 'string') {
columnConfig.title = setting.title;
}
}
}
private makeHeaderFragment(title: string, subtitle: string): DocumentFragment {
const fragment = document.createDocumentFragment();
UI.UIUtils.createTextChild(fragment, title);
const subtitleDiv = fragment.createChild('div', 'network-header-subtitle');
UI.UIUtils.createTextChild(subtitleDiv, subtitle);
return fragment;
}
private innerHeaderContextMenu(contextMenu: UI.ContextMenu.SubMenu): void {
const columnConfigs = this.columns.filter(columnConfig => columnConfig.hideable);
const nonResponseHeaders = columnConfigs.filter(columnConfig => !columnConfig.isResponseHeader);
const hideableGroups = new Map<string, Descriptor[]>();
const nonResponseHeadersWithoutGroup: Descriptor[] = [];
// Sort columns into their groups
for (const columnConfig of nonResponseHeaders) {
if (!columnConfig.hideableGroup) {
nonResponseHeadersWithoutGroup.push(columnConfig);
} else {
const name = columnConfig.hideableGroup;
let hideableGroup = hideableGroups.get(name);
if (!hideableGroup) {
hideableGroup = [];
hideableGroups.set(name, hideableGroup);
}
hideableGroup.push(columnConfig);
}
}
// Add all the groups first
for (const group of hideableGroups.values()) {
const visibleColumns = group.filter(columnConfig => columnConfig.visible);
for (const columnConfig of group) {
// Make sure that at least one item in every group is enabled
const isDisabled = visibleColumns.length === 1 && visibleColumns[0] === columnConfig;
const title = columnConfig.title instanceof Function ? columnConfig.title() : columnConfig.title;
contextMenu.headerSection().appendCheckboxItem(
title, this.toggleColumnVisibility.bind(this, columnConfig), columnConfig.visible, isDisabled);
}
contextMenu.headerSection().appendSeparator();
}
// Add normal columns not belonging to any group
for (const columnConfig of nonResponseHeadersWithoutGroup) {
const title = columnConfig.title instanceof Function ? columnConfig.title() : columnConfig.title;
contextMenu.headerSection().appendCheckboxItem(
title, this.toggleColumnVisibility.bind(this, columnConfig), columnConfig.visible);
}
const responseSubMenu = contextMenu.footerSection().appendSubMenuItem(i18nString(UIStrings.responseHeaders));
const responseHeaders = columnConfigs.filter(columnConfig => columnConfig.isResponseHeader);
for (const columnConfig of responseHeaders) {
const title = columnConfig.title instanceof Function ? columnConfig.title() : columnConfig.title;
responseSubMenu.defaultSection().appendCheckboxItem(
title, this.toggleColumnVisibility.bind(this, columnConfig), columnConfig.visible);
}
responseSubMenu.footerSection().appendItem(
i18nString(UIStrings.manageHeaderColumns), this.manageCustomHeaderDialog.bind(this));
const waterfallSortIds = WaterfallSortIds;
const waterfallSubMenu = contextMenu.footerSection().appendSubMenuItem(i18nString(UIStrings.waterfall));
waterfallSubMenu.defaultSection().appendCheckboxItem(
i18nString(UIStrings.startTime), setWaterfallMode.bind(this, waterfallSortIds.StartTime),
this.activeWaterfallSortId === waterfallSortIds.StartTime);
waterfallSubMenu.defaultSection().appendCheckboxItem(
i18nString(UIStrings.responseTime), setWaterfallMode.bind(this, waterfallSortIds.ResponseTime),
this.activeWaterfallSortId === waterfallSortIds.ResponseTime);
waterfallSubMenu.defaultSection().appendCheckboxItem(
i18nString(UIStrings.endTime), setWaterfallMode.bind(this, waterfallSortIds.EndTime),
this.activeWaterfallSortId === waterfallSortIds.EndTime);
waterfallSubMenu.defaultSection().appendCheckboxItem(
i18nString(UIStrings.totalDuration), setWaterfallMode.bind(this, waterfallSortIds.Duration),
this.activeWaterfallSortId === waterfallSortIds.Duration);
waterfallSubMenu.defaultSection().appendCheckboxItem(
i18nString(UIStrings.latency), setWaterfallMode.bind(this, waterfallSortIds.Latency),
this.activeWaterfallSortId === waterfallSortIds.Latency);
function setWaterfallMode(this: NetworkLogViewColumns, sortId: WaterfallSortIds): void {
let calculator = this.calculatorsMap.get(_calculatorTypes.Time);
const waterfallSortIds = WaterfallSortIds;
if (sortId === waterfallSortIds.Duration || sortId === waterfallSortIds.Latency) {
calculator = this.calculatorsMap.get(_calculatorTypes.Duration);
}
this.networkLogView.setCalculator((calculator as NetworkTimeCalculator));
this.activeWaterfallSortId = sortId;
this.dataGridInternal.markColumnAsSortedBy('waterfall', DataGrid.DataGrid.Order.Ascending);
this.sortHandler();
}
}
private manageCustomHeaderDialog(): void {
const customHeaders = [];
for (const columnConfig of this.columns) {
const title = columnConfig.title instanceof Function ? columnConfig.title() : columnConfig.title;
if (columnConfig.isResponseHeader) {
customHeaders.push({title, editable: columnConfig.isCustomHeader});
}
}
const manageCustomHeaders = new NetworkManageCustomHeadersView(
customHeaders, headerTitle => Boolean(this.addCustomHeader(headerTitle)), this.changeCustomHeader.bind(this),
this.removeCustomHeader.bind(this));
const dialog = new UI.Dialog.Dialog();
manageCustomHeaders.show(dialog.contentElement);
dialog.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);
// @ts-ignore
// TypeScript somehow tries to appy the `WidgetElement` class to the
// `Document` type of the (Document|Element) union. WidgetElement inherits
// from HTMLElement so its valid to be passed here.
dialog.show(this.networkLogView.element);
}
private removeCustomHeader(headerId: string): boolean {
headerId = headerId.toLowerCase();
const index = this.columns.findIndex(columnConfig => columnConfig.id === headerId);
if (index === -1) {
return false;
}
this.columns.splice(index, 1);
this.dataGridInternal.removeColumn(headerId);
this.saveColumnsSettings();
this.updateColumns();
return true;
}
private addCustomHeader(headerTitle: string, headerId?: string, index?: number): Descriptor|null {
if (!headerId) {
headerId = headerTitle.toLowerCase();
}
if (index === undefined) {
index = this.columns.length - 1;
}
const currentColumnConfig = this.columns.find(columnConfig => columnConfig.id === headerId);
if (currentColumnConfig) {
return null;
}
const columnConfigBase = Object.assign({}, _defaultColumnConfig, {
id: headerId,
title: headerTitle,
isResponseHeader: true,
isCustomHeader: true,
visible: true,
sortingFunction: NetworkRequestNode.ResponseHeaderStringComparator.bind(null, headerId),
});
// Split out the column config from the typed version, as doing it in a single assignment causes
// issues with Closure compiler.
const columnConfig = (columnConfigBase as Descriptor);
this.columns.splice(index, 0, columnConfig);
if (this.dataGridInternal) {
this.dataGridInternal.addColumn(NetworkLogViewColumns.convertToDataGridDescriptor(columnConfig), index);
}
this.saveColumnsSettings();
this.updateColumns();
return columnConfig;
}
private changeCustomHeader(oldHeaderId: string, newHeaderTitle: string, newHeaderId?: string): boolean {
if (!newHeaderId) {
newHeaderId = newHeaderTitle.toLowerCase();
}
oldHeaderId = oldHeaderId.toLowerCase();
const oldIndex = this.columns.findIndex(columnConfig => columnConfig.id === oldHeaderId);
const oldColumnConfig = this.columns[oldIndex];
const currentColumnConfig = this.columns.find(columnConfig => columnConfig.id === newHeaderId);
if (!oldColumnConfig || (currentColumnConfig && oldHeaderId !== newHeaderId)) {
return false;
}
this.removeCustomHeader(oldHeaderId);
this.addCustomHeader(newHeaderTitle, newHeaderId, oldIndex);
return true;
}
private getPopoverRequest(event: Event): UI.PopoverHelper.PopoverRequest|null {
if (!this.gridMode) {
return null;
}
const hoveredNode = this.networkLogView.hoveredNode();
if (!hoveredNode || !event.target) {
return null;
}
const anchor = (event.target as HTMLElement).enclosingNodeOrSelfWithClass('network-script-initiated');
if (!anchor) {
return null;
}
const request = hoveredNode.request();
if (!request) {
return null;
}
return {
box: anchor.boxInWindow(),
show: async(popover: UI.GlassPane.GlassPane): Promise<boolean> => {
this.popupLinkifier.setLiveLocationUpdateCallback(() => {
popover.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent);
});
const content = RequestInitiatorView.createStackTracePreview(
(request as SDK.NetworkRequest.NetworkRequest), this.popupLinkifier, false);
if (!content) {
return false;
}
popover.contentElement.appendChild(content.element);
return true;
},
hide: this.popupLinkifier.reset.bind(this.popupLinkifier),
};
}
addEventDividers(times: number[], className: string): void {
// TODO(allada) Remove this and pass in the color.
let color = 'transparent';
switch (className) {
case 'network-dcl-divider':
color = '#0867CB';
break;
case 'network-load-divider':
color = '#B31412';
break;
default:
return;
}
const currentTimes = this.eventDividers.get(color) || [];
this.eventDividers.set(color, currentTimes.concat(times));
this.networkLogView.scheduleRefresh();
}
hideEventDividers(): void {
this.eventDividersShown = true;
this.redrawWaterfallColumn();
}
showEventDividers(): void {
this.eventDividersShown = false;
this.redrawWaterfallColumn();
}
selectFilmStripFrame(time: number): void {
this.eventDividers.set(_filmStripDividerColor, [time]);
this.redrawWaterfallColumn();
}
clearFilmStripFrame(): void {
this.eventDividers.delete(_filmStripDividerColor);
this.redrawWaterfallColumn();
}
}
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration)
// eslint-disable-next-line @typescript-eslint/naming-convention
export const _initialSortColumn = 'waterfall';
// TODO(crbug.com/1167717): Make this a const enum again
// eslint-disable-next-line rulesdir/const_enum, @typescript-eslint/naming-convention
export enum _calculatorTypes {
Duration = 'Duration',
Time = 'Time',
}
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration)
// eslint-disable-next-line @typescript-eslint/naming-convention
export const _defaultColumnConfig: Object = {
subtitle: null,
visible: false,
weight: 6,
sortable: true,
hideable: true,
hideableGroup: null,
nonSelectable: false,
isResponseHeader: false,
isCustomHeader: false,
allowInSortByEvenWhenHidden: false,
};
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration)
// eslint-disable-next-line @typescript-eslint/naming-convention
const _temporaryDefaultColumns = [
{
id: 'name',
title: i18nLazyString(UIStrings.name),
subtitle: i18nLazyString(UIStrings.path),
visible: true,
weight: 20,
hideable: true,
hideableGroup: 'path',
sortingFunction: NetworkRequestNode.NameComparator,
},
{
id: 'path',
title: i18nLazyString(UIStrings.path),
hideable: true,
hideableGroup: 'path',
sortingFunction: NetworkRequestNode.RequestPropertyComparator.bind(null, 'pathname'),
},
{
id: 'url',
title: i18nLazyString(UIStrings.url),
hideable: true,
hideableGroup: 'path',
sortingFunction: NetworkRequestNode.RequestURLComparator,
},
{
id: 'method',
title: i18nLazyString(UIStrings.method),
sortingFunction: NetworkRequestNode.RequestPropertyComparator.bind(null, 'requestMethod'),
},
{
id: 'status',
title: i18nLazyString(UIStrings.status),
visible: true,
subtitle: i18nLazyString(UIStrings.text),
sortingFunction: NetworkRequestNode.RequestPropertyComparator.bind(null, 'statusCode'),
},
{
id: 'protocol',
title: i18nLazyString(UIStrings.protocol),
sortingFunction: NetworkRequestNode.RequestPropertyComparator.bind(null, 'protocol'),
},
{
id: 'scheme',
title: i18nLazyString(UIStrings.scheme),
sortingFunction: NetworkRequestNode.RequestPropertyComparator.bind(null, 'scheme'),
},
{
id: 'domain',
title: i18nLazyString(UIStrings.domain),
sortingFunction: NetworkRequestNode.RequestPropertyComparator.bind(null, 'domain'),
},
{
id: 'remoteaddress',
title: i18nLazyString(UIStrings.remoteAddress),
weight: 10,
align: DataGrid.DataGrid.Align.Right,
sortingFunction: NetworkRequestNode.RemoteAddressComparator,
},
{
id: 'remoteaddress-space',
title: i18nLazyString(UIStrings.remoteAddressSpace),
visible: false,
weight: 10,
sortingFunction: NetworkRequestNode.RemoteAddressSpaceComparator,
},
{
id: 'type',
title: i18nLazyString(UIStrings.type),
visible: true,
sortingFunction: NetworkRequestNode.TypeComparator,
},
{
id: 'initiator',
title: i18nLazyString(UIStrings.initiator),
visible: true,
weight: 10,
sortingFunction: NetworkRequestNode.InitiatorComparator,
},
{
id: 'initiator-address-space',
title: i18nLazyString(UIStrings.initiatorAddressSpace),
visible: false,
weight: 10,
sortingFunction: NetworkRequestNode.InitiatorAddressSpaceComparator,
},
{
id: 'cookies',
title: i18nLazyString(UIStrings.cookies),
align: DataGrid.DataGrid.Align.Right,
sortingFunction: NetworkRequestNode.RequestCookiesCountComparator,
},
{
id: 'setcookies',
title: i18nLazyString(UIStrings.setCookies),
align: DataGrid.DataGrid.Align.Right,
sortingFunction: NetworkRequestNode.ResponseCookiesCountComparator,
},
{
id: 'size',
title: i18nLazyString(UIStrings.size),
visible: true,
subtitle: i18nLazyString(UIStrings.content),
align: DataGrid.DataGrid.Align.Right,
sortingFunction: NetworkRequestNode.SizeComparator,
},
{
id: 'time',
title: i18nLazyString(UIStrings.time),
visible: true,
subtitle: i18nLazyString(UIStrings.latency),
align: DataGrid.DataGrid.Align.Right,
sortingFunction: NetworkRequestNode.RequestPropertyComparator.bind(null, 'duration'),
},
{id: 'priority', title: i18nLazyString(UIStrings.priority), sortingFunction: NetworkRequestNode.PriorityComparator},
{
id: 'connectionid',
title: i18nLazyString(UIStrings.connectionId),
sortingFunction: NetworkRequestNode.RequestPropertyComparator.bind(null, 'connectionId'),
},
{
id: 'cache-control',
isResponseHeader: true,
title: i18n.i18n.lockedLazyString('Cache-Control'),
sortingFunction: NetworkRequestNode.ResponseHeaderStringComparator.bind(null, 'cache-control'),
},
{
id: 'connection',
isResponseHeader: true,
title: i18n.i18n.lockedLazyString('Connection'),
sortingFunction: NetworkRequestNode.ResponseHeaderStringComparator.bind(null, 'connection'),
},
{
id: 'content-encoding',
isResponseHeader: true,
title: i18n.i18n.lockedLazyString('Content-Encoding'),
sortingFunction: NetworkRequestNode.ResponseHeaderStringComparator.bind(null, 'content-encoding'),
},
{
id: 'content-length',
isResponseHeader: true,
title: i18n.i18n.lockedLazyString('Content-Length'),
align: DataGrid.DataGrid.Align.Right,
sortingFunction: NetworkRequestNode.ResponseHeaderNumberComparator.bind(null, 'content-length'),
},
{
id: 'etag',
isResponseHeader: true,
title: i18n.i18n.lockedLazyString('ETag'),
sortingFunction: NetworkRequestNode.ResponseHeaderStringComparator.bind(null, 'etag'),
},
{
id: 'keep-alive',
isResponseHeader: true,
title: i18n.i18n.lockedLazyString('Keep-Alive'),
sortingFunction: NetworkRequestNode.ResponseHeaderStringComparator.bind(null, 'keep-alive'),
},
{
id: 'last-modified',
isResponseHeader: true,
title: i18n.i18n.lockedLazyString('Last-Modified'),
sortingFunction: NetworkRequestNode.ResponseHeaderDateComparator.bind(null, 'last-modified'),
},
{
id: 'server',
isResponseHeader: true,
title: i18n.i18n.lockedLazyString('Server'),
sortingFunction: NetworkRequestNode.ResponseHeaderStringComparator.bind(null, 'server'),
},
{
id: 'vary',
isResponseHeader: true,
title: i18n.i18n.lockedLazyString('Vary'),
sortingFunction: NetworkRequestNode.ResponseHeaderStringComparator.bind(null, 'vary'),
},
// This header is a placeholder to let datagrid know that it can be sorted by this column, but never shown.
{
id: 'waterfall',
title: i18nLazyString(UIStrings.waterfall),
visible: false,
hideable: false,
allowInSortByEvenWhenHidden: true,
},
];
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration)
// eslint-disable-next-line @typescript-eslint/naming-convention, @typescript-eslint/no-explicit-any
const _defaultColumns = (_temporaryDefaultColumns as any);
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration)
// eslint-disable-next-line @typescript-eslint/naming-convention
export const _filmStripDividerColor = '#fccc49';
// TODO(crbug.com/1167717): Make this a const enum again
// eslint-disable-next-line rulesdir/const_enum
export enum WaterfallSortIds {
StartTime = 'startTime',
ResponseTime = 'responseReceivedTime',
EndTime = 'endTime',
Duration = 'duration',
Latency = 'latency',
}
export interface Descriptor {
id: string;
title: string|(() => string);
titleDOMFragment?: DocumentFragment;
subtitle: string|(() => string)|null;
visible: boolean;
weight: number;
hideable: boolean;
hideableGroup: string|null;
nonSelectable: boolean;
sortable: boolean;
align?: string|null;
isResponseHeader: boolean;
sortingFunction: (arg0: NetworkNode, arg1: NetworkNode) => number | undefined;
isCustomHeader: boolean;
allowInSortByEvenWhenHidden: boolean;
} | the_stack |
export enum SyncerClass {
NwjsBinary = 'NwjsBinary',
NodeBinary = 'NodeBinary',
CypressBinary = 'CypressBinary',
BucketBinary = 'BucketBinary',
GithubBinary = 'GithubBinary',
Sqlite3Binary = 'Sqlite3Binary',
SqlcipherBinary = 'SqlcipherBinary',
PuppeteerBinary = 'PuppeteerBinary',
NodePreGypBinary = 'NodePreGypBinary',
ImageminBinary = 'ImageminBinary',
}
export type BinaryTaskConfig = {
category: string;
description: string;
syncer: SyncerClass;
repo: string;
distUrl: string;
ignoreDirs?: string[];
options?: {
nodePlatforms?: string[],
nodeArchs?: {
[key: string]: string[],
},
// Imagemin binFiles
binFiles?: {
[key: string]: string[],
},
},
disable?: boolean;
};
const binaries: {
[category: string]: BinaryTaskConfig;
} = {
// NwjsBinary
nwjs: {
category: 'nwjs',
description: 'NW.js (previously known as node-webkit) lets you call all Node.js modules directly from DOM and enables a new way of writing applications with all Web technologies.',
syncer: SyncerClass.NwjsBinary,
repo: 'nwjs/nw.js',
distUrl: 'https://dl.nwjs.io/',
},
// NodeBinary
node: {
category: 'node',
description: 'Node.js® is a JavaScript runtime built on Chrome\'s V8 JavaScript engine.',
syncer: SyncerClass.NodeBinary,
repo: 'nodejs/node',
distUrl: 'https://nodejs.org/dist',
},
'node-unofficial-builds': {
category: 'node-unofficial-builds',
description: 'Node.js unofficial-builds project https://unofficial-builds.nodejs.org/',
syncer: SyncerClass.NodeBinary,
repo: 'nodejs/unofficial-builds',
distUrl: 'https://unofficial-builds.nodejs.org/download/release',
},
alinode: {
category: 'alinode',
description: 'Node.js 性能平台(Node.js Performance Platform)是面向中大型 Node.js 应用提供性能监控、安全提醒、故障排查、性能优化等服务的整体性解决方案。凭借对 Node.js 内核深入的理解,我们提供完善的工具链和服务,协助客户主动、快速发现和定位线上问题。',
syncer: SyncerClass.NodeBinary,
repo: '',
distUrl: 'http://alinode.aliyun.com/dist/new-alinode',
},
python: {
category: 'python',
description: 'The Python programming language https://www.python.org/',
syncer: SyncerClass.NodeBinary,
repo: 'python/cpython',
distUrl: 'https://www.python.org/ftp/python',
},
// CypressBinary
cypress: {
category: 'cypress',
description: 'Fast, easy and reliable testing for anything that runs in a browser.',
syncer: SyncerClass.CypressBinary,
repo: 'cypress-io/cypress',
distUrl: 'https://www.cypress.io/',
},
// Sqlite3Binary
sqlite3: {
category: 'sqlite3',
description: 'Asynchronous, non-blocking SQLite3 bindings for Node.js',
syncer: SyncerClass.Sqlite3Binary,
repo: 'mapbox/node-sqlite3',
distUrl: 'https://mapbox-node-binary.s3.amazonaws.com',
},
// SqlcipherBinary
'@journeyapps/sqlcipher': {
category: '@journeyapps/sqlcipher',
description: 'SQLCipher bindings for Node',
syncer: SyncerClass.SqlcipherBinary,
repo: 'journeyapps/node-sqlcipher',
distUrl: 'https://journeyapps-node-binary.s3.amazonaws.com',
},
// PuppeteerBinary
'chromium-browser-snapshots': {
category: 'chromium-browser-snapshots',
description: 'chromium-browser-snapshots sync for puppeteer',
syncer: SyncerClass.PuppeteerBinary,
repo: 'puppeteer/puppeteer',
distUrl: 'https://chromium-browser-snapshots.storage.googleapis.com/?delimiter=/&prefix=',
},
// NodePreGypBinary
'grpc-tools': {
category: 'grpc-tools',
description: 'Tools for developing with gRPC on Node.js',
syncer: SyncerClass.NodePreGypBinary,
repo: 'https://github.com/grpc/grpc-node/blob/master/packages/grpc-tools/',
distUrl: 'https://node-precompiled-binaries.grpc.io',
},
grpc: {
category: 'grpc',
description: 'gRPC Library for Node',
syncer: SyncerClass.NodePreGypBinary,
repo: 'grpc/grpc-node',
distUrl: 'https://node-precompiled-binaries.grpc.io',
},
nodegit: {
category: 'nodegit',
description: 'Native Node bindings to Git.',
syncer: SyncerClass.NodePreGypBinary,
repo: 'nodegit/nodegit',
distUrl: 'https://axonodegit.s3.amazonaws.com/nodegit',
options: {
nodeArchs: {
linux: [ 'x64' ],
darwin: [ 'x64' ],
// https://github.com/nodegit/nodegit/blob/master/.github/workflows/tests.yml#L141
win32: [ 'x64', 'ia32' ],
},
},
// don't sync it for now
disable: true,
},
// BucketBinary
chromedriver: {
category: 'chromedriver',
description: 'WebDriver is an open source tool for automated testing of webapps across many browsers',
syncer: SyncerClass.BucketBinary,
repo: 'https://chromedriver.chromium.org/contributing',
distUrl: 'https://chromedriver.storage.googleapis.com/',
},
selenium: {
category: 'selenium',
description: 'Selenium automates browsers. That\'s it!',
syncer: SyncerClass.BucketBinary,
repo: 'https://www.selenium.dev/',
distUrl: 'https://selenium-release.storage.googleapis.com/',
},
'node-inspector': {
category: 'node-inspector',
description: 'Node.js debugger based on Blink Developer Tools',
syncer: SyncerClass.BucketBinary,
repo: 'node-inspector/node-inspector',
distUrl: 'https://node-inspector.s3.amazonaws.com/',
ignoreDirs: [
'/AWSLogs/',
],
},
fsevents: {
category: 'fsevents',
description: 'Native access to MacOS FSEvents in Node.js',
syncer: SyncerClass.BucketBinary,
repo: 'fsevents/fsevents',
distUrl: 'https://fsevents-binaries.s3-us-west-2.amazonaws.com/',
},
'tfjs-models': {
category: 'tfjs-models',
description: 'Pretrained models for TensorFlow.js',
syncer: SyncerClass.BucketBinary,
repo: 'tensorflow/tfjs-models',
distUrl: 'https://tfjs-models.storage.googleapis.com/',
},
tensorflow: {
category: 'tensorflow',
description: 'A WebGL accelerated JavaScript library for training and deploying ML models.',
syncer: SyncerClass.BucketBinary,
repo: 'tensorflow/tfjs',
distUrl: 'https://tensorflow.storage.googleapis.com/',
},
'tf-builds': {
category: 'tf-builds',
description: 'A WebGL accelerated JavaScript library for training and deploying ML models.',
syncer: SyncerClass.BucketBinary,
repo: 'tensorflow/tfjs',
distUrl: 'https://tf-builds.storage.googleapis.com/',
},
prisma: {
category: 'prisma',
description: 'Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite & MongoDB (Preview) https://www.prisma.io/',
syncer: SyncerClass.BucketBinary,
repo: 'prisma/prisma',
distUrl: 'https://prisma-builds.s3-eu-west-1.amazonaws.com/',
ignoreDirs: [
// https://prisma-builds.s3-eu-west-1.amazonaws.com/?delimiter=/&prefix=
'/all_commits/',
'/build_testruns/',
'/bump_engineer/',
'/m1_builds/',
'/master/',
'/ci/',
'/unreverse/',
'/signature_test_run/',
'/sql-server-char-collation-fix/',
'/test-ldd-output-on-release/',
'/windows-mysql-ci/',
],
},
// ImageminBinary
'jpegtran-bin': {
category: 'jpegtran-bin',
description: 'jpegtran bin-wrapper that makes it seamlessly available as a local dependency',
syncer: SyncerClass.ImageminBinary,
repo: 'imagemin/jpegtran-bin',
distUrl: 'https://raw.githubusercontent.com',
options: {
// https://github.com/imagemin/jpegtran-bin/blob/v4.0.0/lib/index.js
nodePlatforms: [ 'macos', 'linux', 'freebsd', 'sunos', 'win' ],
nodeArchs: {
macos: [],
linux: [ 'x86', 'x64' ],
freebsd: [ 'x86', 'x64' ],
sunos: [ 'x86', 'x64' ],
win: [ 'x86', 'x64' ],
},
binFiles: {
macos: [ 'jpegtran' ],
linux: [ 'jpegtran' ],
freebsd: [ 'jpegtran' ],
sunos: [ 'jpegtran' ],
win: [ 'jpegtran.exe', 'libjpeg-62.dll' ],
},
},
},
'pngquant-bin': {
category: 'pngquant-bin',
description: 'pngquant bin-wrapper that makes it seamlessly available as a local dependency',
syncer: SyncerClass.ImageminBinary,
repo: 'imagemin/pngquant-bin',
distUrl: 'https://raw.githubusercontent.com',
options: {
// https://github.com/imagemin/pngquant-bin/blob/v4.0.0/lib/index.js
nodePlatforms: [ 'macos', 'linux', 'freebsd', 'win' ],
nodeArchs: {
macos: [],
linux: [ 'x86', 'x64' ],
freebsd: [ 'x64' ],
win: [],
},
binFiles: {
macos: [ 'pngquant' ],
linux: [ 'pngquant' ],
freebsd: [ 'pngquant' ],
win: [ 'pngquant.exe' ],
},
},
},
'mozjpeg-bin': {
category: 'mozjpeg-bin',
description: 'mozjpeg bin-wrapper that makes it seamlessly available as a local dependency',
syncer: SyncerClass.ImageminBinary,
repo: 'imagemin/mozjpeg-bin',
distUrl: 'https://raw.githubusercontent.com',
options: {
// https://github.com/imagemin/mozjpeg-bin/blob/v4.0.0/lib/index.js
// https://github.com/imagemin/mozjpeg-bin/blob/v5.0.0/lib/index.js
nodePlatforms: [ 'osx', 'macos', 'linux', 'win' ],
nodeArchs: {
osx: [],
macos: [],
linux: [],
win: [],
},
binFiles: {
osx: [ 'cjpeg' ],
macos: [ 'cjpeg' ],
linux: [ 'cjpeg' ],
win: [ 'cjpeg.exe' ],
},
},
},
'gifsicle-bin': {
category: 'gifsicle-bin',
description: 'gifsicle bin-wrapper that makes it seamlessly available as a local dependency',
syncer: SyncerClass.ImageminBinary,
repo: 'imagemin/gifsicle-bin',
distUrl: 'https://raw.githubusercontent.com',
options: {
// https://github.com/imagemin/gifsicle-bin/blob/v4.0.0/lib/index.js
// https://github.com/imagemin/gifsicle-bin/blob/v5.0.0/lib/index.js
nodePlatforms: [ 'macos', 'linux', 'freebsd', 'win' ],
nodeArchs: {
macos: [],
linux: [ 'x86', 'x64' ],
freebsd: [ 'x86', 'x64' ],
win: [ 'x86', 'x64' ],
},
binFiles: {
macos: [ 'gifsicle' ],
linux: [ 'gifsicle' ],
freebsd: [ 'gifsicle' ],
win: [ 'gifsicle.exe' ],
},
},
},
'optipng-bin': {
category: 'optipng-bin',
description: 'optipng bin-wrapper that makes it seamlessly available as a local dependency',
syncer: SyncerClass.ImageminBinary,
repo: 'imagemin/optipng-bin',
distUrl: 'https://raw.githubusercontent.com',
options: {
// https://github.com/imagemin/optipng-bin/blob/v4.0.0/lib/index.js
// https://github.com/imagemin/optipng-bin/blob/v5.0.0/lib/index.js
nodePlatforms: [ 'macos', 'linux', 'freebsd', 'sunos', 'win' ],
nodeArchs: {
macos: [],
linux: [ 'x86', 'x64' ],
freebsd: [ 'x86', 'x64' ],
sunos: [ 'x86', 'x64' ],
win: [],
},
binFiles: {
macos: [ 'optipng' ],
linux: [ 'optipng' ],
freebsd: [ 'optipng' ],
sunos: [ 'optipng' ],
win: [ 'optipng.exe' ],
},
},
},
'zopflipng-bin': {
category: 'zopflipng-bin',
description: 'zopflipng bin-wrapper that makes it seamlessly available as a local dependency',
syncer: SyncerClass.ImageminBinary,
repo: 'imagemin/zopflipng-bin',
distUrl: 'https://raw.githubusercontent.com',
options: {
// https://github.com/imagemin/zopflipng-bin/blob/v4.0.0/lib/index.js
// https://github.com/imagemin/zopflipng-bin/blob/v5.0.0/lib/index.js
nodePlatforms: [ 'osx', 'linux', 'win32' ],
nodeArchs: {
osx: [],
linux: [],
win32: [],
},
binFiles: {
osx: [ 'zopflipng' ],
linux: [ 'zopflipng' ],
win32: [ 'zopflipng.exe' ],
},
},
},
'jpegoptim-bin': {
category: 'jpegoptim-bin',
description: 'jpegoptim bin-wrapper that makes it seamlessly available as a local dependency',
syncer: SyncerClass.ImageminBinary,
repo: 'imagemin/jpegoptim-bin',
distUrl: 'https://raw.githubusercontent.com',
options: {
// https://github.com/imagemin/jpegoptim-bin/blob/v4.0.0/lib/index.js
// https://github.com/imagemin/jpegoptim-bin/blob/v5.0.0/lib/index.js
nodePlatforms: [ 'osx', 'linux', 'win32' ],
nodeArchs: {
osx: [],
linux: [],
win32: [],
},
binFiles: {
osx: [ 'jpegoptim' ],
linux: [ 'jpegoptim' ],
win32: [ 'jpegoptim.exe' ],
},
},
},
'jpeg-recompress-bin': {
category: 'jpeg-recompress-bin',
description: 'jpeg-recompress bin-wrapper that makes it seamlessly available as a local dependency',
syncer: SyncerClass.ImageminBinary,
repo: 'imagemin/jpeg-recompress-bin',
distUrl: 'https://raw.githubusercontent.com',
options: {
// https://github.com/imagemin/jpeg-recompress-bin/blob/v4.0.0/lib/index.js
// https://github.com/imagemin/jpeg-recompress-bin/blob/v5.0.0/lib/index.js
nodePlatforms: [ 'osx', 'linux', 'win' ],
nodeArchs: {
osx: [],
linux: [],
win: [],
},
binFiles: {
osx: [ 'jpeg-recompress' ],
linux: [ 'jpeg-recompress' ],
win: [ 'jpeg-recompress.exe' ],
},
},
},
'pngcrush-bin': {
category: 'pngcrush-bin',
description: 'pngcrush bin-wrapper that makes it seamlessly available as a local dependency',
syncer: SyncerClass.ImageminBinary,
repo: 'imagemin/pngcrush-bin',
distUrl: 'https://raw.githubusercontent.com',
options: {
// https://github.com/imagemin/pngcruss-bin/blob/v4.0.0/lib/index.js
// https://github.com/imagemin/pngcrush-bin/blob/v5.0.0/lib/index.js
nodePlatforms: [ 'osx', 'linux', 'win' ],
nodeArchs: {
osx: [],
linux: [],
win: [ 'x64', 'x86' ],
},
binFiles: {
osx: [ 'pngcrush' ],
linux: [ 'pngcrush' ],
win: [ 'pngcrush.exe' ],
},
},
},
'pngout-bin': {
category: 'pngout-bin',
description: 'pngout bin-wrapper that makes it seamlessly available as a local dependency',
syncer: SyncerClass.ImageminBinary,
repo: 'imagemin/pngout-bin',
distUrl: 'https://raw.githubusercontent.com',
options: {
// https://github.com/imagemin/pngout-bin/blob/v4.0.0/lib/index.js
// https://github.com/imagemin/pngout-bin/blob/v5.0.0/lib/index.js
nodePlatforms: [ 'osx', 'linux', 'freebsd', 'win32' ],
nodeArchs: {
osx: [],
linux: [ 'x64', 'x86' ],
freebsd: [ 'x64', 'x86' ],
win32: [ ],
},
binFiles: {
osx: [ 'pngcrush' ],
linux: [ 'pngcrush' ],
freebsd: [ 'pngout' ],
win32: [ 'pngcrush.exe' ],
},
},
},
'gif2webp-bin': {
category: 'gif2webp-bin',
description: 'gif2webp bin-wrapper that makes it seamlessly available as a local dependency',
syncer: SyncerClass.ImageminBinary,
repo: 'imagemin/gif2webp-bin',
distUrl: 'https://raw.githubusercontent.com',
options: {
// https://github.com/imagemin/gif2webp-bin/blob/v4.0.0/lib/index.js
nodePlatforms: [ 'macos', 'linux', 'win' ],
nodeArchs: {
macos: [],
linux: [ ],
win: [ ],
},
binFiles: {
macos: [ 'gif2webp' ],
linux: [ 'gif2webp' ],
win: [ 'gif2webp.exe' ],
},
},
},
'guetzli-bin': {
category: 'guetzli-bin',
description: 'guetzli bin-wrapper that makes it seamlessly available as a local dependency',
syncer: SyncerClass.ImageminBinary,
repo: 'imagemin/guetzli-bin',
distUrl: 'https://raw.githubusercontent.com',
options: {
// https://github.com/imagemin/guetzli-bin/blob/v4.0.0/lib/index.js
nodePlatforms: [ 'macos', 'linux', 'win' ],
nodeArchs: {
macos: [],
linux: [ ],
win: [ ],
},
binFiles: {
macos: [ 'guetzli' ],
linux: [ 'guetzli' ],
win: [ 'guetzli.exe' ],
},
},
},
'advpng-bin': {
category: 'advpng-bin',
description: 'advpng bin-wrapper that makes it seamlessly available as a local dependency',
syncer: SyncerClass.ImageminBinary,
repo: 'imagemin/advpng-bin',
distUrl: 'https://raw.githubusercontent.com',
options: {
// https://github.com/imagemin/advpng-bin/blob/v4.0.0/lib/index.js
nodePlatforms: [ 'osx', 'linux', 'win32' ],
nodeArchs: {
osx: [],
linux: [],
win32: [ ],
},
binFiles: {
osx: [ 'advpng' ],
linux: [ 'advpng' ],
win32: [ 'advpng.exe' ],
},
},
},
'cwebp-bin': {
category: 'cwebp-bin',
description: 'cwebp bin-wrapper that makes it seamlessly available as a local dependency',
syncer: SyncerClass.ImageminBinary,
repo: 'imagemin/cwebp-bin',
distUrl: 'https://raw.githubusercontent.com',
options: {
// https://github.com/imagemin/cwebp-bin/blob/v4.0.0/lib/index.js
nodePlatforms: [ 'osx', 'linux', 'win' ],
nodeArchs: {
osx: [],
linux: [ 'x86', 'x64' ],
win: [ 'x86', 'x64' ],
},
binFiles: {
osx: [ 'cwebp' ],
linux: [ 'cwebp' ],
win: [ 'cwebp.exe' ],
},
},
},
// GithubBinary
xprofiler: {
category: 'xprofiler',
description: '🌀An addon for node.js, which supporting output performance log and real-time profiling through sampling.',
syncer: SyncerClass.GithubBinary,
repo: 'X-Profiler/xprofiler',
distUrl: 'https://github.com/X-Profiler/xprofiler/releases',
},
'node-sass': {
category: 'node-sass',
description: '🌈 Node.js bindings to libsass',
syncer: SyncerClass.GithubBinary,
repo: 'sass/node-sass',
distUrl: 'https://github.com/sass/node-sass/releases',
},
electron: {
category: 'electron',
description: 'Build cross-platform desktop apps with JavaScript, HTML, and CSS',
syncer: SyncerClass.GithubBinary,
repo: 'electron/electron',
distUrl: 'https://github.com/electron/electron/releases',
},
'electron-builder-binaries': {
category: 'electron-builder-binaries',
description: 'electron-builder downloads required tools files on demand (e.g. to code sign windows application, to make AppX).',
syncer: SyncerClass.GithubBinary,
repo: 'electron-userland/electron-builder-binaries',
distUrl: 'https://github.com/electron-userland/electron-builder-binaries/releases',
},
canvas: {
category: 'canvas',
description: 'Node canvas is a Cairo backed Canvas implementation for NodeJS.',
syncer: SyncerClass.GithubBinary,
repo: 'Automattic/node-canvas',
distUrl: 'https://github.com/Automattic/node-canvas/releases',
},
nodejieba: {
category: 'nodejieba',
description: '"结巴"中文分词的Node.js版本',
syncer: SyncerClass.GithubBinary,
repo: 'yanyiwu/nodejieba',
distUrl: 'https://github.com/yanyiwu/nodejieba/releases',
},
'git-for-windows': {
category: 'git-for-windows',
description: 'A fork of Git containing Windows-specific patches.',
syncer: SyncerClass.GithubBinary,
repo: 'git-for-windows/git',
distUrl: 'https://github.com/git-for-windows/git/releases',
},
atom: {
category: 'atom',
description: 'The hackable text editor',
syncer: SyncerClass.GithubBinary,
repo: 'atom/atom',
distUrl: 'https://github.com/atom/atom/releases',
},
operadriver: {
category: 'operadriver',
description: 'OperaDriver for Chromium-based Opera releases',
syncer: SyncerClass.GithubBinary,
repo: 'operasoftware/operachromiumdriver',
distUrl: 'https://github.com/operasoftware/operachromiumdriver/releases',
},
geckodriver: {
category: 'geckodriver',
description: 'WebDriver for Firefox',
syncer: SyncerClass.GithubBinary,
repo: 'mozilla/geckodriver',
distUrl: 'https://github.com/mozilla/geckodriver/releases',
},
leveldown: {
category: 'leveldown',
description: 'Pure C++ Node.js LevelDB binding. An abstract-leveldown compliant store.',
syncer: SyncerClass.GithubBinary,
repo: 'Level/leveldown',
distUrl: 'https://github.com/Level/leveldown/releases',
},
couchbase: {
category: 'couchbase',
description: 'Couchbase Node.js Client Library (Official)',
syncer: SyncerClass.GithubBinary,
repo: 'couchbase/couchnode',
distUrl: 'https://github.com/couchbase/couchnode/releases',
},
gl: {
category: 'gl',
description: '🎃 Windowless WebGL for node.js',
syncer: SyncerClass.GithubBinary,
repo: 'stackgl/headless-gl',
distUrl: 'https://github.com/stackgl/headless-gl/releases',
},
flow: {
category: 'flow',
description: 'Adds static typing to JavaScript to improve developer productivity and code quality.',
syncer: SyncerClass.GithubBinary,
repo: 'facebook/flow',
distUrl: 'https://github.com/facebook/flow/releases',
},
robotjs: {
category: 'robotjs',
description: 'Node.js Desktop Automation. http://robotjs.io/',
syncer: SyncerClass.GithubBinary,
repo: 'octalmage/robotjs',
distUrl: 'https://github.com/octalmage/robotjs/releases',
},
poi: {
category: 'poi',
description: 'Scalable KanColle browser and tool. https://poi.io/',
syncer: SyncerClass.GithubBinary,
repo: 'poooi/poi',
distUrl: 'https://github.com/poooi/poi/releases',
},
'utf-8-validate': {
category: 'utf-8-validate',
description: 'Check if a buffer contains valid UTF-8',
syncer: SyncerClass.GithubBinary,
repo: 'websockets/utf-8-validate',
distUrl: 'https://github.com/websockets/utf-8-validate/releases',
},
minikube: {
category: 'minikube',
description: 'Run Kubernetes locally https://minikube.sigs.k8s.io/',
syncer: SyncerClass.GithubBinary,
repo: 'kubernetes/minikube',
distUrl: 'https://github.com/kubernetes/minikube/releases',
},
'sentry-cli': {
category: 'sentry-cli',
description: 'A command line utility to work with Sentry. https://docs.sentry.io/cli/',
syncer: SyncerClass.GithubBinary,
repo: 'getsentry/sentry-cli',
distUrl: 'https://github.com/getsentry/sentry-cli/releases',
},
'sharp-libvips': {
category: 'sharp-libvips',
description: 'Packaging scripts to prebuild libvips and its dependencies - you\'re probably looking for https://github.com/lovell/sharp',
syncer: SyncerClass.GithubBinary,
repo: 'lovell/sharp-libvips',
distUrl: 'https://github.com/lovell/sharp-libvips/releases',
},
sharp: {
category: 'sharp',
description: 'High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, AVIF and TIFF images. Uses the libvips library. https://sharp.pixelplumbing.com/',
syncer: SyncerClass.GithubBinary,
repo: 'lovell/sharp',
distUrl: 'https://github.com/lovell/sharp/releases',
},
swc: {
category: 'swc',
description: 'swc is a super-fast compiler written in rust; producing widely-supported javascript from modern standards and typescript. https://swc.rs/',
syncer: SyncerClass.GithubBinary,
repo: 'swc-project/swc',
distUrl: 'https://github.com/swc-project/swc/releases',
},
'node-swc': {
category: 'node-swc',
description: 'Experimental repo to avoid spamming watchers, see https://github.com/swc-project/swc',
syncer: SyncerClass.GithubBinary,
repo: 'swc-project/node-swc',
distUrl: 'https://github.com/swc-project/node-swc/releases',
},
argon2: {
category: 'argon2',
description: 'Node.js bindings for Argon2 hashing algorithm',
syncer: SyncerClass.GithubBinary,
repo: 'ranisalt/node-argon2',
distUrl: 'https://github.com/ranisalt/node-argon2/releases',
},
iohook: {
category: 'iohook',
description: 'Node.js global keyboard and mouse listener.',
syncer: SyncerClass.GithubBinary,
repo: 'wilix-team/iohook',
distUrl: 'https://github.com/wilix-team/iohook/releases',
},
saucectl: {
category: 'saucectl',
description: 'A command line interface to run testrunner tests',
syncer: SyncerClass.GithubBinary,
repo: 'saucelabs/saucectl',
distUrl: 'https://github.com/saucelabs/saucectl/releases',
},
'node-gdal-async': {
category: 'node-gdal-async',
description: 'Node.js bindings for GDAL (Geospatial Data Abstraction Library) with full async support. https://mmomtchev.github.io/node-gdal-async/',
syncer: SyncerClass.GithubBinary,
repo: 'mmomtchev/node-gdal-async',
distUrl: 'https://github.com/mmomtchev/node-gdal-async/releases',
},
'looksgood-s2': {
category: 'looksgood-s2',
description: 'Node.js JavaScript & TypeScript bindings for Google S2.',
syncer: SyncerClass.GithubBinary,
repo: 'looksgood/s2',
distUrl: 'https://github.com/looksgood/s2/releases',
},
};
export default binaries; | the_stack |
import { call, put, select, take } from 'redux-saga/effects'
import * as AccountAction from '../actions/account'
import * as CommonAction from '../actions/common'
import AccountService from './services/Account'
import { StoreStateRouterLocationURI, replace, push } from '../family'
import { RootState } from '../actions/types'
import { showMessage, MSG_TYPE } from 'actions/common'
import { THEME_TEMPLATE_KEY } from 'components/account/ThemeChangeOverlay'
import { CHANGE_THEME, DoUpdateUserSettingAction, updateUserSetting, UPDATE_USER_SETTING_SUCCESS, DO_UPDATE_USER_SETTING, UPDATE_ACCOUNT_SUCCESS, UPDATE_ACCOUNT_FAILURE } from '../actions/account'
import { AnyAction } from 'redux'
import { createCommonDoActionSaga } from './effects/commonSagas'
const relatives = {
reducers: {
userSettings(state: RootState['userSettings'] = {}, action: any) {
switch (action.type) {
case AccountAction.FETCH_USER_SETTINGS_SUCCESS: {
if (action.payload.isOk) {
return {
...state,
...action.payload.data,
}
}
break
}
}
return state
},
userSettingsIsUpdating(state: boolean = false, action: any) {
switch (action.type) {
case AccountAction.UPDATE_USER_SETTING_REQUEST:
case AccountAction.FETCH_USER_SETTINGS_REQUEST:
return true
case AccountAction.UPDATE_USER_SETTING_FAILURE:
case AccountAction.UPDATE_USER_SETTING_SUCCESS:
case AccountAction.FETCH_USER_SETTINGS_FAILURE:
case AccountAction.FETCH_USER_SETTINGS_SUCCESS:
return false
}
return state
},
themeId(state: THEME_TEMPLATE_KEY = THEME_TEMPLATE_KEY.INDIGO, action: any) {
switch (action.type) {
case CHANGE_THEME:
return action.payload
default:
return state
}
},
loading(state: boolean = false, action: any) {
switch (action.type) {
case 'INTERFACE_LOCK':
case 'INTERFACE_UNLOCK':
case 'REPOSITORY_UPDATE':
case 'PROPERTIES_UPDATE':
return true
case 'INTERFACE_LOCK_SUCCEEDED':
case 'INTERFACE_LOCK_FAILED':
case 'INTERFACE_UNLOCK_SUCCEEDED':
case 'INTERFACE_UNLOCK_FAILED':
case 'REPOSITORY_UPDATE_SUCCEEDED':
case 'REPOSITORY_UPDATE_FAILED':
case 'PROPERTIES_UPDATE_SUCCEEDED':
case 'PROPERTIES_UPDATE_FAILED':
return false
}
return state
},
auth(state: any = {}, action: any) {
switch (action.type) {
case AccountAction.findpwdSucceeded().type:
case AccountAction.findpwdFailed('').type:
case AccountAction.loginSucceeded({}).type:
case AccountAction.fetchLoginInfoSucceeded({}).type:
return action.user && action.user.id ? action.user : {}
case AccountAction.loginFailed('').type:
case AccountAction.logoutSucceeded().type:
case AccountAction.logoutFailed().type:
case AccountAction.fetchLoginInfoFailed('').type:
return {}
default:
return state
}
},
user(state: any = {}, action: any) {
switch (action.type) {
case AccountAction.findpwdSucceeded().type:
case AccountAction.findpwdFailed('').type:
case AccountAction.loginSucceeded({}).type:
case AccountAction.fetchLoginInfoSucceeded({}).type:
return action.user && action.user.id ? action.user : {}
case AccountAction.loginFailed('').type:
case AccountAction.logoutSucceeded().type:
case AccountAction.logoutFailed().type:
case AccountAction.fetchLoginInfoFailed('').type:
return {}
default:
return state
}
},
users(
state: any = {
data: [],
pagination: { total: 0, limit: 100, cursor: 1 },
},
action: any
) {
switch (action.type) {
case '...':
return state
case AccountAction.addUserSucceeded({}).type:
return {
data: [...state.data, action.user],
pagination: state.pagination,
}
case AccountAction.fetchUserCountSucceeded(0).type:
return {
data: [...state.data],
pagination: { ...state.pagination, total: action.count },
}
case AccountAction.fetchUserListSucceeded([]).type:
return action.users
default:
return state
}
},
},
sagas: {
*[AccountAction.DO_FETCH_USER_SETTINGS](action: AccountAction.DoFetchUserSettingsAction) {
const { keys, cb } = action.payload
yield put(AccountAction.fetchUserSettings(keys) as AnyAction)
const resultAction = yield take(AccountAction.FETCH_USER_SETTINGS_SUCCESS)
cb && cb(true, resultAction.payload)
},
*[AccountAction.FETCH_USER_SETTINGS_SUCCESS](action: any) {
const themeId = action.payload?.data?.THEME_ID
if (themeId) {
yield put(AccountAction.changeTheme(themeId))
}
},
*[CommonAction.refresh().type]() {
const router = yield select((state: RootState) => state.router)
const uri = StoreStateRouterLocationURI(router)
yield put(replace(uri.href()))
},
*[AccountAction.fetchLoginInfo().type]() {
try {
const user = yield call(AccountService.fetchLoginInfo)
if (user.id) {
yield put(AccountAction.fetchLoginInfoSucceeded(user))
}
} catch (e) {
yield put(AccountAction.fetchLoginInfoFailed(e.message))
}
},
*[AccountAction.addUser(null, null).type](action: any) {
try {
const user = yield call(AccountService.addUser, action.user)
let isOk = false
if (user && user.id) {
isOk = true
yield put(AccountAction.addUserSucceeded(user))
try {
const user = yield call(AccountService.fetchLoginInfo)
if (user.id) {
yield put(AccountAction.fetchLoginInfoSucceeded(user))
}
} catch (e) {
yield put(AccountAction.fetchLoginInfoFailed(e.message))
}
yield put(push('/'))
} else {
yield put(showMessage(`注册失败:${user.errMsg}`, MSG_TYPE.ERROR))
yield put(AccountAction.addUserFailed('注册失败'))
}
if (action.onResolved) {
action.onResolved(isOk)
}
} catch (e) {
yield put(AccountAction.addUserFailed(e.message))
}
},
*[AccountAction.login({}, () => {
/** empty */
}).type](action: any) {
try {
const user = yield call(AccountService.login, action.user)
if (user.errMsg) {
throw new Error(user.errMsg)
}
if (user) {
yield put(AccountAction.loginSucceeded(user))
// yield put(AccountAction.fetchLoginInfo()) // 注意:更好的方式是在 rootSaga 中控制跳转,而不是在这里重再次请求。
if (action.onResolved) {
action.onResolved()
}
} else {
yield put(AccountAction.loginFailed(undefined))
}
} catch (e) {
yield put(showMessage(e.message, MSG_TYPE.WARNING))
yield put(AccountAction.loginFailed(e.message))
}
},
*[AccountAction.logout().type]() {
try {
yield call(AccountService.logout)
yield put(AccountAction.logoutSucceeded())
yield put(push('/account/login'))
} catch (e) {
yield put(AccountAction.logoutFailed())
}
},
*[AccountAction.deleteUser({}).type](action: any) {
try {
const count = yield call(AccountService.deleteUser, action.id)
yield put(AccountAction.deleteUserSucceeded(count))
} catch (e) {
yield put(AccountAction.deleteUserFailed(e.message))
}
},
*[AccountAction.fetchUserCount().type](action: any) {
try {
const count = yield call(AccountService.fetchUserCount as any, action)
yield put(AccountAction.fetchUserCountSucceeded(count))
} catch (e) {
yield put(AccountAction.fetchUserCountFailed(e.message))
}
},
*[AccountAction.fetchUserList().type](action: any) {
try {
const users = yield call(AccountService.fetchUserList, action)
yield put(AccountAction.fetchUserListSucceeded(users))
} catch (e) {
yield put(AccountAction.fetchUserListFailed(e.message))
}
},
*[AccountAction.findpwd({}, () => {/** empty */ }).type](action: any) {
try {
const result = yield call(AccountService.findpwd, action.user)
if (result.errMsg) {
throw new Error(result.errMsg)
}
yield put(AccountAction.findpwdSucceeded())
if (action.onResolved) { action.onResolved() }
} catch (e) {
yield put(showMessage(e.message, MSG_TYPE.WARNING))
yield put(AccountAction.findpwdFailed(e.message))
}
},
*[AccountAction.resetpwd({}, () => {/** empty */ }).type](action: any) {
try {
const result = yield call(AccountService.resetpwd, action.user)
if (result.errMsg) {
throw new Error(result.errMsg)
}
yield put(AccountAction.resetpwdSucceeded())
if (action.onResolved) { action.onResolved() }
} catch (e) {
yield put(showMessage(e.message, MSG_TYPE.WARNING))
yield put(AccountAction.resetpwdFailed(e.message))
}
},
*[DO_UPDATE_USER_SETTING](action: DoUpdateUserSettingAction) {
const { key, value, cb } = action.payload
yield put(updateUserSetting(key, value) as AnyAction)
const opAction = yield take(UPDATE_USER_SETTING_SUCCESS)
cb && cb(opAction.payload.isOk)
},
*[AccountAction.DO_UPDATE_ACCOUNT](action: ReturnType<typeof AccountAction.doUpdateAccount>) {
console.log(`saga run`)
yield createCommonDoActionSaga(AccountAction.updateAccount, UPDATE_ACCOUNT_SUCCESS, UPDATE_ACCOUNT_FAILURE)(action)
}
},
listeners: {
'/account': [AccountAction.fetchUserList],
},
}
export default relatives | the_stack |
import { getSolidDataset } from "../resource/solidDataset";
import {
IriString,
WithChangeLog,
Thing,
WithServerResourceInfo,
} from "../interfaces";
import {
getSourceUrl,
internal_defaultFetchOptions,
getResourceInfo,
getSourceIri,
} from "../resource/resource";
import { acl, rdf } from "../constants";
import { Quad } from "@rdfjs/types";
import { DataFactory, subjectToRdfJsQuads } from "../rdfjs.internal";
import {
createThing,
getThingAll,
removeThing,
setThing,
} from "../thing/thing";
import { getIri, getIriAll } from "../thing/get";
import { setIri } from "../thing/set";
import { addIri } from "../thing/add";
import {
Access,
AclDataset,
AclRule,
hasAccessibleAcl,
WithAccessibleAcl,
WithAcl,
WithFallbackAcl,
WithResourceAcl,
} from "./acl";
import { removeAll, removeIri } from "../thing/remove";
import { freeze } from "../rdf.internal";
import { internal_cloneResource } from "../resource/resource.internal";
import { isAcr } from "../acp/acp.internal";
/**
* This (currently internal) function fetches the ACL indicated in the [[WithServerResourceInfo]]
* attached to a resource.
*
* @internal
* @param resourceInfo The Resource info with the ACL URL
* @param options Optional parameter `options.fetch`: An alternative `fetch` function to make the HTTP request, compatible with the browser-native [fetch API](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters).
*/
export async function internal_fetchAcl(
resourceInfo: WithServerResourceInfo,
options: Partial<
typeof internal_defaultFetchOptions
> = internal_defaultFetchOptions
): Promise<WithAcl["internal_acl"]> {
if (!hasAccessibleAcl(resourceInfo)) {
return {
resourceAcl: null,
fallbackAcl: null,
};
}
try {
const resourceAcl = await internal_fetchResourceAcl(resourceInfo, options);
const acl =
resourceAcl === null
? {
resourceAcl: null,
fallbackAcl: await internal_fetchFallbackAcl(resourceInfo, options),
}
: { resourceAcl: resourceAcl, fallbackAcl: null };
return acl;
} catch (e: unknown) {
/* istanbul ignore else: fetchResourceAcl swallows all non-AclIsAcrErrors */
if (e instanceof AclIsAcrError) {
return {
resourceAcl: null,
fallbackAcl: null,
};
}
/* istanbul ignore next: fetchResourceAcl swallows all non-AclIsAcrErrors */
throw e;
}
}
/** @internal */
export async function internal_fetchResourceAcl(
dataset: WithServerResourceInfo,
options: Partial<
typeof internal_defaultFetchOptions
> = internal_defaultFetchOptions
): Promise<AclDataset | null> {
if (!hasAccessibleAcl(dataset)) {
return null;
}
try {
const aclSolidDataset = await getSolidDataset(
dataset.internal_resourceInfo.aclUrl,
options
);
if (isAcr(aclSolidDataset)) {
throw new AclIsAcrError(dataset, aclSolidDataset);
}
return freeze({
...aclSolidDataset,
internal_accessTo: getSourceUrl(dataset),
});
} catch (e) {
if (e instanceof AclIsAcrError) {
throw e;
}
// Since a Solid server adds a `Link` header to an ACL even if that ACL does not exist,
// failure to fetch the ACL is expected to happen - we just return `null` and let callers deal
// with it.
return null;
}
}
/** @internal */
export async function internal_fetchFallbackAcl(
resource: WithAccessibleAcl,
options: Partial<
typeof internal_defaultFetchOptions
> = internal_defaultFetchOptions
): Promise<AclDataset | null> {
const resourceUrl = new URL(getSourceUrl(resource));
const resourcePath = resourceUrl.pathname;
// Note: we're currently assuming that the Origin is the root of the Pod. However, it is not yet
// set in stone that that will always be the case. We might need to check the Container's
// metadata at some point in time to check whether it is actually the root of the Pod.
// See: https://github.com/solid/specification/issues/153#issuecomment-624630022
if (resourcePath === "/") {
// We're already at the root, so there's no Container we can retrieve:
return null;
}
const containerPath = internal_getContainerPath(resourcePath);
const containerIri = new URL(containerPath, resourceUrl.origin).href;
const containerInfo = await getResourceInfo(containerIri, options);
if (!hasAccessibleAcl(containerInfo)) {
// If the current user does not have access to this Container's ACL,
// we cannot determine whether its ACL is the one that applies. Thus, return null:
return null;
}
const containerAcl = await internal_fetchResourceAcl(containerInfo, options);
if (containerAcl === null) {
return internal_fetchFallbackAcl(containerInfo, options);
}
return containerAcl;
}
/**
* Given the path to a Resource, get the URL of the Container one level up in the hierarchy.
* @param resourcePath The path of the Resource of which we need to determine the Container's path.
* @hidden For internal use only.
*/
export function internal_getContainerPath(resourcePath: string): string {
const resourcePathWithoutTrailingSlash =
resourcePath.substring(resourcePath.length - 1) === "/"
? resourcePath.substring(0, resourcePath.length - 1)
: resourcePath;
const containerPath =
resourcePath.substring(
0,
resourcePathWithoutTrailingSlash.lastIndexOf("/")
) + "/";
return containerPath;
}
/** @internal */
export function internal_getAclRules(aclDataset: AclDataset): AclRule[] {
const things = getThingAll(aclDataset);
return things.filter(isAclRule);
}
function isAclRule(thing: Thing): thing is AclRule {
return getIriAll(thing, rdf.type).includes(acl.Authorization);
}
/** @internal */
export function internal_getResourceAclRules(aclRules: AclRule[]): AclRule[] {
return aclRules.filter(isResourceAclRule);
}
function isResourceAclRule(aclRule: AclRule): boolean {
return getIri(aclRule, acl.accessTo) !== null;
}
/** @internal */
export function internal_getResourceAclRulesForResource(
aclRules: AclRule[],
resource: IriString
): AclRule[] {
return aclRules.filter((rule) => appliesToResource(rule, resource));
}
function appliesToResource(aclRule: AclRule, resource: IriString): boolean {
return getIriAll(aclRule, acl.accessTo).includes(resource);
}
/** @internal */
export function internal_getDefaultAclRules(aclRules: AclRule[]): AclRule[] {
return aclRules.filter(isDefaultAclRule);
}
function isDefaultAclRule(aclRule: AclRule): boolean {
return (
getIri(aclRule, acl.default) !== null ||
getIri(aclRule, acl.defaultForNew) !== null
);
}
/** @internal */
export function internal_getDefaultAclRulesForResource(
aclRules: AclRule[],
resource: IriString
): AclRule[] {
return aclRules.filter((rule) => isDefaultForResource(rule, resource));
}
function isDefaultForResource(aclRule: AclRule, resource: IriString): boolean {
return (
getIriAll(aclRule, acl.default).includes(resource) ||
getIriAll(aclRule, acl.defaultForNew).includes(resource)
);
}
/** @internal */
export function internal_getAccess(rule: AclRule): Access {
const ruleAccessModes = getIriAll(rule, acl.mode);
const writeAccess = ruleAccessModes.includes(
internal_accessModeIriStrings.write
);
return writeAccess
? {
read: ruleAccessModes.includes(internal_accessModeIriStrings.read),
append: true,
write: true,
control: ruleAccessModes.includes(
internal_accessModeIriStrings.control
),
}
: {
read: ruleAccessModes.includes(internal_accessModeIriStrings.read),
append: ruleAccessModes.includes(internal_accessModeIriStrings.append),
write: false,
control: ruleAccessModes.includes(
internal_accessModeIriStrings.control
),
};
}
/** @internal */
export function internal_combineAccessModes(modes: Access[]): Access {
return modes.reduce(
(accumulator, current) => {
const writeAccess = accumulator.write || current.write;
return writeAccess
? {
read: accumulator.read || current.read,
append: true,
write: true,
control: accumulator.control || current.control,
}
: {
read: accumulator.read || current.read,
append: accumulator.append || current.append,
write: false,
control: accumulator.control || current.control,
};
},
{ read: false, append: false, write: false, control: false }
);
}
/** @internal */
export function internal_removeEmptyAclRules<Dataset extends AclDataset>(
aclDataset: Dataset
): Dataset {
const aclRules = internal_getAclRules(aclDataset);
const aclRulesToRemove = aclRules.filter(isEmptyAclRule);
// Is this too clever? It iterates over aclRulesToRemove, one by one removing them from aclDataset.
const updatedAclDataset = aclRulesToRemove.reduce(removeThing, aclDataset);
return updatedAclDataset;
}
function isEmptyAclRule(aclRule: AclRule): boolean {
// If there are Quads in there unrelated to Access Control,
// this is not an empty ACL rule that can be deleted:
if (
subjectToRdfJsQuads(
aclRule.predicates,
DataFactory.namedNode(aclRule.url),
DataFactory.defaultGraph()
).some((quad) => !isAclQuad(quad))
) {
return false;
}
// If the rule does not apply to any Resource, it is no longer working:
if (
getIri(aclRule, acl.accessTo) === null &&
getIri(aclRule, acl.default) === null &&
getIri(aclRule, acl.defaultForNew) === null
) {
return true;
}
// If the rule does not specify Access Modes, it is no longer working:
if (getIri(aclRule, acl.mode) === null) {
return true;
}
// If the rule does not specify whom it applies to, it is no longer working:
if (
getIri(aclRule, acl.agent) === null &&
getIri(aclRule, acl.agentGroup) === null &&
getIri(aclRule, acl.agentClass) === null
) {
return true;
}
return false;
}
function isAclQuad(quad: Quad): boolean {
const predicate = quad.predicate;
const object = quad.object;
if (
predicate.equals(DataFactory.namedNode(rdf.type)) &&
object.equals(DataFactory.namedNode(acl.Authorization))
) {
return true;
}
if (
predicate.equals(DataFactory.namedNode(acl.accessTo)) ||
predicate.equals(DataFactory.namedNode(acl.default)) ||
predicate.equals(DataFactory.namedNode(acl.defaultForNew))
) {
return true;
}
if (
predicate.equals(DataFactory.namedNode(acl.mode)) &&
Object.values(internal_accessModeIriStrings).some((mode) =>
object.equals(DataFactory.namedNode(mode))
)
) {
return true;
}
if (
predicate.equals(DataFactory.namedNode(acl.agent)) ||
predicate.equals(DataFactory.namedNode(acl.agentGroup)) ||
predicate.equals(DataFactory.namedNode(acl.agentClass))
) {
return true;
}
if (predicate.equals(DataFactory.namedNode(acl.origin))) {
return true;
}
return false;
}
/**
* IRIs of potential Access Modes
* @internal
*/
export const internal_accessModeIriStrings = {
read: "http://www.w3.org/ns/auth/acl#Read",
append: "http://www.w3.org/ns/auth/acl#Append",
write: "http://www.w3.org/ns/auth/acl#Write",
control: "http://www.w3.org/ns/auth/acl#Control",
} as const;
/** @internal */
type AccessModeIriString =
typeof internal_accessModeIriStrings[keyof typeof internal_accessModeIriStrings];
/** @internal
* This function finds, among a set of ACL rules, the ones granting access to a given entity (the target)
* and identifying it with a specific property (`acl:agent` or `acl:agentGroup`).
* @param aclRules The set of rules to filter
* @param targetIri The IRI of the target
* @param targetType The property linking the rule to the target
*/
export function internal_getAclRulesForIri(
aclRules: AclRule[],
targetIri: IriString,
targetType: typeof acl.agent | typeof acl.agentGroup
): AclRule[] {
return aclRules.filter((rule) =>
getIriAll(rule, targetType).includes(targetIri)
);
}
/** @internal
* This function transforms a given set of rules into a map associating the IRIs
* of the entities to which permissions are granted by these rules, and the permissions
* granted to them. Additionally, it filters these entities based on the predicate
* that refers to them in the rule.
*/
export function internal_getAccessByIri(
aclRules: AclRule[],
targetType: typeof acl.agent | typeof acl.agentGroup
): Record<IriString, Access> {
const targetIriAccess: Record<IriString, Access> = {};
aclRules.forEach((rule) => {
const ruleTargetIri = getIriAll(rule, targetType);
const access = internal_getAccess(rule);
// A rule might apply to multiple agents. If multiple rules apply to the same agent, the Access
// Modes granted by those rules should be combined:
ruleTargetIri.forEach((targetIri) => {
targetIriAccess[targetIri] =
typeof targetIriAccess[targetIri] === "undefined"
? access
: internal_combineAccessModes([targetIriAccess[targetIri], access]);
});
});
return targetIriAccess;
}
/**
* Initialises a new ACL Rule that grants some access - but does not yet specify to whom.
*
* @hidden This is an internal utility function that should not be used directly by downstreams.
* @param access Access mode that this Rule will grant
*/
export function internal_initialiseAclRule(access: Access): AclRule {
let newRule = createThing();
newRule = setIri(newRule, rdf.type, acl.Authorization);
if (access.read) {
newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.read);
}
if (access.append && !access.write) {
newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.append);
}
if (access.write) {
newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.write);
}
if (access.control) {
newRule = addIri(newRule, acl.mode, internal_accessModeIriStrings.control);
}
return newRule;
}
/**
* Creates a new ACL Rule with the same ACL values as the input ACL Rule, but having a different IRI.
*
* Note that non-ACL values will not be copied over.
*
* @hidden This is an internal utility function that should not be used directly by downstreams.
* @param sourceRule ACL rule to duplicate.
*/
export function internal_duplicateAclRule(sourceRule: AclRule): AclRule {
let targetRule = createThing();
targetRule = setIri(targetRule, rdf.type, acl.Authorization);
function copyIris(
inputRule: typeof sourceRule,
outputRule: typeof targetRule,
predicate: IriString
) {
return getIriAll(inputRule, predicate).reduce(
(outputRule, iriTarget) => addIri(outputRule, predicate, iriTarget),
outputRule
);
}
targetRule = copyIris(sourceRule, targetRule, acl.accessTo);
targetRule = copyIris(sourceRule, targetRule, acl.default);
targetRule = copyIris(sourceRule, targetRule, acl.defaultForNew);
targetRule = copyIris(sourceRule, targetRule, acl.agent);
targetRule = copyIris(sourceRule, targetRule, acl.agentGroup);
targetRule = copyIris(sourceRule, targetRule, acl.agentClass);
targetRule = copyIris(sourceRule, targetRule, acl.origin);
targetRule = copyIris(sourceRule, targetRule, acl.mode);
return targetRule;
}
/**
* Attach an ACL dataset to a Resource.
*
* @hidden This is an internal utility function that should not be used directly by downstreams.
* @param resource The Resource to which an ACL is being attached
* @param acl The ACL being attached to the Resource
*/
export function internal_setAcl<ResourceExt extends WithServerResourceInfo>(
resource: ResourceExt,
acl: WithResourceAcl["internal_acl"]
): ResourceExt & WithResourceAcl;
export function internal_setAcl<ResourceExt extends WithServerResourceInfo>(
resource: ResourceExt,
acl: WithFallbackAcl["internal_acl"]
): ResourceExt & WithFallbackAcl;
export function internal_setAcl<ResourceExt extends WithServerResourceInfo>(
resource: ResourceExt,
acl: WithAcl["internal_acl"]
): ResourceExt & WithAcl;
export function internal_setAcl<ResourceExt extends WithServerResourceInfo>(
resource: ResourceExt,
acl: WithAcl["internal_acl"]
): ResourceExt & WithAcl {
return Object.assign(internal_cloneResource(resource), { internal_acl: acl });
}
const supportedActorPredicates = [
acl.agent,
acl.agentClass,
acl.agentGroup,
acl.origin,
];
/**
* Union type of all relations defined in `knownActorRelations`.
*
* When the ACP spec evolves to support additional relations of Rules to Actors,
* adding those relations to `knownActorRelations` will cause TypeScript to warn
* us everywhere to update everywhere the ActorRelation type is used and that
* needs additional work to handle it.
*/
type SupportedActorPredicate = typeof supportedActorPredicates extends Array<
infer E
>
? E
: never;
/**
* Given an ACL Rule, returns two new ACL Rules that cover all the input Rule's use cases,
* except for giving the given Actor access to the given Resource.
*
* @param rule The ACL Rule that should no longer apply for a given Actor to a given Resource.
* @param actor The Actor that should be removed from the Rule for the given Resource.
* @param resourceIri The Resource to which the Rule should no longer apply for the given Actor.
* @returns A tuple with the original ACL Rule without the given Actor, and a new ACL Rule for the given Actor for the remaining Resources, respectively.
*/
function internal_removeActorFromRule(
rule: AclRule,
actor: IriString,
actorPredicate: SupportedActorPredicate,
resourceIri: IriString,
ruleType: "resource" | "default"
): [AclRule, AclRule] {
// If the existing Rule does not apply to the given Actor, we don't need to split up.
// Without this check, we'd be creating a new rule for the given Actor (ruleForOtherTargets)
// that would give it access it does not currently have:
if (!getIriAll(rule, actorPredicate).includes(actor)) {
const emptyRule = internal_initialiseAclRule({
read: false,
append: false,
write: false,
control: false,
});
return [rule, emptyRule];
}
// The existing rule will keep applying to Actors other than the given one:
const ruleWithoutActor = removeIri(rule, actorPredicate, actor);
// The actor might have been given other access in the existing rule, so duplicate it...
let ruleForOtherTargets = internal_duplicateAclRule(rule);
// ...but remove access to the original Resource...
ruleForOtherTargets = removeIri(
ruleForOtherTargets,
ruleType === "resource" ? acl.accessTo : acl.default,
resourceIri
);
// Prevents the legacy predicate 'acl:defaultForNew' to lead to privilege escalation
if (ruleType === "default") {
ruleForOtherTargets = removeIri(
ruleForOtherTargets,
acl.defaultForNew,
resourceIri
);
}
// ...and only apply the new Rule to the given Actor (because the existing Rule covers the others):
ruleForOtherTargets = setIri(ruleForOtherTargets, actorPredicate, actor);
supportedActorPredicates
.filter((predicate) => predicate !== actorPredicate)
.forEach((predicate) => {
ruleForOtherTargets = removeAll(ruleForOtherTargets, predicate);
});
return [ruleWithoutActor, ruleForOtherTargets];
}
/**
* ```{note}
* This function is still experimental and subject to change, even in a non-major release.
* ```
* Modifies the resource ACL (Access Control List) to set the Access Modes for the given Agent.
* Specifically, the function returns a new resource ACL initialised with the given ACL and
* new rules for the Actor's access.
*
* If rules for Actor's access already exist in the given ACL, in the returned ACL,
* they are replaced by the new rules.
*
* This function does not modify:
*
* - Access Modes granted indirectly to Actors through other ACL rules, e.g., public or group-specific permissions.
* - Access Modes granted to Actors for the child Resources if the associated Resource is a Container.
* - The original ACL.
*
* @param aclDataset The SolidDataset that contains Access-Control List rules.
* @param actor The Actor to grant specific Access Modes.
* @param access The Access Modes to grant to the Actor for the Resource.
* @returns A new resource ACL initialised with the given `aclDataset` and `access` for the `agent`.
*/
export function internal_setActorAccess(
aclDataset: AclDataset,
access: Access,
actorPredicate: SupportedActorPredicate,
accessType: "default" | "resource",
actor: IriString
): AclDataset & WithChangeLog {
// First make sure that none of the pre-existing rules in the given ACL SolidDataset
// give the Agent access to the Resource:
let filteredAcl = aclDataset;
getThingAll(aclDataset).forEach((aclRule) => {
// Obtain both the Rule that no longer includes the given Actor,
// and a new Rule that includes all ACL Quads
// that do not pertain to the given Actor-Resource combination.
// Note that usually, the latter will no longer include any meaningful statements;
// we'll clean them up afterwards.
const [filteredRule, remainingRule] = internal_removeActorFromRule(
aclRule,
actor,
actorPredicate,
aclDataset.internal_accessTo,
accessType
);
filteredAcl = setThing(filteredAcl, filteredRule);
filteredAcl = setThing(filteredAcl, remainingRule);
});
// Create a new Rule that only grants the given Actor the given Access Modes:
let newRule = internal_initialiseAclRule(access);
newRule = setIri(
newRule,
accessType === "resource" ? acl.accessTo : acl.default,
aclDataset.internal_accessTo
);
newRule = setIri(newRule, actorPredicate, actor);
const updatedAcl = setThing(filteredAcl, newRule);
// Remove any remaining Rules that do not contain any meaningful statements:
return internal_removeEmptyAclRules(updatedAcl);
}
export function internal_setResourceAcl<
T extends WithServerResourceInfo & WithAcl
>(resource: T, acl: AclDataset): T & WithResourceAcl {
const newAcl: WithResourceAcl["internal_acl"] = {
resourceAcl: acl,
fallbackAcl: null,
};
return internal_setAcl(resource, newAcl);
}
export function internal_getResourceAcl(
resource: WithServerResourceInfo & WithResourceAcl
): AclDataset {
return resource.internal_acl.resourceAcl;
}
/**
* This error indicates that, if we're following a Link with rel="acl",
* it does not result in a WAC ACL, but in an ACP ACR.
*/
class AclIsAcrError extends Error {
constructor(
sourceResource: WithServerResourceInfo,
aclResource: WithServerResourceInfo
) {
super(
`[${getSourceIri(
sourceResource
)}] is governed by Access Control Policies in [${getSourceIri(
aclResource
)}] rather than by Web Access Control.`
);
}
} | the_stack |
import * as UE from 'ue';
import {$ref, $unref, $set, argv} from 'puerts';
import * as assert from './MyAssert';
import './mocha';
/*
* 测试示例
*/
describe('Test Array', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function () {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
});
/*
* 测试path模块,在mocha中使用
*/
let Path = require('path');
describe('Path Module', function() {
it('path.resolve should be a function', function() {
assert.equal(typeof Path.resolve, typeof function(){});
});
});
describe('Path Module', function() {
it('path.resolve(\'Hello.js\') should be \'./Hello.js\'', function() {
assert.equal(Path.resolve('Hello.js'), './Hello.js');
});
});
/*
* 测试Base.ts的内容
*/
let obj = new UE.MainObject();
//成员访问
describe('Access Object Member: obj.MyString', function() {
it('before set, should be empty/undefined', function() {
assert.equal(obj.MyString, '');
});
it('after set, should be \'PPPPP\'', function() {
obj.MyString = "PPPPP";
assert.equal(obj.MyString, "PPPPP");
});
});
//简单类型参数函数
describe('Function with POD Type Parameters: obj.Add()', function() {
it('obj.Add(100, 300) should return 400', function() {
assert.equal(obj.Add(100, 300), 400);
});
});
//复杂类型参数函数
describe('Function with Non-POD Type Parameters: obj.Bar()', function() {
it('obj.Bar(new UE.Vector(1, 2, 3) should return \'UMyObject::Bar(X=1.000 Y=2.000 Z=3.000)\'', function() {
assert.equal(obj.Bar(new UE.Vector(1, 2, 3)), 'UMyObject::Bar(X=1.000 Y=2.000 Z=3.000)');
});
});
//引用类型参数函数
describe('Function with Reference Type Parameters: $ref()', function() {
let vectorRef = $ref(new UE.Vector(1, 2, 3));
it('obj.Bar2($ref(new UE.Vector(1, 2, 3))) should return \'UMyObject::Bar2(X=1.000 Y=2.000 Z=3.000)\'', function() {
assert.equal(obj.Bar2(vectorRef), 'UMyObject::Bar2(X=1.000 Y=2.000 Z=3.000)');
});
it('The X value of the argument passed to obj.Bar2() should be modified to 1024.000', function() {
assert.equal(obj.Bar($unref(vectorRef)), 'UMyObject::Bar(X=1024.000 Y=2.000 Z=3.000)');
});
});
//静态方法
describe('Calling BlueprintCallable Static Methods', function() {
let str1 = UE.JSBlueprintFunctionLibrary.GetName();
it('UE.JSBlueprintFunctionLibrary.GetName() should return \'小马哥\'', function() {
assert.equal(str1, '小马哥');
});
it('UE.JSBlueprintFunctionLibrary.Hello(str2) should return \'Hello , 小马哥\'', function() {
let str2 = UE.JSBlueprintFunctionLibrary.Concat(', ', str1);
assert.equal(UE.JSBlueprintFunctionLibrary.Hello(str2), 'Hello , 小马哥');
});
});
//扩展方法,和C#的扩展方法类似
describe('Calling Extension Methods', function() {
let v = new UE.Vector(3, 2, 1);
it('v.ToString() should return \'X=3.000 Y=2.000 Z=1.000\'', function() {
assert.equal(v.ToString(), 'X=3.000 Y=2.000 Z=1.000');
});
it('After calling v.Set(8, 88, 888), v.ToString() should return \'X=8.000 Y=88.000 Z=888.000\'', function() {
v.Set(8, 88, 888);
assert.equal(v.ToString(), 'X=8.000 Y=88.000 Z=888.000');
});
});
//枚举
describe('Test UEnum', function() {
it('UE.EToTest.V1 should be 1', function() {
assert.equal(UE.EToTest.V1, 1);
});
it('UE.EToTest.V13 should be 13', function() {
assert.equal(UE.EToTest.V13, 13);
})
});
//定长数组
describe('Test Fix Size Array', function() {
it('Size of obj.MyFixSizeArray should be 100', function() {
assert.equal(obj.MyFixSizeArray.Num(), 100);
});
it('MyFixSizeArray[i] should be 99-i', function() {
assert.equal(obj.MyFixSizeArray.Get(32), 99-32);
assert.equal(obj.MyFixSizeArray.Get(33), 99-33);
assert.equal(obj.MyFixSizeArray.Get(34), 99-34);
});
it('MyFixSizeArray.Set(33, 1000) should make [33] be 1000', function() {
obj.MyFixSizeArray.Set(33, 1000)
assert.equal(obj.MyFixSizeArray.Get(32), 99-32);
assert.equal(obj.MyFixSizeArray.Get(33), 1000);
assert.equal(obj.MyFixSizeArray.Get(34), 99-34);
});
});
//TArray
describe('Test TArray', function() {
it('Size of obj.MyArray should be 2: [0]:1024, [1]:777', function() {
assert.equal(obj.MyArray.Num(), 2);
assert.equal(obj.MyArray.Get(0), 1024);
assert.equal(obj.MyArray.Get(1), 777);
});
it('After adding an element, size of obj.MyArray should be 3: [0]:1024, [1]:777, [2]:888', function() {
obj.MyArray.Add(888);
assert.equal(obj.MyArray.Num(), 3);
assert.equal(obj.MyArray.Get(0), 1024);
assert.equal(obj.MyArray.Get(1), 777);
assert.equal(obj.MyArray.Get(2), 888);
});
it('After set [0] to 7, content of obj.MyArray should be: [0]:7, [1]:777, [2]:888', function() {
obj.MyArray.Set(0, 7);
assert.equal(obj.MyArray.Get(0), 7);
assert.equal(obj.MyArray.Get(1), 777);
assert.equal(obj.MyArray.Get(2), 888);
});
});
//TSet
describe('Test TSet', function() {
it('Size of obj.MySet should be 2: {\"Hello\", \"John\"}', function() {
assert.equal(obj.MySet.Num(), 2);
assert.equal(obj.MySet.Contains("John"), true);
assert.equal(obj.MySet.Contains("Hello"), true);
assert.notEqual(obj.MySet.Contains("Che"), true);
});
});
//TMap
describe('Test TMap', function() {
it('Size of obj.MyMap should be 2: {{\"John\", 1}, {\"Hello\", 2}}', function() {
assert.equal(obj.MyMap.Num(), 2);
assert.equal(obj.MyMap.Get("John"), 1);
assert.equal(obj.MyMap.Get("Hello"), 2);
assert.equal(obj.MyMap.Get("Che"), undefined);
});
it('After adding {\"Che\", 10}, content of obj.MyMap should be: {{\"John\", 1}, {\"Hello\", 2}, {\"Che\", 10}}', function() {
obj.MyMap.Add("Che", 10)
assert.equal(obj.MyMap.Num(), 3);
assert.equal(obj.MyMap.Get("John"), 1);
assert.equal(obj.MyMap.Get("Hello"), 2);
assert.equal(obj.MyMap.Get("Che"), 10);
});
});
let world = (argv.getByName("GameInstance") as UE.GameInstance).GetWorld();
let actor = world.SpawnActor(UE.MainActor.StaticClass(), undefined, UE.ESpawnActorCollisionHandlingMethod.Undefined, undefined, undefined) as UE.MainActor;
//引擎方法
describe('Calling Engine Methods', function() {
it('actor.GetName should be \'MainActor_0\'', function() {
assert.equal(actor.GetName(), 'MainActor_0');
});
it('actor.K2_GetActorLocation().ToString() should be \'X=0.000 Y=0.000 Z=0.000\'', function() {
assert.equal(actor.K2_GetActorLocation().ToString(), 'X=0.000 Y=0.000 Z=0.000');
});
});
//Delegate
describe('Test Delegate', function() {
it('Test Multicast, Add and Broadcast', function() {
let multicastResult1: string;
let multicastResult2: string;
function MutiCast1(i) {
multicastResult1 = 'MutiCast1<<<' + i;
}
function MutiCast2(i) {
multicastResult2 = 'MutiCast2>>>' + i;
actor.NotifyWithInt.Remove(MutiCast2);//调用一次后就停掉
}
actor.NotifyWithInt.Add(MutiCast1);
actor.NotifyWithInt.Add(MutiCast2);
actor.NotifyWithInt.Broadcast(888999);
assert.equal(multicastResult1, 'MutiCast1<<<888999');
assert.equal(multicastResult2, 'MutiCast2>>>888999');
});
it('If the delegate is not bound, IsBound() should return false', function() {
assert.equal(actor.NotifyWithString.IsBound(), false);
assert.equal(actor.NotifyWithRefString.IsBound(), false);
});
let outerStrRef: string;
it('If the delegate is bound, IsBound() should return true', function() {
actor.NotifyWithRefString.Bind((strRef) => {
outerStrRef = $unref(strRef);
$set(strRef, 'out to NotifyWithRefString');//引用参数输出
});
assert.equal(actor.NotifyWithString.IsBound(), false);
assert.equal(actor.NotifyWithRefString.IsBound(), true);
});
it('Executing NotifyWithRefString delegate', function() {
let strRef = $ref('666');
actor.NotifyWithRefString.Execute(strRef);
assert.equal(outerStrRef, '666');
assert.equal($unref(strRef), 'out to NotifyWithRefString');
});
it('Executing a delegate with return value', function() {
actor.NotifyWithStringRet.Bind((inStr) => {
return "////" + inStr;
});
let retStr = actor.NotifyWithStringRet.Execute('console.log("hello world")');
assert.equal(retStr, '////console.log("hello world")');
});
});
/*
* 测试容器的接口,元素类型涵盖PropertyTranslator支持的所有类型、边界、组合
*/
let testObj = new UE.ContainersTest();
describe('Test TArray<int32>', function() {
/* 先保证基本功能正确 */
it('Num', function() {
assert.equal(testObj.Int32Array.Num(), 0, 'Num of an empty array should be 0');
assert.equal(testObj.Int32ArrayWithInit.Num(), 3, 'Num of an array with 3 initialized elements should be 3');
});
it('IsValidIndex', function() {
assert.equal(testObj.Int32Array.IsValidIndex(0), false, '0 is not a valid index of an empty array');
assert.equal(testObj.Int32ArrayWithInit.IsValidIndex(0), true);
assert.equal(testObj.Int32ArrayWithInit.IsValidIndex(1), true);
assert.equal(testObj.Int32ArrayWithInit.IsValidIndex(2), true);
assert.equal(testObj.Int32ArrayWithInit.IsValidIndex(3), false);
});
it('Empty', function() {
testObj.Int32ArrayWithInit.Empty();
assert.equal(testObj.Int32ArrayWithInit.Num(), 0, 'After emptying an array, the num of the array should be 0');
});
it('Add', function() {
const ADD_NUM = 10;
for (let i = 0; i < ADD_NUM; ++i) {
testObj.Int32Array.Add(i);
}
assert.equal(testObj.Int32Array.Num(), ADD_NUM, 'After adding ADD_NUM elements to an empty array, the num of the array should be ADD_NUM');
});
it('Get', function() {
for (let i = 0; i < testObj.Int32Array.Num(); ++i) {
testObj.Int32Array.IsValidIndex(i);
assert.equal(testObj.Int32Array.Get(i), i, 'Adding value i at index i');
}
// 如果Get索引越界,抛异常
// TODO - assert提供“接收异常”的语义
// testObj.Int32Array.Get(testObj.Int32Array.Num());
});
it('Set', function() {
for (let i = 0; i < testObj.Int32Array.Num(); ++i) {
testObj.Int32Array.Set(i, 2 * i);
assert.equal(testObj.Int32Array.Get(i), 2 * i, 'Setting value of the element at index i to 2*i');
}
let ele_num = testObj.Int32Array.Num();
// 如果Set索引越界,抛异常
// TODO - assert提供“接收异常”的语义
// testObj.Int32Array.Set(ele_num, ele_num);
});
it('Contains', function() {
let ele_num = testObj.Int32Array.Num();
for (let i = 0; i < ele_num; ++i) {
assert.equal(testObj.Int32Array.Contains(2 * i), true);
}
assert.equal(testObj.Int32Array.Contains(2 * ele_num), false);
});
it('FindIndex', function() {
let ele_num = testObj.Int32Array.Num();
for (let i = 0; i < ele_num; ++i) {
assert.equal(testObj.Int32Array.FindIndex(2 * i), i);
}
assert.equal(testObj.Int32Array.FindIndex(2 * ele_num), -1, 'Finding the index of an element that does not exist should return -1');
});
it('RemoveAt', function() {
let ele_num = testObj.Int32Array.Num();
// 删除前ele_num/2个元素
for (let i = 0; i < ele_num / 2; ++i) {
testObj.Int32Array.RemoveAt(0);
}
assert.equal(testObj.Int32Array.Num(), ele_num - ele_num/2, 'After removing front ele_num/2 elements, the num of elements should be (ele_num - ele_num/2)');
// 检查IsValidIndex
let rest_num = ele_num - ele_num/2;
assert.equal(rest_num, testObj.Int32Array.Num());
for (let i = 0; i < ele_num; ++i) {
if (i < rest_num) {
assert.equal(testObj.Int32Array.IsValidIndex(i), true)
}
else {
assert.equal(testObj.Int32Array.IsValidIndex(i), false, 'RemoveAt() should shrink the array');
}
}
// 原本数组后一半的元素前移
for (let i = 0; i < testObj.Int32Array.Num(); ++i) {
assert.equal(testObj.Int32Array.Get(i), 2*(i + ele_num/2));
}
// 如果RemoveAt索引越界,抛异常
});
/* 临界值 */
it('Empty the array', function() {
testObj.Int32Array.Empty();
assert.equal(testObj.Int32Array.Num(), 0);
});
it('Add boundary values to the int32 array', function() {
// TArray<int32>无法呈现MAX_SAFE_INTEGER(64-bits)
testObj.Int32Array.Add(Number.MAX_SAFE_INTEGER); // 不安全地型转为其他值
assert.equal(testObj.Int32Array.IsValidIndex(0), true); // TODO - 调用Contains会先把参数不安全地型转为其他值,然后再在容器内寻找。这样一来尽管保存的不是真正的MAX_SAFE_INTEGER,Contains却会返回true
// assert.equal(testObj.Int32Array.Contains(Number.MAX_SAFE_INTEGER), false, 'TArray<int32> should not be able to represent Number.MAX_SAFE_INTEGER');
assert.notEqual(testObj.Int32Array.Get(0), Number.MAX_SAFE_INTEGER, 'The value of element in the TArray<int32> that was assigned as MAX_SAFE_INTEGER should not be MAX_SAFE_INTEGER');
assert.equal(testObj.Int32Array.Get(0), -1, 'The value of a int32 variable that was assigned MAX_SAFE_INTEGER(2^53-1) should be -1');
// TArray<int32>无法呈现MIN_SAFE_INTEGER(64-bits)
testObj.Int32Array.Add(Number.MIN_SAFE_INTEGER);
assert.equal(testObj.Int32Array.IsValidIndex(1), true);
assert.notEqual(testObj.Int32Array.Get(1), Number.MIN_SAFE_INTEGER, 'The value of element in the TArray<int32> that was assigned as MIN_SAFE_INTEGER should not be MIN_SAFE_INTEGER');
assert.equal(testObj.Int32Array.Get(1), 1, 'The value of a int32 variable that was assigned MIN_SAFE_INTEGER(-1*(2^53-1)) should be 1');
// 最大为2^31-1
const MAX_INT32 = Math.pow(2, 31) - 1;
testObj.Int32Array.Add(MAX_INT32);
assert.equal(testObj.Int32Array.IsValidIndex(2), true);
assert.equal(testObj.Int32Array.Get(2), MAX_INT32, 'TArray<int32> should be able to represent MAX_INT32');
// 最小为-1*2^31
const MIN_INT32 = Math.pow(2, 31) * -1;
testObj.Int32Array.Add(MIN_INT32);
assert.equal(testObj.Int32Array.IsValidIndex(3), true);
assert.equal(testObj.Int32Array.Get(3), MIN_INT32, 'TArray<int32> should be able to represent MIN_INT32');
// 溢出测试,MAX_INT32 + 1 == MIN_INT32
testObj.Int32Array.Add(MAX_INT32 + 1);
assert.equal(testObj.Int32Array.IsValidIndex(4), true);
assert.notEqual(testObj.Int32Array.Get(4), MAX_INT32 + 1, 'The value of element in the TArray<int32> that was assigned as (MAX_INT32+1) should not be (MAX_INT32+1)');
assert.equal(testObj.Int32Array.Get(4), MIN_INT32, '(MAX_INT32+1) should be MIN_INT32');
// 溢出测试,MIN_INT32 - 1 == MAX_INT32
testObj.Int32Array.Add(MIN_INT32 - 1);
assert.equal(testObj.Int32Array.IsValidIndex(5), true);
assert.notEqual(testObj.Int32Array.Get(5), MIN_INT32 - 1, 'The value of element in the TArray<int32> that was assigned as (MIN_INT32-1) should not be (MIN_INT32-1)');
assert.equal(testObj.Int32Array.Get(5), MAX_INT32, '(MIN_INT32-1) should be MAX_INT32');
});
});
describe('Test TArray<uint32>', function () {
/* 临界值 */
it('Empty the array', function () {
testObj.UInt32Array.Empty();
assert.equal(testObj.UInt32Array.Num(), 0);
});
it('Add boundary values to the uint32 array', function () {
// uint32无法呈现MAX_SAFE_INTEGER
testObj.UInt32Array.Add(Number.MAX_SAFE_INTEGER);
assert.equal(testObj.UInt32Array.IsValidIndex(0), true);
assert.notEqual(testObj.UInt32Array.Get(0), Number.MAX_SAFE_INTEGER, 'TArray<uint32> cannot represent MAX_SAFE_INTEGER');
// uint32无法呈现MIN_SAFE_INTEGER
testObj.UInt32Array.Add(Number.MIN_SAFE_INTEGER);
assert.equal(testObj.UInt32Array.IsValidIndex(1), true);
assert.notEqual(testObj.UInt32Array.Get(1), Number.MIN_SAFE_INTEGER, 'TArray<uint32> cannot represent MIN_SAFE_INTEGER');
// uint32的合法数值范围0~(2^32-1),最大值
const MAX_UINT32 = Math.pow(2, 32) - 1;
testObj.UInt32Array.Add(MAX_UINT32);
assert.equal(testObj.UInt32Array.IsValidIndex(2), true);
assert.equal(testObj.UInt32Array.Get(2), MAX_UINT32, 'TArray<uint32> should be able to represent MAX_UINT32');
// uint32最小值
const MIN_UINT32 = 0;
testObj.UInt32Array.Add(0);
assert.equal(testObj.UInt32Array.IsValidIndex(3), true);
assert.equal(testObj.UInt32Array.Get(3), MIN_UINT32, 'TArray<uint32> should be able to represent MIN_UINT32');
// 溢出测试,MAX_UINT32 + 1 == MIN_UINT32
testObj.UInt32Array.Add(MAX_UINT32 + 1);
assert.equal(testObj.UInt32Array.IsValidIndex(4), true);
assert.equal(testObj.UInt32Array.Get(4), MIN_UINT32, '(MAX_UINT32+1) should be MIN_UINT32');
// 溢出测试,MIN_UINT32 - 1 == MAX_UINT32
testObj.UInt32Array.Add(MIN_UINT32 - 1);
assert.equal(testObj.UInt32Array.IsValidIndex(5), true);
assert.equal(testObj.UInt32Array.Get(5), MAX_UINT32, '(MIN_UINT32-1) should be MAX_UINT32');
});
/* 非临界值 */
});
describe('Test TArray<int64>', function() {
/* 临界值 */
it('Empty the array', function () {
testObj.Int64Array.Empty();
assert.equal(testObj.Int64Array.Num(), 0);
});
it('Add boundary values to the int64 array', function () {
// TODO - 当用例错误,且包含bigint时,mocha内的JSON.stringify报错:'Do not know how to serialize a BigInt'
// int64能呈现MAX_SAFE_INTEGER
const MAX_SAFE_INTEGER = BigInt(Number.MAX_SAFE_INTEGER);
testObj.Int64Array.Add(MAX_SAFE_INTEGER);
assert.equal(testObj.Int64Array.IsValidIndex(0), true);
assert.equal(testObj.Int64Array.Get(0), MAX_SAFE_INTEGER, 'TArray<int64> should be able to represent MAX_SAFE_INTEGER');
// int64能呈现MIN_SAFE_INTEGER
const MIN_SAFE_INTEGER = BigInt(Number.MIN_SAFE_INTEGER);
testObj.Int64Array.Add(MIN_SAFE_INTEGER);
assert.equal(testObj.Int64Array.IsValidIndex(1), true);
assert.equal(testObj.Int64Array.Get(1), MIN_SAFE_INTEGER, 'TArray<int64> should be able to represent MIN_SAFE_INTEGER');
// int64能呈现MAX_INT64
const MAX_INT64 = BigInt("0x7FFFFFFFFFFFFFFF");
testObj.Int64Array.Add(MAX_INT64);
assert.equal(testObj.Int64Array.IsValidIndex(2), true);
assert.equal(testObj.Int64Array.Get(2), MAX_INT64, 'TArray<int64> should be able to represent MAX_INT64');
// int64能呈现MIN_INT64
const MIN_INT64 = -1n * MAX_INT64 - 1n;
testObj.Int64Array.Add(MIN_INT64);
assert.equal(testObj.Int64Array.IsValidIndex(3), true);
assert.equal(testObj.Int64Array.Get(3), MIN_INT64, 'TArray<int64> should be able to represent MIN_INT64');
// 溢出测试,MAX_INT64 + 1 == MIN_INT64
testObj.Int64Array.Add(MAX_INT64 + 1n);
assert.equal(testObj.Int64Array.IsValidIndex(4), true);
assert.equal(testObj.Int64Array.Get(4), MIN_INT64, '(MAX_INT64+1n) should be MIN_INT64');
// 溢出测试,MIN_INT64 - 1 == MAX_INT64
testObj.Int64Array.Add(MIN_INT64 - 1n);
assert.equal(testObj.Int64Array.IsValidIndex(5), true);
assert.equal(testObj.Int64Array.Get(5), MAX_INT64, '(MIN_INT64-1n) should be MAX_INT64');
});
/* 非临界值 */
});
describe('Test TArray<uint64>', function() {
it('Add boundary values to the uint64 array', function() {
testObj.UInt64Array.Empty();
assert.equal(testObj.UInt64Array.Num(), 0);
// uint64能呈现MAX_SAFE_INTEGER
const MAX_SAFE_INTEGER = BigInt(Number.MAX_SAFE_INTEGER);
testObj.UInt64Array.Add(MAX_SAFE_INTEGER);
assert.equal(testObj.UInt64Array.IsValidIndex(0), true);
assert.equal(testObj.UInt64Array.Get(0), MAX_SAFE_INTEGER, 'TArray<uint64> should be able to represent MAX_SAFE_INTEGER');
// uint64无法呈现MIN_SAFE_INTEGER(因为是负数)
const MIN_SAFE_INTEGER = BigInt(Number.MIN_SAFE_INTEGER);
testObj.UInt64Array.Add(MIN_SAFE_INTEGER);
assert.equal(testObj.UInt64Array.IsValidIndex(1), true);
assert.notEqual(testObj.UInt64Array.Get(1), MIN_SAFE_INTEGER, 'TArray<uint64> cannot represent MIN_SAFE_INTEGER');
// uint64的最大值MAX_UINT64
const MAX_UINT64 = BigInt("0xFFFFFFFFFFFFFFFF");
testObj.UInt64Array.Add(MAX_UINT64);
assert.equal(testObj.UInt64Array.IsValidIndex(2), true);
assert.equal(testObj.UInt64Array.Get(2), MAX_UINT64, 'TArray<uint64> should be able to represent MAX_UINT64');
// uint64的最小值MIN_UINT64
const MIN_UINT64 = 0n;
testObj.UInt64Array.Add(MIN_UINT64);
assert.equal(testObj.UInt64Array.IsValidIndex(3), true);
assert.equal(testObj.UInt64Array.Get(3), MIN_UINT64, 'TArray<uint64> should be able to represent MIN_UINT64');
// 溢出测试,MAX_UINT64 + 1 == MIN_UINT64
testObj.UInt64Array.Add(MAX_UINT64 + 1n);
assert.equal(testObj.UInt64Array.IsValidIndex(4), true);
assert.equal(testObj.UInt64Array.Get(4), MIN_UINT64, '(MAX_UINT64+1n) should be MIN_UINT64');
// 溢出测试,MIN_UINT64 - 1 == MAX_UINT64
testObj.UInt64Array.Add(MIN_UINT64 - 1n);
assert.equal(testObj.UInt64Array.IsValidIndex(5), true);
assert.equal(testObj.UInt64Array.Get(5), MAX_UINT64, '(MIN_INT64-1n) should be MAX_INT64');
});
});
describe('Test TArray<float>', function() {
it('Add boundary values to the float array', function() {
testObj.FloatArray.Empty();
assert.equal(testObj.FloatArray.Num(), 0);
// float无法呈现MAX_VALUE
const MAX_VALUE = Number.MAX_VALUE;
testObj.FloatArray.Add(MAX_VALUE);
assert.equal(testObj.FloatArray.IsValidIndex(0), true);
assert.notEqual(testObj.FloatArray.Get(0), MAX_VALUE, 'TArray<float> cannot represent MAX_VALUE');
// float无法呈现MIN_VALUE(注:此处使用的并不是Number.MIN_VALUE,Number.MIN_VALUE是Number能表示的最小正值,而非最小值)
const MIN_VALUE = -MAX_VALUE;
testObj.FloatArray.Add(MIN_VALUE);
assert.equal(testObj.FloatArray.IsValidIndex(1), true);
assert.notEqual(testObj.FloatArray.Get(1), MIN_VALUE, 'TArray<float> cannot represent MIN_VALUE');
// float的最大值MAX_FLOAT
const MAX_FLOAT = 3.402823466e+38;
testObj.FloatArray.Add(MAX_FLOAT);
assert.equal(testObj.FloatArray.IsValidIndex(2), true);
// TODO - 从FloatArray取出值[2],精度变大:3.4028234663852886e+38,不等于原来的MAX_FLOAT。误差小于0.000000001e+38
// assert.equal(testObj.FloatArray.Get(2), MAX_FLOAT, 'TArray<float> should be able to represent MAX_FLOAT');
assert.ok(Math.abs(testObj.FloatArray.Get(2) - MAX_FLOAT) < 0.000000001e+38, 'Math.abs(testObj.FloatArray.Get(2) - MAX_FLOAT) should less than 0.000000001e+38');
// MAX_FLOAT加上一个较小的数值后溢出(阶码相同,尾数取能产生进位的最小值。查看浮点数二进制:https://www.h-schmidt.net/FloatConverter/IEEE754.html)
testObj.FloatArray.Add(MAX_FLOAT + 0.0000002e+38);
assert.equal(testObj.FloatArray.IsValidIndex(3), true);
assert.equal(testObj.FloatArray.Get(3), Infinity, 'MAX_FLOAT + 0.000000002e+38 should overflow');
// MAX_FLOAT+MAX_FLOAT对float而言是Infinity,对ECMAScript Number而言则不是
testObj.FloatArray.Add(MAX_FLOAT + MAX_FLOAT);
assert.equal(testObj.FloatArray.IsValidIndex(4), true);
assert.equal(testObj.FloatArray.Get(4), Infinity, 'MAX_FLOAT + MAX_FLOAT should be Infinity for float number');
assert.notEqual(MAX_FLOAT + MAX_FLOAT, Infinity, 'MAX_FLOAT + MAX_FLOAT should not be Infinity for double number(ECMAScript Number)');
// float的最小值MIN_FLOAT
const MIN_FLOAT = -3.402823466e+38;
testObj.FloatArray.Add(MIN_FLOAT);
assert.equal(testObj.FloatArray.IsValidIndex(5), true);
// 从FloatArray取出值[5],精度变大:-3.4028234663852886e+38,不等于原来的MIN_FLOAT
// assert.equal(testObj.FloatArray.Get(5), MIN_FLOAT, 'TArray<float> should be able to represent MIN_FLOAT');
assert.ok(Math.abs(testObj.FloatArray.Get(5) - MIN_FLOAT) < 0.000000001e+38, 'Math.abs(testObj.FloatArray.Get(5) - MIN_FLOAT) should less than 0.000000001e+38');
// MIN_FLOAT减去一个较小的数值后溢出
testObj.FloatArray.Add(MIN_FLOAT - 0.0000002e+38);
assert.equal(testObj.FloatArray.IsValidIndex(6), true);
assert.equal(testObj.FloatArray.Get(6), -Infinity, 'MIN_FLOAT - 0.0000002e+38 should overflow');
// MIN_FLOAT+MIN_FLOAT对float而言是-Infinity,对ECMAScript Number而言则不是
testObj.FloatArray.Add(MIN_FLOAT + MIN_FLOAT);
assert.equal(testObj.FloatArray.IsValidIndex(7), true);
assert.equal(testObj.FloatArray.Get(7), -Infinity, 'MIN_FLOAT + MIN_FLOAT should be -Infinity for float number');
assert.notEqual(MIN_FLOAT + MIN_FLOAT, -Infinity, 'MIN_FLOAT + MIN_FLOAT should not be Infinity for double number(ECMAScript Number)');
});
});
describe('Test TArray<double>', function() {
it('Add boundary values to the double array', function() {
testObj.DoubleArray.Empty();
assert.equal(testObj.DoubleArray.Num(), 0);
// double能呈现MAX_VALUE(1.7976931348623157e+308,双精度浮点数最大值)
const MAX_VALUE = Number.MAX_VALUE;
testObj.DoubleArray.Add(MAX_VALUE);
assert.equal(testObj.DoubleArray.IsValidIndex(0), true);
assert.equal(testObj.DoubleArray.Get(0), MAX_VALUE, 'TArray<double> should be able represent MAX_VALUE');
// MAX_VALUE加一个较小的数值后得到Infinity
const MAX_VALUE_CONST = 1.7976931348623157e+308;
assert.equal(MAX_VALUE_CONST, MAX_VALUE);
assert.equal(MAX_VALUE_CONST + 0.0000000000000001e+308, Number.POSITIVE_INFINITY, 'MAX_VALUE_CONST should be the biggest valid double number');
// double能呈现MIN_VALUE(注:此处使用的并不是Number.MIN_VALUE,Number.MIN_VALUE是Number能表示的最小正值,而非最小值)
const MIN_VALUE = -1 * MAX_VALUE;
testObj.DoubleArray.Add(MIN_VALUE);
assert.equal(testObj.DoubleArray.IsValidIndex(1), true);
assert.equal(testObj.DoubleArray.Get(1), MIN_VALUE, 'TArray<double> should be able represent MIN_VALUE');
// MIN_VALUE减去一个较小的数值后得到-Infinity
const MIN_VALUE_CONST = -1.7976931348623157e+308;
assert.equal(MIN_VALUE_CONST, MIN_VALUE);
assert.equal(MIN_VALUE_CONST - 0.0000000000000001e+308, Number.NEGATIVE_INFINITY, 'MIN_VALUE_CONST should be the smallest valid double number');
});
});
describe('Test TArray<bool>', function() {
it('Add values to bool array', function() {
testObj.BoolArray.Empty();
assert.equal(testObj.BoolArray.Num(), 0);
testObj.BoolArray.Add(false);
assert.equal(testObj.BoolArray.IsValidIndex(0), true);
assert.equal(testObj.BoolArray.Get(0), false);
testObj.BoolArray.Add(true);
assert.equal(testObj.BoolArray.IsValidIndex(1), true);
assert.equal(testObj.BoolArray.Get(1), true);
assert.equal(testObj.BoolArray.Num(), 2);
assert.equal(testObj.BoolArray.IsValidIndex(0), true);
assert.equal(testObj.BoolArray.Get(0), false);
});
});
describe('Test TArray<EnumInt32>', function() {
it('Add values to the enum(int32) array', function() {
testObj.EnumInt32Array.Empty();
assert.equal(testObj.EnumInt32Array.Num(), 0);
// 测试枚举值
testObj.EnumInt32Array.Add(UE.EnumInt32.V0);
assert.equal(testObj.EnumInt32Array.IsValidIndex(0), true);
assert.equal(testObj.EnumInt32Array.Get(0), UE.EnumInt32.V0);
testObj.EnumInt32Array.Add(UE.EnumInt32.V1);
assert.equal(testObj.EnumInt32Array.IsValidIndex(1), true);
assert.equal(testObj.EnumInt32Array.Get(1), UE.EnumInt32.V1);
testObj.EnumInt32Array.Add(UE.EnumInt32.V2);
assert.equal(testObj.EnumInt32Array.IsValidIndex(2), true);
assert.equal(testObj.EnumInt32Array.Get(2), UE.EnumInt32.V2);
testObj.EnumInt32Array.Add(UE.EnumInt32.V3);
assert.equal(testObj.EnumInt32Array.IsValidIndex(3), true);
assert.equal(testObj.EnumInt32Array.Get(3), UE.EnumInt32.V3);
testObj.EnumInt32Array.Add(UE.EnumInt32.EnumInt32_MAX);
assert.equal(testObj.EnumInt32Array.IsValidIndex(4), true);
assert.equal(testObj.EnumInt32Array.Get(4), UE.EnumInt32.EnumInt32_MAX, 'EnumInt32_MAX should be valid (no overflow)');
// 测试枚举值(负数)
testObj.EnumInt32Array.Add(UE.EnumInt32.VM1);
assert.equal(testObj.EnumInt32Array.IsValidIndex(5), true);
assert.equal(testObj.EnumInt32Array.Get(5), UE.EnumInt32.VM1);
assert.equal(testObj.EnumInt32Array.Get(5), -1);
// 测试枚举值之外的值
testObj.EnumInt32Array.Add(1111);
assert.equal(testObj.EnumInt32Array.IsValidIndex(6), true);
assert.equal(testObj.EnumInt32Array.Get(6), 1111);
testObj.EnumInt32Array.Add(-1111);
assert.equal(testObj.EnumInt32Array.IsValidIndex(7), true);
assert.equal(testObj.EnumInt32Array.Get(7), -1111);
});
it('Test EnumInt32_MAX', function() {
testObj.EnumInt32Array.Empty();
assert.equal(testObj.EnumInt32Array.Num(), 0);
testObj.EnumInt32Array.Add(UE.EnumInt32.VM1);
testObj.EnumInt32Array.Add(UE.EnumInt32.V0);
testObj.EnumInt32Array.Add(UE.EnumInt32.V1);
testObj.EnumInt32Array.Add(UE.EnumInt32.V2);
testObj.EnumInt32Array.Add(UE.EnumInt32.V3);
for (let i = 0; i < testObj.EnumInt32Array.Num(); ++i) {
assert.ok(testObj.EnumInt32Array.Get(i) < UE.EnumInt32.EnumInt32_MAX, 'Should less than UE.EnumInt32.EnumInt32_MAX');
}
});
it('Test overflow in enum(int32) array', function() {
testObj.EnumInt32Array.Empty();
assert.equal(testObj.EnumInt32Array.Num(), 0);
const INT32_MAX = Math.pow(2, 31) - 1;
const INT32_MIN = Math.pow(2, 31) * -1;
// 枚举最大值
testObj.EnumInt32Array.Add(INT32_MAX);
assert.equal(testObj.EnumInt32Array.IsValidIndex(0), true);
assert.equal(testObj.EnumInt32Array.Get(0), INT32_MAX, 'Enum(int32) should be able to represent INT32_MAX');
// 枚举溢出
testObj.EnumInt32Array.Add(INT32_MAX + 1);
assert.equal(testObj.EnumInt32Array.IsValidIndex(1), true);
assert.equal(testObj.EnumInt32Array.Get(1), INT32_MIN, 'EnumInt32_MAX + 1 should be INT32_MIN(overflow)');
// 枚举最小值
testObj.EnumInt32Array.Add(INT32_MIN);
assert.equal(testObj.EnumInt32Array.IsValidIndex(2), true);
assert.equal(testObj.EnumInt32Array.Get(2), INT32_MIN, 'Enum(int32) should be able to represent INT32_MIN');
// 枚举溢出
testObj.EnumInt32Array.Add(INT32_MIN - 1);
assert.equal(testObj.EnumInt32Array.IsValidIndex(3), true);
assert.equal(testObj.EnumInt32Array.Get(3), INT32_MAX, 'INT32_MIN + 1 should be INT32_MAX(overflow)');
});
});
describe('Test TArray<EnumInt8Min>', function() {
it('Test overflow', function() {
testObj.EnumInt8MinArray.Empty();
assert.equal(testObj.EnumInt8MinArray.Num(), 0);
const INT8_MAX = Math.pow(2, 7) - 1;
const INT8_MIN = Math.pow(2, 7) * -1;
assert.equal(INT8_MIN, UE.EnumInt8Min.VINT8_MIN);
testObj.EnumInt8MinArray.Add(INT8_MIN - 1);
assert.equal(testObj.EnumInt8MinArray.IsValidIndex(0), true);
assert.equal(testObj.EnumInt8MinArray.Get(0), INT8_MAX, '(INT8_MIN - 1) should be overflow');
assert.equal(UE.EnumInt8Min.VINT8_MIN + 1, UE.EnumInt8Min.VINT8_MAX);
});
});
describe('Test TArray<EnumInt8Max>', function() {
it('Test overflow', function() {
testObj.EnumInt8MaxArray.Empty();
assert.equal(testObj.EnumInt8MaxArray.Num(), 0);
const INT8_MAX = Math.pow(2, 7) - 1;
const INT8_MIN = Math.pow(2, 7) * -1;
assert.equal(INT8_MAX, UE.EnumInt8Max.VINT8_MAX);
testObj.EnumInt8MaxArray.Add(INT8_MAX + 1);
assert.equal(testObj.EnumInt8MaxArray.IsValidIndex(0), true);
assert.equal(testObj.EnumInt8MaxArray.Get(0), INT8_MIN, '(INT8_MAX + 1) should be overflow');
});
});
function TestStringLikeArray(Array: any) {
Array.Empty();
assert.equal(Array.Num(), 0);
// 随便添加两个字符串
const STR_1 = 'The First String';
Array.Add(STR_1);
assert.equal(Array.IsValidIndex(0), true);
assert.equal(Array.Get(0), STR_1);
const STR_2 = 'The Second String';
Array.Add(STR_2);
assert.equal(Array.IsValidIndex(1), true);
assert.equal(Array.Get(1), STR_2);
// 修改索引1处的字符串
const STR_3 = Array.Get(1) + ': Say Hello World!';
Array.Set(1, STR_3);
assert.equal(Array.Num(), 2);
assert.equal(Array.IsValidIndex(1), true);
assert.equal(Array.Get(1), STR_3);
// utf8
const URF8_STR = '中文 español Deutsch English देवनागरी العربية português বাংলা русский 日本語 norsk bokmål ਪੰਜਾਬੀ 한국어 தமிழ் עברית';
Array.Add(URF8_STR);
assert.equal(Array.IsValidIndex(2), true);
assert.equal(Array.Get(2), URF8_STR, 'utf8 should works');
// template literals
let who = 'Martin';
Array.Add(`hello ${who}`);
assert.equal(Array.IsValidIndex(3), true);
assert.equal(Array.Get(3), 'hello ' + who, 'template literals should works');
}
function TestEmptyString(Array: any) {
Array.Empty();
// 空字符串
Array.Add('');
assert.equal(Array.IsValidIndex(0), true);
assert.equal(Array.Get(0), '', 'should be empty string');
assert.equal(Array.Get(0).concat('This string is 29-byte length').length, 29);
}
describe('Test TArray<FString>', function() {
it('Test normal use', function() {
TestStringLikeArray(testObj.FStringArray);
TestEmptyString(testObj.FStringArray);
});
});
describe('Test TArray<FText>', function() {
it('Test normal use', function() {
TestStringLikeArray(testObj.FTextArray);
TestEmptyString(testObj.FStringArray);
});
});
describe('Test TArray<FName>', function() {
it('Test normal use', function() {
TestStringLikeArray(testObj.FNameArray);
// 空字符串(FName为空时,值为'None')
testObj.FNameArray.Empty();
testObj.FNameArray.Add('');
assert.equal(testObj.FNameArray.IsValidIndex(0), true);
assert.equal(testObj.FNameArray.Get(0), 'None', 'should be empty string');
});
});
// 其他元素类型的Array
// (UScriptStruct、UClass、UObject、UInterface。UE到JS的类型对应关系见FPropertyTranslator::Create)
// (还有复合类型,Array内嵌Array等,也就是元素类型为UScriptArray)
// 其他容器
describe('Test fix size array int32[]', function() {
let arrayNum;
it('Num', function() {
arrayNum = testObj.Int32FixSizeArray.Num();
assert.equal(arrayNum, 1024);
});
it('Add & Get', function() {
for (let i = 0; i < arrayNum; ++i) {
testObj.Int32FixSizeArray.Set(i, i);
}
for (let i = 0; i < arrayNum; ++i) {
assert.equal(testObj.Int32FixSizeArray.Get(i), i);
}
});
it('Error suitation', function() {
// // TODO - 使用assert获取异常
// testObj.Int32FixSizeArray.Get(-1);
// testObj.Int32FixSizeArray.Get(arrayNum);
// testObj.Int32FixSizeArray.Set(-1, -1);
// testObj.Int32FixSizeArray.Set(1024, 1024);
});
});
describe('Test Int32Set', function() {
it('Num', function() {
assert.equal(testObj.Int32Set.Num(), 0, 'Size of the empty set should be 0');
// TODO - 补充一个已被初始化的set的情形
});
it('Add', function() {
// 加入非重复的值
testObj.Int32Set.Add(0);
testObj.Int32Set.Add(1);
testObj.Int32Set.Add(2);
assert.equal(testObj.Int32Set.Num(), 3, 'After adding 3 different keys, the size of set should 3');
// 加入重复的值
testObj.Int32Set.Add(0);
testObj.Int32Set.Add(1);
testObj.Int32Set.Add(2);
assert.equal(testObj.Int32Set.Num(), 3, 'Adding keys that already in the set should not change the size');
});
it('Empty', function() {
testObj.Int32Set.Empty();
assert.equal(testObj.Int32Set.Num(), 0, 'After emptying, the num of the set should be 0');
// 把key加回来
testObj.Int32Set.Add(0);
testObj.Int32Set.Add(1);
testObj.Int32Set.Add(2);
assert.equal(testObj.Int32Set.Num(), 3, 'After adding 3 different keys, the size of set should 3');
});
it('Contains', function() {
// 判断不在Set中的值
assert.equal(testObj.Int32Set.Contains(-1), false, 'Check a nonexistent key should return false');
// 判断在Set中的值
assert.equal(testObj.Int32Set.Contains(0), true);
assert.equal(testObj.Int32Set.Contains(1), true);
assert.equal(testObj.Int32Set.Contains(2), true);
});
it('FindIndex', function() {
// 寻找不在Set中的值的索引
assert.equal(testObj.Int32Set.FindIndex(-1), -1, 'The index of a nonexistent key should be -1');
// 寻找在Set中的值的索引
assert.notEqual(testObj.Int32Set.FindIndex(0), -1);
assert.notEqual(testObj.Int32Set.FindIndex(1), -1);
assert.notEqual(testObj.Int32Set.FindIndex(2), -1);
});
it('GetMaxIndex', function() {
assert.ok(testObj.Int32Set.GetMaxIndex() > 0, 'The max index of a nonempty set should greater than 0');
// assert.equal(testObj.Int32Set.GetMaxIndex(), testObj.Int32Set.Num(), 'The max index of current set should be its num');
});
it('IsValidIndex', function() {
// 判断Set中的key的index,应为合法
let index0 = testObj.Int32Set.FindIndex(0);
assert.equal(testObj.Int32Set.IsValidIndex(index0), true);
let index1 = testObj.Int32Set.FindIndex(1);
assert.equal(testObj.Int32Set.IsValidIndex(index1), true);
let index2 = testObj.Int32Set.FindIndex(2);
assert.equal(testObj.Int32Set.IsValidIndex(index2), true);
// 判断-1(即不在Set中的key的索引),应为非法
assert.equal(testObj.Int32Set.IsValidIndex(-1), false);
// 判断大于等于MaxIndex,应为非法(?)
const MAXINDEX = testObj.Int32Set.GetMaxIndex();
assert.equal(testObj.Int32Set.IsValidIndex(MAXINDEX), false);
assert.equal(testObj.Int32Set.IsValidIndex(MAXINDEX + 1), false);
});
it('RemoveAt', function() {
// 取中间索引值,移除对应的key
let index0 = testObj.Int32Set.FindIndex(0);
let index1 = testObj.Int32Set.FindIndex(1);
let index2 = testObj.Int32Set.FindIndex(2);
let small = index0; // 因为此时Set的值依此为0、1、2,索引值也一样,所以直接设置
let mid = index1;
let big = index2;
const OLD_MAXINDEX = testObj.Int32Set.GetMaxIndex();
const OLD_NUM = testObj.Int32Set.Num();
// 移除已有的值,Num应该减小
testObj.Int32Set.RemoveAt(mid); // TODO - 使用assert期望不抛出异常
assert.equal(testObj.Int32Set.Num(), OLD_NUM - 1, 'After removing one key the size of set should decrease 1');
// 移除中间index的一个值后,MaxIndex应该保持不变
assert.equal(testObj.Int32Set.GetMaxIndex(), OLD_MAXINDEX, 'After removing one key the max index of the set should be the same');
// 被移除的index,IsValidIndex返回false,其余index仍为true
for (let i = 0; i < OLD_MAXINDEX; ++i) {
if (i == mid) {
assert.equal(testObj.Int32Set.IsValidIndex(i), false, 'The only index of the removed key should be invalid');
}
else {
assert.equal(testObj.Int32Set.IsValidIndex(i), true);
}
}
// 移除最大的index,GetMaxIndex也不变
testObj.Int32Set.RemoveAt(big);
assert.equal(testObj.Int32Set.Num(), OLD_NUM - 2);
assert.equal(testObj.Int32Set.GetMaxIndex(), OLD_MAXINDEX);
// 移除所有值后,GetMaxIndex也不变
testObj.Int32Set.RemoveAt(small);
assert.equal(testObj.Int32Set.Num(), 0);
assert.equal(testObj.Int32Set.GetMaxIndex(), OLD_MAXINDEX);
// 只有调用Empty,GetMaxIndex才变为0
testObj.Int32Set.Empty();
assert.equal(testObj.Int32Set.GetMaxIndex(), 0);
});
it('Get', function() {
// 清空后再加值
testObj.Int32Set.Empty();
assert.equal(testObj.Int32Set.Num(), 0);
testObj.Int32Set.Add(0);
testObj.Int32Set.Add(1);
testObj.Int32Set.Add(2);
assert.equal(testObj.Int32Set.Num(), 3);
const OLD_NUM = testObj.Int32Set.Num();
// 以存在于Set中的key的索引为参数
let index0 = testObj.Int32Set.FindIndex(0);
let index1 = testObj.Int32Set.FindIndex(1);
let index2 = testObj.Int32Set.FindIndex(2);
assert.equal(testObj.Int32Set.Get(index0), 0);
assert.equal(testObj.Int32Set.Get(index1), 1);
assert.equal(testObj.Int32Set.Get(index2), 2);
// 以-1为参数(抛异常)
// testObj.Int32Set.Get(-1); // TODO - 使用assert预期异常
// 以不存在于Set中的key的索引为参数(抛异常)
// testObj.Int32Set.Get(testObj.Int32Set.GetMaxIndex());
testObj.Int32Set.RemoveAt(index0);
assert.equal(testObj.Int32Set.Num(), OLD_NUM - 1);
// 移除原本的key后,Get对应index(抛异常)
// testObj.Int32Set.Get(index0);
});
});
describe('Test Int32ToStrMap', function() {
it('Num', function() {
assert.equal(testObj.Int32ToStrMap.Num(), 0, 'Size of the empty map is 0');
// TODO - 增加对非空map的num判断
});
it('Add', function() {
testObj.Int32ToStrMap.Add(0, 'zero');
testObj.Int32ToStrMap.Add(1, 'one');
testObj.Int32ToStrMap.Add(2, 'two');
assert.equal(testObj.Int32ToStrMap.Num(), 3);
// 加入已有的kv
testObj.Int32ToStrMap.Add(0, 'zero');
testObj.Int32ToStrMap.Add(1, 'one');
testObj.Int32ToStrMap.Add(2, 'two');
assert.equal(testObj.Int32ToStrMap.Num(), 3);
});
it('Get', function() {
// 获取已有的kv
assert.equal(testObj.Int32ToStrMap.Get(0), 'zero');
assert.equal(testObj.Int32ToStrMap.Get(1), 'one');
assert.equal(testObj.Int32ToStrMap.Get(2), 'two');
// 获取不存在的kv
assert.equal(testObj.Int32ToStrMap.Get(3), undefined, 'Getting an undefined key should returns undefined');
});
it('Set', function() {
// 更改kv值
testObj.Int32ToStrMap.Set(0, 'zero_zero');
testObj.Int32ToStrMap.Set(1, 'one_one');
testObj.Int32ToStrMap.Set(2, 'two_two');
assert.equal(testObj.Int32ToStrMap.Num(), 3);
assert.equal(testObj.Int32ToStrMap.Get(0), 'zero_zero');
assert.equal(testObj.Int32ToStrMap.Get(1), 'one_one');
assert.equal(testObj.Int32ToStrMap.Get(2), 'two_two');
// 实际上Add函数也可以
testObj.Int32ToStrMap.Add(0, 'zero');
testObj.Int32ToStrMap.Add(1, 'one');
testObj.Int32ToStrMap.Add(2, 'two');
assert.equal(testObj.Int32ToStrMap.Num(), 3);
assert.equal(testObj.Int32ToStrMap.Get(0), 'zero');
assert.equal(testObj.Int32ToStrMap.Get(1), 'one');
assert.equal(testObj.Int32ToStrMap.Get(2), 'two');
});
it('Remove', function() {
// 移除一个Map中的kv
const OLD_NUM = testObj.Int32ToStrMap.Num();
testObj.Int32ToStrMap.Remove(0);
assert.equal(testObj.Int32ToStrMap.Num(), OLD_NUM - 1);
// 移除Map中不存在的kv
// testObj.Int32ToStrMap.Remove(0); // TODO - 使用assert预期异常
// 获取已移除的key
assert.equal(testObj.Int32ToStrMap.Get(0), undefined);
// 把已移除的kv加回去
testObj.Int32ToStrMap.Add(0, 'zero');
assert.equal(testObj.Int32ToStrMap.Num(), OLD_NUM);
assert.equal(testObj.Int32ToStrMap.Get(0), 'zero');
});
it('Empty', function() {
// 清空
testObj.Int32ToStrMap.Empty();
assert.equal(testObj.Int32ToStrMap.Num(), 0);
// 访问旧kv均为undefined
assert.equal(testObj.Int32ToStrMap.Get(0), undefined);
assert.equal(testObj.Int32ToStrMap.Get(1), undefined);
assert.equal(testObj.Int32ToStrMap.Get(2), undefined);
});
it('GetMaxIndex', function() {
// 空的容器最大索引应该为0
assert.equal(testObj.Int32ToStrMap.GetMaxIndex(), 0);
// 加入三个kv
testObj.Int32ToStrMap.Add(0, 'zero');
testObj.Int32ToStrMap.Add(5, 'five');
testObj.Int32ToStrMap.Add(10, 'ten');
assert.equal(testObj.Int32ToStrMap.Num(), 3);
// GetMaxIndex获取的是kv的最大索引+1
assert.equal(testObj.Int32ToStrMap.GetMaxIndex(), 3, 'The max index of the current map should be 3(there are only three key-value pairs');
// 移除中间的kv,最大索引不变
testObj.Int32ToStrMap.Remove(5);
assert.equal(testObj.Int32ToStrMap.Num(), 2);
assert.equal(testObj.Int32ToStrMap.GetMaxIndex(), 3);
// 移除最后加入的kv,最大索引不变
testObj.Int32ToStrMap.Remove(10);
assert.equal(testObj.Int32ToStrMap.Num(), 1);
assert.equal(testObj.Int32ToStrMap.GetMaxIndex(), 3);
// 移除唯一的一个,最大索引不变
testObj.Int32ToStrMap.Remove(0);
assert.equal(testObj.Int32ToStrMap.Num(), 0);
assert.equal(testObj.Int32ToStrMap.GetMaxIndex(), 3);
// 只有调用了Empty,最大索引才会变为0
testObj.Int32ToStrMap.Empty();
assert.equal(testObj.Int32ToStrMap.Num(), 0);
assert.equal(testObj.Int32ToStrMap.GetMaxIndex(), 0);
});
it('IsValidIndex', function() {
// 加入三个kv
testObj.Int32ToStrMap.Add(0, 'zero'); // 索引0
testObj.Int32ToStrMap.Add(5, 'five'); // 索引1
testObj.Int32ToStrMap.Add(10, 'ten'); // 索引2
assert.equal(testObj.Int32ToStrMap.Num(), 3);
for (let i = 0; i < testObj.Int32ToStrMap.GetMaxIndex(); ++i) {
assert.equal(testObj.Int32ToStrMap.IsValidIndex(i), true);
}
// 被移除的kv,其原本的index变为非法索引
testObj.Int32ToStrMap.Remove(5);
assert.equal(testObj.Int32ToStrMap.Num(), 2);
for (let i = 0; i < testObj.Int32ToStrMap.GetMaxIndex(); ++i) {
if (i == 1) {
assert.equal(testObj.Int32ToStrMap.IsValidIndex(i), false);
} else {
assert.equal(testObj.Int32ToStrMap.IsValidIndex(i), true);
}
}
});
it('GetKey', function() {
testObj.Int32ToStrMap.Empty();
assert.equal(testObj.Int32ToStrMap.Num(), 0);
// 加入三个kv
testObj.Int32ToStrMap.Add(0, 'zero'); // 索引0
testObj.Int32ToStrMap.Add(5, 'five'); // 索引1
testObj.Int32ToStrMap.Add(10, 'ten'); // 索引2
assert.equal(testObj.Int32ToStrMap.Num(), 3);
// 获取index对应的key
assert.equal(testObj.Int32ToStrMap.GetKey(0), 0);
assert.equal(testObj.Int32ToStrMap.GetKey(1), 5);
assert.equal(testObj.Int32ToStrMap.GetKey(2), 10);
// 获取非法index对应的key
// testObj.Int32ToStrMap.GetKey(testObj.Int32ToStrMap.GetMaxIndex()); // TODO - 用assert期望异常
});
});
describe('Test FStringSet', function() {
it('Add some keys', function() {
testObj.FStringSet.Empty();
assert.equal(testObj.FStringSet.Num(), 0);
testObj.FStringSet.Add('One');
testObj.FStringSet.Add('Two');
testObj.FStringSet.Add('Three');
assert.equal(testObj.FStringSet.Num(), 3);
// FString的hash,大小写不敏感
testObj.FStringSet.Add('one');
testObj.FStringSet.Add('two');
testObj.FStringSet.Add('three');
// assert.equal(testObj.FStringSet.Num(), 6);
assert.equal(testObj.FStringSet.Num(), 3);
assert.equal(testObj.FStringSet.Contains('One'), true);
assert.equal(testObj.FStringSet.Contains('one'), true);
assert.equal(testObj.FStringSet.Contains('Two'), true);
assert.equal(testObj.FStringSet.Contains('two'), true);
assert.equal(testObj.FStringSet.Contains('Three'), true);
assert.equal(testObj.FStringSet.Contains('three'), true);
});
});
describe('Test StrToStrMap', function() {
it('Add some key-value pairs', function() {
testObj.StrToStrMap.Empty();
assert.equal(testObj.StrToStrMap.Num(), 0);
// 加三个kv
testObj.StrToStrMap.Add('One', 'one_one');
testObj.StrToStrMap.Add('Two', 'two_two');
testObj.StrToStrMap.Add('Three', 'three_three');
assert.equal(testObj.StrToStrMap.Num(), 3);
// FString的hash,大小写不敏感
assert.equal(testObj.StrToStrMap.Get('one'), 'one_one');
assert.equal(testObj.StrToStrMap.Get('two'), 'two_two');
assert.equal(testObj.StrToStrMap.Get('three'), 'three_three');
});
});
/*
* 测试访问UE对象,属性、方法:{简单类型参数方法、复杂类型参数方法、引用类型参数方法、静态类型、扩展方法}*{带返回值、不带返回值}
*/
/*
* 引擎方法
*/
/*
* Delegate
*/ | the_stack |
import * as coreClient from "@azure/core-client";
export const AvailabilityStatusListResult: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "AvailabilityStatusListResult",
modelProperties: {
value: {
serializedName: "value",
required: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "AvailabilityStatus"
}
}
}
},
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const AvailabilityStatus: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "AvailabilityStatus",
modelProperties: {
id: {
serializedName: "id",
type: {
name: "String"
}
},
name: {
serializedName: "name",
type: {
name: "String"
}
},
type: {
serializedName: "type",
type: {
name: "String"
}
},
location: {
serializedName: "location",
type: {
name: "String"
}
},
properties: {
serializedName: "properties",
type: {
name: "Composite",
className: "AvailabilityStatusProperties"
}
}
}
}
};
export const AvailabilityStatusProperties: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "AvailabilityStatusProperties",
modelProperties: {
availabilityState: {
serializedName: "availabilityState",
type: {
name: "Enum",
allowedValues: ["Available", "Unavailable", "Unknown"]
}
},
summary: {
serializedName: "summary",
type: {
name: "String"
}
},
detailedStatus: {
serializedName: "detailedStatus",
type: {
name: "String"
}
},
reasonType: {
serializedName: "reasonType",
type: {
name: "String"
}
},
rootCauseAttributionTime: {
serializedName: "rootCauseAttributionTime",
type: {
name: "DateTime"
}
},
healthEventType: {
serializedName: "healthEventType",
type: {
name: "String"
}
},
healthEventCause: {
serializedName: "healthEventCause",
type: {
name: "String"
}
},
healthEventCategory: {
serializedName: "healthEventCategory",
type: {
name: "String"
}
},
healthEventId: {
serializedName: "healthEventId",
type: {
name: "String"
}
},
resolutionETA: {
serializedName: "resolutionETA",
type: {
name: "DateTime"
}
},
occuredTime: {
serializedName: "occuredTime",
type: {
name: "DateTime"
}
},
reasonChronicity: {
serializedName: "reasonChronicity",
type: {
name: "Enum",
allowedValues: ["Transient", "Persistent"]
}
},
reportedTime: {
serializedName: "reportedTime",
type: {
name: "DateTime"
}
},
recentlyResolvedState: {
serializedName: "recentlyResolvedState",
type: {
name: "Composite",
className: "AvailabilityStatusPropertiesRecentlyResolvedState"
}
},
recommendedActions: {
serializedName: "recommendedActions",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "RecommendedAction"
}
}
}
},
serviceImpactingEvents: {
serializedName: "serviceImpactingEvents",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ServiceImpactingEvent"
}
}
}
}
}
}
};
export const AvailabilityStatusPropertiesRecentlyResolvedState: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "AvailabilityStatusPropertiesRecentlyResolvedState",
modelProperties: {
unavailableOccurredTime: {
serializedName: "unavailableOccurredTime",
type: {
name: "DateTime"
}
},
resolvedTime: {
serializedName: "resolvedTime",
type: {
name: "DateTime"
}
},
unavailabilitySummary: {
serializedName: "unavailabilitySummary",
type: {
name: "String"
}
}
}
}
};
export const RecommendedAction: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "RecommendedAction",
modelProperties: {
action: {
serializedName: "action",
type: {
name: "String"
}
},
actionUrl: {
serializedName: "actionUrl",
type: {
name: "String"
}
},
actionUrlText: {
serializedName: "actionUrlText",
type: {
name: "String"
}
}
}
}
};
export const ServiceImpactingEvent: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ServiceImpactingEvent",
modelProperties: {
eventStartTime: {
serializedName: "eventStartTime",
type: {
name: "DateTime"
}
},
eventStatusLastModifiedTime: {
serializedName: "eventStatusLastModifiedTime",
type: {
name: "DateTime"
}
},
correlationId: {
serializedName: "correlationId",
type: {
name: "String"
}
},
status: {
serializedName: "status",
type: {
name: "Composite",
className: "ServiceImpactingEventStatus"
}
},
incidentProperties: {
serializedName: "incidentProperties",
type: {
name: "Composite",
className: "ServiceImpactingEventIncidentProperties"
}
}
}
}
};
export const ServiceImpactingEventStatus: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ServiceImpactingEventStatus",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "String"
}
}
}
}
};
export const ServiceImpactingEventIncidentProperties: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ServiceImpactingEventIncidentProperties",
modelProperties: {
title: {
serializedName: "title",
type: {
name: "String"
}
},
service: {
serializedName: "service",
type: {
name: "String"
}
},
region: {
serializedName: "region",
type: {
name: "String"
}
},
incidentType: {
serializedName: "incidentType",
type: {
name: "String"
}
}
}
}
};
export const ErrorResponse: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ErrorResponse",
modelProperties: {
code: {
serializedName: "code",
readOnly: true,
type: {
name: "String"
}
},
message: {
serializedName: "message",
readOnly: true,
type: {
name: "String"
}
},
details: {
serializedName: "details",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const OperationListResult: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "OperationListResult",
modelProperties: {
value: {
serializedName: "value",
required: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Operation"
}
}
}
}
}
}
};
export const Operation: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Operation",
modelProperties: {
name: {
serializedName: "name",
type: {
name: "String"
}
},
display: {
serializedName: "display",
type: {
name: "Composite",
className: "OperationDisplay"
}
}
}
}
};
export const OperationDisplay: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "OperationDisplay",
modelProperties: {
provider: {
serializedName: "provider",
type: {
name: "String"
}
},
resource: {
serializedName: "resource",
type: {
name: "String"
}
},
operation: {
serializedName: "operation",
type: {
name: "String"
}
},
description: {
serializedName: "description",
type: {
name: "String"
}
}
}
}
};
export const StatusBanner: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "StatusBanner",
modelProperties: {
title: {
serializedName: "title",
type: {
name: "String"
}
},
message: {
serializedName: "message",
type: {
name: "String"
}
},
cloud: {
serializedName: "cloud",
type: {
name: "String"
}
},
lastModifiedTime: {
serializedName: "lastModifiedTime",
type: {
name: "DateTime"
}
}
}
}
};
export const StatusActiveEvent: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "StatusActiveEvent",
modelProperties: {
title: {
serializedName: "title",
type: {
name: "String"
}
},
description: {
serializedName: "description",
type: {
name: "String"
}
},
trackingId: {
serializedName: "trackingId",
type: {
name: "String"
}
},
startTime: {
serializedName: "startTime",
type: {
name: "DateTime"
}
},
cloud: {
serializedName: "cloud",
type: {
name: "String"
}
},
severity: {
serializedName: "severity",
type: {
name: "String"
}
},
stage: {
serializedName: "stage",
type: {
name: "String"
}
},
published: {
serializedName: "published",
type: {
name: "Boolean"
}
},
lastModifiedTime: {
serializedName: "lastModifiedTime",
type: {
name: "DateTime"
}
},
impacts: {
serializedName: "impacts",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "EmergingIssueImpact"
}
}
}
}
}
}
};
export const EmergingIssueImpact: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "EmergingIssueImpact",
modelProperties: {
id: {
serializedName: "id",
type: {
name: "String"
}
},
name: {
serializedName: "name",
type: {
name: "String"
}
},
regions: {
serializedName: "regions",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ImpactedRegion"
}
}
}
}
}
}
};
export const ImpactedRegion: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ImpactedRegion",
modelProperties: {
id: {
serializedName: "id",
type: {
name: "String"
}
},
name: {
serializedName: "name",
type: {
name: "String"
}
}
}
}
};
export const Resource: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Resource",
modelProperties: {
id: {
serializedName: "id",
readOnly: true,
type: {
name: "String"
}
},
name: {
serializedName: "name",
readOnly: true,
type: {
name: "String"
}
},
type: {
serializedName: "type",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const EmergingIssueListResult: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "EmergingIssueListResult",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "EmergingIssuesGetResult"
}
}
}
},
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
};
export const EmergingIssuesGetResult: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "EmergingIssuesGetResult",
modelProperties: {
...Resource.type.modelProperties,
refreshTimestamp: {
serializedName: "properties.refreshTimestamp",
type: {
name: "DateTime"
}
},
statusBanners: {
serializedName: "properties.statusBanners",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "StatusBanner"
}
}
}
},
statusActiveEvents: {
serializedName: "properties.statusActiveEvents",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "StatusActiveEvent"
}
}
}
}
}
}
}; | the_stack |
import { FC, useState } from "react";
import Modal from "../Modal";
import { ExperimentInterfaceStringDates } from "back-end/types/experiment";
import Tabs from "../Tabs/Tabs";
import Tab from "../Tabs/Tab";
import { getEvenSplit } from "../../services/utils";
import stringify from "json-stringify-pretty-compact";
import { useForm } from "react-hook-form";
import { useEffect } from "react";
import {
generateJavascriptSnippet,
getUrlRegex,
TrackingType,
} from "../../services/codegen";
import { FaExclamationTriangle } from "react-icons/fa";
import Code from "../Code";
import Field from "../Forms/Field";
type Experiment = {
key: string;
// eslint-disable-next-line
variations: any[];
weights?: number[];
status?: string;
coverage?: number;
url?: string;
groups?: string[];
force?: number;
anon?: boolean;
};
function removeKeyAndVariations(expDef: Experiment) {
// eslint-disable-next-line
const { key, variations, ...other } = expDef;
if (Object.keys(other).length) return other;
return null;
}
function phpArrayFormat(json: unknown) {
return stringify(json)
.replace(/\{/g, "[")
.replace(/\}/g, "]")
.replace(/:/g, " =>");
}
function indentLines(code: string, indent: number = 2) {
const spaces = " ".repeat(indent);
return code.split("\n").join("\n" + spaces);
}
function withHashAttribute(expDef: Experiment) {
const { anon, ...otherProps } = expDef;
if (anon) {
return {
...otherProps,
hashAttribute: "anonId",
};
} else {
return {
...otherProps,
};
}
}
function withRealRegex(stringified: string): string {
return stringified.replace(/("url"\s*:\s*)"([^"]+)"/, (match, key, value) => {
return key + getUrlRegex(value);
});
}
function toPythonParams(stringified: string): string {
return stringified
.replace(/^\{|\}$/g, "")
.replace(/\n {2}"([a-zA-Z0-9_]+)": /g, "\n $1 = ");
}
function toRubyParams(stringified: string): string {
return stringified
.replace(/^\[|\]$/g, "")
.replace(/"([a-zA-Z]+)" => /g, ":$1 => ");
}
const InstructionsModal: FC<{
experiment: ExperimentInterfaceStringDates;
close: () => void;
}> = ({ experiment, close }) => {
const {
trackingKey,
userIdType,
variations,
targetURLRegex,
status,
results,
winner,
phases,
} = experiment;
const phase = phases?.[0];
const form = useForm<{
tracking: TrackingType;
funcs: string[];
gaDimension: number;
mixpanelProjectId: string;
}>({
defaultValues: {
tracking: "segment",
funcs: variations.slice(1).map((v) => `console.log("${v.name}")`),
gaDimension: 1,
mixpanelProjectId: "",
},
});
const [codegen, setCodegen] = useState("");
const value = {
tracking: form.watch("tracking"),
funcs: variations.slice(1).map((v, i) => form.watch(`funcs.${i}`)),
gaDimension: form.watch("gaDimension"),
mixpanelProjectId: form.watch("mixpanelProjectId"),
};
useEffect(() => {
setCodegen(
generateJavascriptSnippet(
experiment,
["", ...value.funcs],
value.tracking,
value.tracking === "ga"
? String(value.gaDimension)
: value.tracking === "mixpanel"
? value.mixpanelProjectId
: ""
)
);
}, [value.funcs, value.tracking, value.gaDimension, value.mixpanelProjectId]);
const expDef: Experiment = {
key: trackingKey,
variations: variations.map((v) =>
v.value ? JSON.parse(v.value) : v.key || v.name
),
};
let variationParam = "";
let variationParamValues: string[];
if (typeof expDef.variations[0] === "object") {
variationParam = Object.keys(expDef.variations[0])[0];
variationParamValues = expDef.variations.map((v) => v[variationParam]);
} else {
variationParamValues = expDef.variations;
}
const variationParamList = variationParamValues
.map((v) => `"${v}"`)
.join(" or ");
if (status !== "running") {
expDef.status = status;
}
if (targetURLRegex) {
expDef.url = targetURLRegex;
}
if (userIdType === "anonymous") {
expDef.anon = true;
}
expDef.groups = [];
if (phase) {
if (phase.groups?.length > 0) {
expDef.groups.push(...phase.groups);
}
// Add coverage or variation weights if different from defaults
if (phase.coverage < 1) {
expDef.coverage = phase.coverage;
}
const evenWeights = getEvenSplit(variations.length);
if (evenWeights.join(",") !== phase.variationWeights.join(",")) {
expDef.weights = phase.variationWeights;
}
}
if (status === "stopped" && results === "won") {
expDef.force = winner;
}
if (!expDef.groups.length) {
delete expDef.groups;
}
return (
<Modal
close={close}
open={true}
header="Implementation Instructions"
size="lg"
closeCta="Close"
>
<Tabs className="mb-3">
<Tab display="JS">
<p>
Install our{" "}
<a
href="https://docs.growthbook.io/lib/js"
target="_blank"
rel="noopener noreferrer"
>
Javascript Client Library
</a>{" "}
and then...
</p>
<Code
language="javascript"
code={`const { value } = growthbook.run(${withRealRegex(
stringify(withHashAttribute(expDef))
)})\n\nconsole.log(value${
!variationParam
? ""
: variationParam.match(/^[a-zA-Z0-9_]*$/)
? "." + variationParam
: '["' + variationParam + '"]'
}); // ${variationParamList}`}
/>
</Tab>
<Tab display="React">
<p>
Install our{" "}
<a
href="https://docs.growthbook.io/lib/react"
target="_blank"
rel="noopener noreferrer"
>
React Client Library
</a>{" "}
and then...
</p>
<Code
language="tsx"
code={`function MyComponent() {\n const { value } = useExperiment(${indentLines(
stringify(expDef)
)})\n\n return <div>{value${
!variationParam
? ""
: variationParam.match(/^[a-zA-Z0-9_]*$/)
? "." + variationParam
: '["' + variationParam + '"]'
}}</div>; // ${variationParamList}\n}`}
/>
</Tab>
<Tab display="PHP">
<p>
Install our{" "}
<a
href="https://github.com/growthbook/growthbook-php"
target="_blank"
rel="noopener noreferrer"
>
PHP Client Library
</a>{" "}
and then...
</p>
<Code
language="php"
code={`<?php\n$experiment = new Growthbook\\Experiment(\n "${
expDef.key
}",\n ${indentLines(phpArrayFormat(expDef.variations))}${
removeKeyAndVariations(expDef)
? ",\n " +
indentLines(phpArrayFormat(removeKeyAndVariations(expDef)))
: ""
}\n);\n$result = $user->experiment($experiment);\n\necho $result->value${
!variationParam ? "" : '["' + variationParam + '"]'
}; // ${variationParamList}`}
/>
</Tab>
<Tab display="Python">
<p>
Install our{" "}
<a
href="https://github.com/growthbook/growthbook-python"
target="_blank"
rel="noopener noreferrer"
>
Python Client Library
</a>{" "}
and then...
</p>
<Code
language="python"
code={`from growthbook import Experiment\n\nresult = gb.run(Experiment(${toPythonParams(
stringify(withHashAttribute(expDef))
)}))\n\n# ${variationParamList}\nprint(result.value${
!variationParam ? "" : '["' + variationParam + '"]'
})`}
/>
</Tab>
<Tab display="Ruby">
<p>
Install our{" "}
<a
href="https://github.com/growthbook/growthbook-ruby"
target="_blank"
rel="noopener noreferrer"
>
Ruby Client Library
</a>{" "}
and then...
</p>
<Code
language="ruby"
code={`exp = Growthbook::Experiment.new("${expDef.key}", ${
expDef.variations.length
}${
removeKeyAndVariations(expDef)
? ",\n " +
toRubyParams(
indentLines(phpArrayFormat(removeKeyAndVariations(expDef)))
) +
"\n"
: ""
})\n\nresult = user.experiment(exp)\ncase result.variation\n${experiment.variations
.map((v, i) => {
return `when ${i}\n puts ${JSON.stringify(v.name)}`;
})
.join("\n")}\nelse\n puts "Not in experiment"`}
/>
</Tab>
<Tab display="Inline">
<div className="alert alert-warning">
<FaExclamationTriangle /> Inline Scripts are a beta feature. Use at
your own risk and make sure to test!
</div>
<p>
Generate a small inline script tag (~500 bytes) for your experiment
without any dependencies or network requests.
</p>
<hr />
<form onSubmit={(e) => e.preventDefault()}>
<div className="row">
<div className="col">
<Field
label="Event Tracking System"
{...form.register("tracking")}
options={[
{ display: "Segment", value: "segment" },
{ display: "Mixpanel", value: "mixpanel" },
{ display: "Google Analytics", value: "ga" },
{ display: "Custom", value: "custom" },
]}
/>
</div>
{value.tracking === "ga" && (
<div className="col">
<Field
label="GA Custom Dimension"
type="number"
{...form.register("gaDimension", { valueAsNumber: true })}
min={1}
max={100}
/>
</div>
)}
{value.tracking === "mixpanel" && (
<div className="col">
<Field
label="Mixpanel Project Token"
{...form.register("mixpanelProjectId")}
/>
</div>
)}
</div>
{variations.slice(1).map((v, i) => (
<Field
key={i}
label={
<>
<strong>Javascript:</strong> {v.name}
</>
}
placeholder={`console.log("${v.name}")`}
textarea
minRows={1}
maxRows={6}
{...form.register(`funcs.${i}`)}
helpText={
<>
Will be executed if user is assigned variation:{" "}
<code>{v.name}</code>
</>
}
/>
))}
</form>
<Code language="html" code={codegen} />
</Tab>
</Tabs>
Full documentation and other languages are at{" "}
<a
href="https://docs.growthbook.io"
target="_blank"
rel="noopener noreferrer"
>
https://docs.growthbook.io
</a>
</Modal>
);
};
export default InstructionsModal; | the_stack |
import { assert, expect } from 'chai';
import { rejects } from 'assert';
import sinon from 'sinon';
import path from 'path';
import fs from 'fs-extra';
import { applyYarnResolutions } from '../src/applyYarnResolutions';
import { generateComposite } from '../src/generateComposite';
import {
getMiniAppsDeltas,
getPackageJsonDependenciesUsingMiniAppDeltas,
runYarnUsingMiniAppDeltas,
} from '../src/miniAppsDeltasUtils';
import * as ernUtil from 'ern-core';
import { PackagePath } from 'ern-core';
const { YarnCli, shell } = ernUtil;
const sandbox = sinon.createSandbox();
// Spies
let yarnCliStub: any;
let tmpOutDir: string;
const currentDir = __dirname;
const pathToFixtures = path.join(currentDir, 'fixtures');
const pathToSampleYarnLock = path.join(pathToFixtures, 'sample.yarn.lock');
const sampleYarnLock = fs.readFileSync(pathToSampleYarnLock, 'utf8');
describe('ern-container-gen utils.js', () => {
// Before each test
beforeEach(() => {
yarnCliStub = sandbox.stub(YarnCli.prototype);
// Go back to initial dir (otherwise we might start execution from a temporary
// created directory that got removed and it makes shelljs go crazy)
process.chdir(currentDir);
// Create temporary directory to use as target output directory of some
// functions under test
tmpOutDir = ernUtil.createTmpDir();
});
// After each test
afterEach(() => {
// Remove the temporary output directory created for the test
shell.rm('-rf', tmpOutDir);
sandbox.restore();
});
describe('getMiniAppsDeltas', () => {
it('should compute new deltas', () => {
const miniApps = [
PackagePath.fromString('fourth-miniapp@1.0.0'),
PackagePath.fromString('fifth-miniapp@1.0.0'),
];
const result = getMiniAppsDeltas(miniApps, sampleYarnLock);
expect(result).to.have.property('new').that.is.a('array').lengthOf(2);
});
it('should compute same deltas', () => {
const miniApps = [
PackagePath.fromString('first-miniapp@6.0.0'),
PackagePath.fromString('second-miniapp@3.0.0'),
];
const result = getMiniAppsDeltas(miniApps, sampleYarnLock);
expect(result).to.have.property('same').that.is.a('array').lengthOf(2);
});
it('should compute upgraded deltas', () => {
const miniApps = [
PackagePath.fromString('first-miniapp@7.0.0'),
PackagePath.fromString('second-miniapp@4.0.0'),
];
const result = getMiniAppsDeltas(miniApps, sampleYarnLock);
expect(result)
.to.have.property('upgraded')
.that.is.a('array')
.lengthOf(2);
});
it('should compute deltas', () => {
const miniApps = [
PackagePath.fromString('first-miniapp@1.0.0'),
PackagePath.fromString('second-miniapp@3.0.0'),
PackagePath.fromString('fourth-miniapp@1.0.0'),
];
const result = getMiniAppsDeltas(miniApps, sampleYarnLock);
expect(result).to.have.property('new').that.is.a('array').lengthOf(1);
expect(result).to.have.property('same').that.is.a('array').lengthOf(1);
expect(result)
.to.have.property('upgraded')
.that.is.a('array')
.lengthOf(1);
});
});
describe('runYarnUsingMiniAppDeltas', () => {
it('should yarn add new MiniApps', async () => {
const miniAppsDeltas = {
new: [
PackagePath.fromString('fourth-miniapp@7.0.0'),
PackagePath.fromString('fifth-miniapp@4.0.0'),
],
};
await runYarnUsingMiniAppDeltas(miniAppsDeltas);
assert(yarnCliStub.add.calledTwice);
});
it('should yarn add upgraded MiniApps', async () => {
const miniAppsDeltas = {
upgraded: [
PackagePath.fromString('first-miniapp@7.0.0'),
PackagePath.fromString('second-miniapp@4.0.0'),
],
};
await runYarnUsingMiniAppDeltas(miniAppsDeltas);
assert(yarnCliStub.add.calledTwice);
});
it('should not yarn add same MiniApps versions', async () => {
const miniAppsDeltas = {
same: [
PackagePath.fromString('first-miniapp@6.0.0'),
PackagePath.fromString('second-miniapp@3.0.0'),
],
};
await runYarnUsingMiniAppDeltas(miniAppsDeltas);
assert(yarnCliStub.add.notCalled);
});
it('should work correctly with mixed deltas', async () => {
const miniAppsDeltas = {
new: [PackagePath.fromString('fourth-miniapp@7.0.0')],
same: [
PackagePath.fromString('first-miniapp@6.0.0'),
PackagePath.fromString('second-miniapp@3.0.0'),
],
upgraded: [
PackagePath.fromString('first-miniapp@7.0.0'),
PackagePath.fromString('second-miniapp@4.0.0'),
],
};
await runYarnUsingMiniAppDeltas(miniAppsDeltas);
assert(yarnCliStub.add.calledThrice);
});
});
describe('getPackageJsonDependenciesBasedOnMiniAppDeltas', () => {
it('should inject MiniApps that have same version as previous', () => {
const miniAppsDeltas = {
same: [
PackagePath.fromString('first-miniapp@6.0.0'),
PackagePath.fromString('second-miniapp@3.0.0'),
],
};
const result = getPackageJsonDependenciesUsingMiniAppDeltas(
miniAppsDeltas,
sampleYarnLock,
);
expect(result).to.have.property('first-miniapp', '6.0.0');
expect(result).to.have.property('second-miniapp', '3.0.0');
});
it('should inject MiniApps that have upgraded versions', () => {
const miniAppsDeltas = {
upgraded: [
PackagePath.fromString('first-miniapp@7.0.0'),
PackagePath.fromString('second-miniapp@4.0.0'),
],
};
const result = getPackageJsonDependenciesUsingMiniAppDeltas(
miniAppsDeltas,
sampleYarnLock,
);
expect(result).to.have.property('first-miniapp', '6.0.0');
expect(result).to.have.property('second-miniapp', '3.0.0');
});
it('should not inject MiniApps that are new', () => {
const miniAppsDeltas = {
new: [
PackagePath.fromString('fourth-miniapp@7.0.0'),
PackagePath.fromString('fifth-miniapp@4.0.0'),
],
};
const result = getPackageJsonDependenciesUsingMiniAppDeltas(
miniAppsDeltas,
sampleYarnLock,
);
expect(result).empty;
});
it('should inject proper MiniApps', () => {
const miniAppsDeltas = {
new: [PackagePath.fromString('fourth-miniapp@7.0.0')],
same: [PackagePath.fromString('first-miniapp@6.0.0')],
upgraded: [PackagePath.fromString('second-miniapp@4.0.0')],
};
const result = getPackageJsonDependenciesUsingMiniAppDeltas(
miniAppsDeltas,
sampleYarnLock,
);
expect(result).to.have.property('first-miniapp', '6.0.0');
expect(result).to.have.property('second-miniapp', '3.0.0');
});
});
const createCompositeNodeModulesReactNativePackageJson = (
rootDir: string,
rnVersion: string,
) => {
const pathToCompositeNodeModulesReactNative = path.join(
rootDir,
'node_modules',
'react-native',
);
const pathToCompositeNodeModulesMetro = path.join(
rootDir,
'node_modules',
'metro',
);
ernUtil.shell.mkdir('-p', pathToCompositeNodeModulesReactNative);
fs.writeFileSync(
path.join(pathToCompositeNodeModulesReactNative, 'package.json'),
JSON.stringify({ version: rnVersion }),
);
ernUtil.shell.mkdir('-p', pathToCompositeNodeModulesMetro);
fs.writeFileSync(
path.join(pathToCompositeNodeModulesMetro, 'package.json'),
JSON.stringify({ version: '0.51.0' }),
);
};
describe('generateComposite [with yarn lock]', () => {
it('should throw an exception if at least one of the MiniApp path is using a file scheme [1]', async () => {
const miniApps = [
PackagePath.fromString(path.join(__dirname, 'fixtures', 'miniapp')),
];
assert(
rejects(
generateComposite({
miniApps,
outDir: tmpOutDir,
pathToYarnLock: 'hello',
}),
),
);
});
it('should throw an exception if at least one of the MiniApp path is using a file scheme [2]', async () => {
const miniApps = [
PackagePath.fromString('first-miniapp@1.0.0'),
PackagePath.fromString(path.join(__dirname, 'fixtures', 'miniapp')),
];
assert(
rejects(
generateComposite({
miniApps,
outDir: tmpOutDir,
pathToYarnLock: 'hello',
}),
),
);
});
it('should throw an exception if at least one of the MiniApp path is using a git scheme [1]', async () => {
const miniApps = [PackagePath.fromString('git://github.com:org/repo')];
assert(
rejects(
generateComposite({
miniApps,
outDir: tmpOutDir,
pathToYarnLock: 'hello',
}),
),
);
});
it('should throw an exception if at least one of the MiniApp path is using a git scheme [2]', async () => {
const miniApps = [
PackagePath.fromString('first-miniapp@1.0.0'),
PackagePath.fromString('git://github.com:org/repo'),
];
assert(
rejects(
generateComposite({
miniApps,
outDir: tmpOutDir,
pathToYarnLock: 'hello',
}),
),
);
});
it('should throw an exception if one of the MiniApp is not using an explicit version [1]', async () => {
const miniApps = [PackagePath.fromString('first-miniapp')];
assert(
rejects(
generateComposite({
miniApps,
outDir: tmpOutDir,
pathToYarnLock: 'hello',
}),
),
);
});
it('should throw an exception if one of the MiniApp is not using an explicit version [1]', async () => {
const miniApps = [
PackagePath.fromString('first-miniapp'),
PackagePath.fromString('second-miniapp@1.0.0'),
];
assert(
rejects(
generateComposite({
miniApps,
outDir: tmpOutDir,
pathToYarnLock: 'hello',
}),
),
);
});
it('should throw an exception if path to yarn.lock does not exists', async () => {
const miniApps = [
PackagePath.fromString('first-miniapp@1.0.0'),
PackagePath.fromString('second-miniapp@1.0.0'),
];
assert(
rejects(
generateComposite({
miniApps,
outDir: tmpOutDir,
pathToYarnLock: path.join(tmpOutDir, 'yarn.lock'),
}),
),
);
});
it('should throw an exception if called with no miniapp or js api impl', async () => {
yarnCliStub.install.callsFake(() =>
createCompositeNodeModulesReactNativePackageJson(tmpOutDir, '0.56.0'),
);
const miniApps: PackagePath[] = [];
assert(
rejects(
generateComposite({
miniApps,
outDir: tmpOutDir,
pathToYarnLock: pathToSampleYarnLock,
}),
),
);
});
it('should call yarn install prior to calling yarn add for each MiniApp', async () => {
// One new, one same, one upgrade
yarnCliStub.install.callsFake(() =>
createCompositeNodeModulesReactNativePackageJson(tmpOutDir, '0.56.0'),
);
const miniApps = [
PackagePath.fromString('first-miniapp@6.0.0'), // same
PackagePath.fromString('second-miniapp@4.0.0'), // upgraded
PackagePath.fromString('fourth-miniapp@1.0.0'), // new
];
await generateComposite({
miniApps,
outDir: tmpOutDir,
pathToYarnLock: pathToSampleYarnLock,
});
assert(yarnCliStub.install.calledOnce);
sinon.assert.callCount(yarnCliStub.add, 4);
assert(yarnCliStub.install.calledBefore(yarnCliStub.add));
});
it('should create index.js', async () => {
// One new, one same, one upgrade
yarnCliStub.install.callsFake(() =>
createCompositeNodeModulesReactNativePackageJson(tmpOutDir, '0.56.0'),
);
const miniApps = [PackagePath.fromString('first-miniapp@6.0.0')];
await generateComposite({
miniApps,
outDir: tmpOutDir,
pathToYarnLock: pathToSampleYarnLock,
});
assert(fs.existsSync(path.join(tmpOutDir, 'index.js')));
});
});
const fakeYarnInit = (rootDir: string, rnVersion: string) => {
fs.writeFileSync(
path.join(tmpOutDir, 'package.json'),
JSON.stringify({ dependencies: {} }),
);
createCompositeNodeModulesReactNativePackageJson(rootDir, rnVersion);
};
describe('generateComposite [without yarn lock]', () => {
// For the following tests, because in the case of no yarn lock provided
// the package.json is created when running first yarn add, and we are using
// a yarnAdd stub that is not going to run real yarn add, we need to create the
// expected package.json beforehand
it('should call yarn add for each MiniApp', async () => {
const miniApps = [
PackagePath.fromString('first-miniapp@6.0.0'), // same
PackagePath.fromString('second-miniapp@4.0.0'), // upgraded
PackagePath.fromString('fourth-miniapp@1.0.0'), // new
];
yarnCliStub.init.callsFake(() => fakeYarnInit(tmpOutDir, '0.57.0'));
await generateComposite({ miniApps, outDir: tmpOutDir });
sinon.assert.callCount(yarnCliStub.add, 5);
});
it('should create index.js', async () => {
// One new, one same, one upgrade
const miniApps = [PackagePath.fromString('first-miniapp@6.0.0')];
yarnCliStub.init.callsFake(() => fakeYarnInit(tmpOutDir, '0.57.0'));
await generateComposite({ miniApps, outDir: tmpOutDir });
assert(fs.existsSync(path.join(tmpOutDir, 'index.js')));
});
it('should create .babelrc with react-native preset for RN < 0.57.0', async () => {
// One new, one same, one upgrade
const miniApps = [PackagePath.fromString('first-miniapp@6.0.0')];
yarnCliStub.init.callsFake(() => fakeYarnInit(tmpOutDir, '0.56.0'));
await generateComposite({ miniApps, outDir: tmpOutDir });
assert(fs.existsSync(path.join(tmpOutDir, '.babelrc')));
const babelRc: any = JSON.parse(
fs.readFileSync(path.join(tmpOutDir, '.babelrc')).toString(),
);
assert(babelRc.presets.includes('react-native'));
});
it('should create .babelrc with module:metro-react-native-babel-preset preset for RN >= 0.57.0', async () => {
// One new, one same, one upgrade
const miniApps = [PackagePath.fromString('first-miniapp@6.0.0')];
yarnCliStub.init.callsFake(() => fakeYarnInit(tmpOutDir, '0.57.0'));
await generateComposite({ miniApps, outDir: tmpOutDir });
assert(fs.existsSync(path.join(tmpOutDir, '.babelrc')));
const babelRc: any = JSON.parse(
fs.readFileSync(path.join(tmpOutDir, '.babelrc')).toString(),
);
assert(
babelRc.presets.includes('module:metro-react-native-babel-preset'),
);
});
});
describe('applyYarnResolutions', () => {
it('should add resolutions field to the package.json', async () => {
const packageJsonPath = path.join(tmpOutDir, 'package.json');
fs.writeFileSync(packageJsonPath, '{}');
const resolutions = {
'c/**/left-pad': '1.1.2',
'd2/left-pad': '1.1.1',
};
await applyYarnResolutions({ cwd: tmpOutDir, resolutions });
const packageJson: any = JSON.parse(
fs.readFileSync(packageJsonPath).toString(),
);
expect(packageJson.resolutions).to.be.an('object');
});
it('should add correct resolutions to the package.json', async () => {
const packageJsonPath = path.join(tmpOutDir, 'package.json');
fs.writeFileSync(packageJsonPath, '{}');
const resolutions = {
'c/**/left-pad': '1.1.2',
'd2/left-pad': '1.1.1',
};
await applyYarnResolutions({ cwd: tmpOutDir, resolutions });
const packageJson: any = JSON.parse(
fs.readFileSync(packageJsonPath).toString(),
);
expect(packageJson.resolutions).deep.equal(resolutions);
});
it('should call yarn install', async () => {
const packageJsonPath = path.join(tmpOutDir, 'package.json');
fs.writeFileSync(packageJsonPath, '{}');
const resolutions = {
'c/**/left-pad': '1.1.2',
'd2/left-pad': '1.1.1',
};
await applyYarnResolutions({ cwd: tmpOutDir, resolutions });
assert(yarnCliStub.install.calledOnce);
});
});
describe('generateComposite [with custom extraNodeModules]', () => {
it('should create custom extraNodeModules in Metro config', async () => {
yarnCliStub.init.callsFake(() => fakeYarnInit(tmpOutDir, '0.57.0'));
await generateComposite({
metroExtraNodeModules: {
'pkg-a': '@scope/new-pkg-a',
'pkg-b': path.join('/absolute/path/to/new-pkg-b'),
},
miniApps: [PackagePath.fromString('test-miniapp@1.0.0')],
outDir: tmpOutDir,
});
fs.mkdirpSync(
path.join(tmpOutDir, 'node_modules/metro-config/src/defaults'),
);
fs.mkdirpSync(
path.join(tmpOutDir, 'node_modules/react-native-svg-transformer'),
);
fs.writeFileSync(
path.join(
tmpOutDir,
'node_modules/metro-config/src/defaults/blacklist',
),
'module.exports = () => {};\n',
);
fs.writeFileSync(
path.join(
tmpOutDir,
'node_modules/react-native-svg-transformer/index.js',
),
'',
);
assert(fs.existsSync(path.join(tmpOutDir, 'metro.config.js')));
const metroConfig = require(path.join(tmpOutDir, 'metro.config.js'));
expect(metroConfig.resolver).to.be.an('object');
expect(metroConfig.resolver.extraNodeModules).to.be.an('object');
expect(metroConfig.resolver.extraNodeModules)
.to.have.property('pkg-a')
.which.equals(path.join(tmpOutDir, 'node_modules', '@scope/new-pkg-a'));
expect(metroConfig.resolver.extraNodeModules)
.to.have.property('pkg-b')
.which.equals(path.join('/absolute/path/to/new-pkg-b'));
});
});
}); | the_stack |
import { ChartAxisGeneralSetConfig, ChartAxisBoxPlotSetConfig, ChartAxisBubblePackSetConfig, ChartAxisGeneralSetData, ChartAxisBoxPlotSetData, ChartAxisBubblePackSetData } from "./ChartAxisSets"
import { Padding, Orient } from "./General"
import { ChartAxisGraphData } from "./ChartAxisGraphs"
import { SymbolType, Axis, AxisScale, AxisTimeInterval } from "d3"
import { ChartAxisValueData } from "./ChartAxisValues"
/**
* Axis chart graph annotation interface.
*/
interface Annotation {
/**
* Annotation x position.
*/
x: number | string
/**
* Annotation y position.
*/
y: number | string
/**
* Annotation x2 position.
*/
x2?: number | string
/**
* Annotation y2 position.
*/
y2?: number | string
/**
* Annotation z position.
* @default 'front'
*/
z?: 'front' | 'back'
/**
* Annotation x type.
* @default 'x'
*/
xType?: 'x' | 'x2'
/**
* Annotation y type.
* @default 'y'
*/
yType?: 'y' | 'y2'
/**
* Additional attributes can be added to the annotation for reference.
*/
[key: string]: any
}
/**
* Possible domain values type.
*/
type DomainValues = Array<string | number | Date>
/**
* Axis chart, axis config interface.
*/
interface AxisConfig {
/**
* Specify a configured [d3-axis](https://github.com/d3/d3-axis). It's usually better to use the
* following axis configuration properties instead of setting your own.
*/
axis?: Axis<any>
/**
* Axis orientation inside or outside the plane.
* @default 'outer'
*/
orient?: 'inner' | 'outer'
/**
* Axis tick wrap length.
* @default Infinity
*/
wrapLength?: number
/**
* See d3-axis [tickSize](https://github.com/d3/d3-axis#axis_tickSize)
* @default 6
*/
tickSize?: number
/**
* Enable or disable the grid for this axis.
* @default true
*/
showGrid?: boolean
/**
* Sets a label for this axis.
*/
label?: string
/**
* Axis label orientation.
*/
labelOrient?: 'outer start' | 'outer middle' | 'outer end' | 'inner start' | 'inner middle' | 'inner end'
/**
* Pad both sides of the continuous scale by a percent of the domain range. For example [-0.1, 0.2] will
* pad the minimum scale domain by 10% and the upper end by 20%.
*/
linearPadding?: [number, number]
/**
* Pad tick labels from the plan for this axis. See d3-axis [tickPadding](https://github.com/d3/d3-axis#axis_tickPadding)
* @default 3
*/
tickPadding?: number
/**
* Specify the tick count or axis time interval for the axis. See d3-axis [ticks](https://github.com/d3/d3-axis#axis_ticks)
*/
ticks?: AxisTimeInterval | number
/**
* Specify the tick format. See d3-axis [tickFormat](https://github.com/d3/d3-axis#axis_tickFormat)
*/
tickFormat?: (n: number | { valueOf(): number }) => string
/**
* Specify the tick values instead of automatically generating them. See d3-axis [tickValues](https://github.com/d3/d3-axis#axis_tickValues)
*/
tickValues?: Array<any>
/**
* Axis' scale config interface.
*/
scale?: {
/**
* D3 scale instance or descriptor string.
*/
type?: 'band' | 'point' | 'linear' | 'time' | 'pow' | 'log' | AxisScale<any>
/**
* See [d3-scale](https://github.com/d3/d3-scale) for different scale type domains.
*/
domain?: DomainValues | ((values: DomainValues) => DomainValues)
/**
* See d3-scale [continuous clamp](https://github.com/d3/d3-scale#continuous_clamp)
* @default false
*/
clamp?: boolean
/**
* See d3-scale [continuous nice](https://github.com/d3/d3-scale#continuous_nice)
* @default false
*/
nice?: boolean
/**
* See d3-scale [power exponent](https://github.com/d3/d3-scale#pow_exponent)
* @default 1
*/
exponent?: number
/**
* See d3-scale [log base](https://github.com/d3/d3-scale#log_base)
* @default 10
*/
base?: number
/**
* See d3-scale [symlog constant](https://github.com/d3/d3-scale#symlog_constant)
* @default 1
*/
constant?: number
/**
* Force domain bounds for [continuous scales](https://github.com/d3/d3-scale#_continuous).
* This is useful if you want the domain min OR max to be automatic but the other to be fixed.
*/
forceBounds?: {
/**
* Force minimum domain bound for [continuous scales](https://github.com/d3/d3-scale#_continuous)
*/
min?: number
/**
* Force maximum domain bound for [continuous scales](https://github.com/d3/d3-scale#_continuous)
*/
max?: number
}
}
}
/**
* Axis chart group config interface.
*/
export interface ChartAxisGroupConfig {
/**
* The group label, should match the corresponding graph's group property.
*/
label: string
/**
* The group color property. By default this will defer to the graph color.
*/
color?: string
/**
* Legend icon symbol type. This can either be a font awesome character code
* (e.g. '\uf111' for a circle), [d3 symbol](https://github.com/d3/d3-shape#symbols)
* or [d2b symbol](https://docs.d2bjs.org/shape/symbols.html). If set, this will
* override the legend's icon property.
*/
legendIcon?: string | SymbolType
/**
* Initially hides this group. This value will be modified internally when interacting with the chart legend.
*/
hidden?: boolean
}
/**
* Chart axis config interface.
*/
export interface ChartAxisConfig {
/**
* Chart annotations. Refer to the d3-annotation [docs](https://d3-annotation.susielu.com) for
* additional annotation configuration.
*/
annotations?: Array<Annotation>
/**
* Axis chart groups. Groups are used to group multiple graph's together on the legend.
*/
groups?: Array<ChartAxisGroupConfig>
/**
* Event hook for d2b charts. Will be after the chart is rendered.
* Note: Transitions may still occur after this lifecycle hook fires.
*/
updated?: (this: HTMLElement, data: ChartAxisData) => void
/**
* The pixel size of the chart.
*/
size?: {
/**
* The pixel width of the chart. If not given, the container width will be used.
*/
width?: number,
/**
* The pixel height of the chart. If not given, the container height will be used.
*/
height?: number
}
/**
* The internal chart duration in miliseconds.
* @default 250
*/
duration?: number
/**
* Chart axis group color or accessor function.
* @default d => colorGenerator(d.label)
*/
groupColor?: string | ((data: ChartAxisGraphData) => string)
/**
* Chart axis graph color or accessor function.
* @default d => colorGenerator(d.label)
*/
graphColor?: string | ((data: ChartAxisGroupConfig) => string)
/**
* The chart's inner padding (excluding the legend) in pixels.
* @default 10
*/
chartPadding?: number | Padding
/**
* The chart's outer padding (including the legend) in pixels.
* @default 10
*/
padding?: number | Padding
/**
* The chart's plane padding. If set to null the padding will be computed automatically based on the axis label and tick sizes.
* @default null
*/
planePadding?: null | number | Padding
/**
* The chart's plane margin. This is useful if additional space is required for axis labels or ticks.
* @default 10
*/
planeMargin?: number | Padding
/**
* Chart legend configuration options.
*/
legend?: {
/**
* Enable or disable the legend.
* @default true
*/
enabled?: boolean
/**
* Legend orientation, relative to the chart.
* @default 'bottom'
*/
orient?: Orient
/**
* Whether the legend will hide / show arcs on click.
* @default true
*/
clickable?: boolean
/**
* Whether the legend will hide / show arcs on dblclick.
* @default true
*/
dblclickable?: boolean
/**
* Legend icon symbol type. This can either be a font awesome character code
* (e.g. '\uf111' for a circle), [d3 symbol](https://github.com/d3/d3-shape#symbols)
* or [d2b symbol](https://docs.d2bjs.org/shape/symbols.html). This can also be provided
* as an accessor function to the graph / group data.
* @default d3.symbolCircle
*/
icon?: string | SymbolType | ((data: ChartAxisGraphData | ChartAxisGroupConfig) => string | SymbolType)
}
/**
* Chart tooltip configuration options.
*/
tooltip?: {
/**
* Tooltip will show values near the horizontal position of the cursor.
* @default true
*/
trackX?: boolean
/**
* Tooltip will show values near the vertical position of the cursor. (useful for horizontally oriented graphs or
* charts that have a lot of y values stacked on the same discrete x values)
* @default false
*/
trackY?: boolean
/**
* The tooltip threshold for the cursor distant to the nearest axis chart value.
* @default 50
*/
threshold?: number
/**
* Html content to be displayed in the tooltip's title.
* @default (values) => {
* const first = values[0].value
* return `${first.x, first.x1, first.median}`
* }
*/
title?: null | string | ((values: Array<{value: ChartAxisValueData, graph: ChartAxisGraphData}>) => string | null)
/**
* Html content to be displayed in each of the tooltip's rows.
* @default (value, graph) => {
* return `${graph.label}: ${orEquals(value.y, value.y1, value.median)}`
* }
*/
row?: null | string | ((value: ChartAxisValueData, graph: ChartAxisGraphData) => string | null)
}
/**
* X-axis (bottom) config
*/
x?: AxisConfig
/**
* Y-axis (left) config
*/
y?: AxisConfig
/**
* X2-axis (top) config
*/
x2?: AxisConfig
/**
* Y2-axis (right) config
*/
y2?: AxisConfig
/**
* Axis chart graph set configuration.
*/
sets?: Array<ChartAxisGeneralSetConfig | ChartAxisBoxPlotSetConfig | ChartAxisBubblePackSetConfig>
}
/**
* Chart axis data interface.
*/
export interface ChartAxisData extends ChartAxisConfig {
/**
* Axis chart graph set data.
*/
sets: Array<ChartAxisGeneralSetData | ChartAxisBoxPlotSetData | ChartAxisBubblePackSetData>
} | the_stack |
import $ from '../util/domUtil';
import {em} from '../em';
import animationUtil from '../util/animationUtil';
import constant from '../constant';
import {Col} from '../Col'
import {Picker} from '../Picker'
import {IOptions} from '../API'
import { AWheel } from './AWheel';
declare function require<T>(name: string): T
const tick = require<{(): {play()}}>("../tick/tick")();
export class Wheel extends AWheel{
///////////////////滚轮显示属性
//最大位移
private maxDistance = 0;
//最小位移,设置可选项列表后需重新计算
private minDistance = 0;
//获取0.01em的实际像素值
private em: () => number = em;
//获得控件到body最顶端的距离,计算触摸事件的offsetY时候使用
private offsetTop = 0;
////////////////////滚动属性
//滚轮转动前初始的位移,用于计算滚轮是否转动过
private originalDistance = 0;
//一次拖动过程中滚轮被转动的最大位移
private lastIndexDistance = 0;
//当前的刻度,计算发声时候会用到。发声要进过一个刻度线或者达到一个新刻度新才会发声。所以需要记录上一次的刻度线。
private changeMaxDistance = 0;
//当前滚轮位移
private distance = 0;
//记录惯性滑动动画的id
private animationId = -1;
//速度,供触摸离开时候的惯性滑动动画使用
private speed = 0;
//当前时间戳,主要是计算转动速度使用的
private timeStamp = 0;
//记录上一次触摸节点的offsetY,主要是是计算转动速度使用的
private lastY = 0;
//是否开始触摸,主要给鼠标事件使用
private isDraging = false;
constructor(picker: Picker, col: Col, option: IOptions, index: number){
super()
///////////////////主要属性
//picker对象
this.picker = picker;
//option对象
this.option = option;
//记录当前滚轮是容器中第几个滚轮
this.index = index;
//转轮主体
this.dom = $(
`<div class="picker-wheel">
<div class="picker-label"><span class="picker-text"></span></div>
<ul></ul>
<div class="picker-label"><span class="picker-text"></span></div>
</div>`).css('height', constant.WHEEL_HEIGHT / 100 + 'em');
//转轮上面标签的容器,同时也是转动的轴
this.contains = this.dom.find('ul');
this.setDistance(0)
////////////////////可选项属性
//如果items数组里的值是对象,其中显示的key
this.labelKey = col.labelKey;
//如果items数组里的值是对象,其中值的key
this.itemValueKey = col.valueKey;
////////////////////注册dom事件
var that = this;
//注册拖拽开始事件
function startDrag(event) {
//计算offsetTop,为计算触摸事件的offset使用
var target = event.currentTarget;
that.offsetTop = 0;
while (target){
that.offsetTop += target.offsetTop;
var target = target.parentElement;
}
var offsetY = event.touches ? event.touches[0].clientY - that.offsetTop : event.clientY - that.offsetTop;
that.startDrag(offsetY);
}
this.dom[0].addEventListener("touchstart", startDrag);
this.dom[0].addEventListener("mousedown", startDrag);
//注册拖拽事件
function drag(event){
var offsetY = event.touches ? event.touches[0].clientY - that.offsetTop : event.clientY - that.offsetTop;
that.drag(offsetY);
}
this.dom[0].addEventListener("touchmove", drag);
this.dom[0].addEventListener("mousemove", drag);
//注册拖拽结束事件
function endDrag(){
that.endDrag();
}
this.dom[0].addEventListener("touchend", endDrag);
this.dom[0].addEventListener("mouseup", endDrag);
this.dom[0].addEventListener("mouseleave", endDrag);
// 注册滚轮事件
this.initMouseWheel()
//设置标签
this.setSuffix(col.suffix);
this.setPrefix(col.prefix);
this.setOptions(col.options, null, true)
}
/**
* 开始拖拽
* @param {number} offsetY 当前用户手指(鼠标)的y坐标
*/
startDrag(offsetY: number) {
//记录触摸相关信息,为下一步计算用.计算时候,要将坐标系移至中心,并将单位转为em
this.lastY = (constant.WHEEL_HEIGHT / 2 - offsetY / this.em()) * -1 ;
this.timeStamp = Date.now();
this.isDraging = true;
this.offsetTop = this.dom[0].offsetTop;
this.originalDistance = this.distance;
this.changeMaxDistance = 0;
this.lastIndexDistance = this.selectedIndex;
for(var parent = this.dom[0].parentElement;parent; parent = parent.parentElement){
this.offsetTop += parent.offsetTop;
}
//终止之前的动画
animationUtil.stopAnimation(this.animationId);
}
/**
* 拖拽
* @param {number} offsetY 当前用户手指(鼠标)的y坐标
*/
drag(offsetY: number) {
if(!this.isDraging){
return;
}
//根据触摸位移(鼠标移动位移)计算位移变化量
//现将坐标系移植中心,并将单位转为vm
var y = (constant.WHEEL_HEIGHT / 2 - offsetY / this.em()) * -1;
//计算位移,因为z轴有透视,所以位移量不是真正的曲面的位移量,要做一次透视变换
var changeDistance = this.lastY - y
var distance = changeDistance + this.distance;
//记录滚轮滚动的最大位移
this.changeMaxDistance = Math.max( Math.abs( this.originalDistance - distance ), this.changeMaxDistance);
//记录当前位移
this.setDistance(distance);
//计算并记录速度
this.lastY = y;
if(changeDistance){
this.speed = changeDistance / (Date.now() - this.timeStamp);
} else{
this.speed = 0;
}
this.timeStamp = Date.now();
}
/**
* 拖拽结束
*/
endDrag(): void {
if(!this.isDraging){
return;
}
//速度*4,做均减少运动,计算滚动后的Distance。之所以乘4是根据偏移效果经验得到的
var changeDistance = this.speed * Math.abs( this.speed) * 8 * constant.WHEEL_TRANSITION_TIME;
var distance = changeDistance + this.distance;
//根据位移计算最终的被选值
var selectedIndex = this.calcSelectedIndexByDistance(distance);
//开启动画,选中被选中
this.selectIndex(selectedIndex, true);
//计算完成,清空速度相关变量,并去除之前的动画效果
this.isDraging = false;
this.lastY = 0;
this.speed = 0;
}
/////////////////////////////////设置相关
/**
* 生成用户可选的标签
* @param {any[]} list 用户可选项数组
* @param {*} selectedValue 默认值
* @param {boolean} [isInti=false] 是否是初始化,初始化不执行设置默认值操作
*/
setOptions(list: any[], selectedValue: any, isInti: boolean = false) {
var that = this;
list = list || [];
if(Array.isArray(list)){
//清空容器
that.contains.html("");
this.list = list;
} else {
throw new TypeError("list is not a array.")
}
//计算valueHashMap
this.valueHashMap = {};
//计算最小位移
this.maxDistance = constant.WHEEL_ITEM_HIGHT * (Math.max(0, this.list.length - 1) );
//生成滚轮的标签
//标签的index
var i = 0,
//标签显示值
label;
this.list.forEach(function(item,index){
//如果是对象,取labelKey对应值显示。否则直接显示它本身
if(typeof item === 'object'){
label = item[that.labelKey];
that.valueHashMap[item[that.itemValueKey]] = i;
} else {
label = item;
that.valueHashMap[item] = i;
}
//创建label的显示dom,并计算他在容器中的位置(位移)
var li = $("<li></li>").css('top', `${constant.WHEEL_ITEM_HIGHT / 100 * i}em`);
li.append($('<span class="picker-text"></span>').text(label));
var distance = constant.WHEEL_ITEM_HIGHT * -index;
//将标签的位移保存到其dom中
li.data("distance", distance);
//将标签的index保存到其dom中
li.data("index", i);
//将标签的dom放到contains上,contains的事件全部委托于容器,即标签不监听事件
that.contains.append(li);
//增加点击选择功能
var clickHandle = function (event) {
if(that.changeMaxDistance < 0.1) {
//计算完成,清空速度相关变量,并去除之前的动画效果
that.isDraging = false;
that.lastY = 0;
that.speed = 0;
that.selectIndex(index, true);
event.stopPropagation();
event.preventDefault();
}
}
li[0].addEventListener('mouseup',clickHandle);
li[0].addEventListener('touchend',clickHandle);
i++;
});
if(isInti){
if(list.length > 0 ){
this.selectedIndex = 0;
if(typeof list[0] === 'object'){
this.selectedValue = this.list[0][this.itemValueKey];
} else {
this.selectedValue = this.list[0];
}
} else {
this.selectedIndex = -1;
this.selectedValue = undefined;
}
return;
}
//设置被选值。如果用户给定被选值,使用给定被选值。如果没有且之前有被选值,并仍在新options里面,保存之前的值。都没有返回0
if(list.length > 0 ){
if(selectedValue != null && this.valueHashMap[selectedValue] != null){
this.selectOption(selectedValue);
} else if(this.valueHashMap[this.selectedValue] != null){
this.selectOption(this.selectedValue);
} else {
this.selectIndex(0);
}
} else {
this.selectedIndex = -1;
this.selectedValue = undefined;
}
}
/**
* 给定指定备选标签的index,自动设定标签的各个位置
* @param index 要选择的index
* @param showAnimation 是否显示动画,如果显示动画,会用100帧来显示动画
*/
protected selectIndex(index: number, showAnimation = false){
var distance = this.calcDistanceBySelectedIndex(index);
animationUtil.stopAnimation(this.animationId);
if(showAnimation){
//用50帧渲染动画,并使用easeOut,使其有匀减速效果
//当前帧数
var start = 0,
//总帧数
during = 50,
that = this;
//动画渲染函数
var _run = function() {
start++;
var _Distance = animationUtil.easeOut(start, that.distance, distance - that.distance, during);
if(Math.abs(_Distance - distance) < 1){
_Distance = distance;
}
that.setDistance(_Distance);
if (_Distance != distance) {
that.animationId = animationUtil.startAnimation(_run);
} else {
//记录下原有的index,确定选择是否发生了改变
var oldSelectedIndex = that.selectedIndex;
that.selectedIndex = index;
that.selectedValue = that.list[index];
if(typeof that.selectedValue == 'object'){
that.selectedValue = that.selectedValue[that.itemValueKey];
}
if(oldSelectedIndex != that.selectedIndex)
that.toggleSelected(that.selectedIndex, that.selectedValue);
}
};
//启动动画
that.animationId = animationUtil.startAnimation(_run);
} else {
//记录下原有的index,确定选择是否发生了改变
var oldSelectedIndex = this.selectedIndex;
//如果不显示动画,直接赋值
this.setDistance(distance);
this.selectedIndex = index;
this.selectedValue = this.list[index];
if(typeof this.selectedValue == 'object'){
this.selectedValue = this.selectedValue[this.itemValueKey];
}
if(oldSelectedIndex != this.selectedIndex)
this.toggleSelected(this.selectedIndex, this.selectedValue);
}
}
/**
* 给定指定位移,自动设定标签的各个位置
* @param {number} distance 要转到的位移
* @returns {number} 修正后的位移,即最终的实际位移
*/
private setDistance(distance: number): number{
//修正位移,要求位移不能大于maxDistance,不能小于minDistance
distance = this.rangeDistance(distance);
// 如果位移变化经过刻度,则放声
if(this.option.hasVoice && this.picker.visible){
var lastIndexDistance = this.lastIndexDistance;
var index = this.calcSelectedIndexByDistance(distance);
if(lastIndexDistance != index ){
if(this.option.hasVoice){
tick.play()
}
}
this.lastIndexDistance = index;
}
var translateValue = "translate3d(0, " + (constant.WHEEL_HEIGHT / 2 - constant.WHEEL_ITEM_HIGHT / 2 - distance) / 100 + "em, 0)"
this.contains.css("-webkit-transform", translateValue).css("transform", translateValue)
this.distance = distance;
return distance;
}
/**
* 通过位移计算被选项的id
* @param distance {number} 要计算的位移
* @returns {number} 被选项id
*/
private calcSelectedIndexByDistance(distance: number): number{
distance = this.rangeDistance(distance);
return Math.round(Math.abs(distance / constant.WHEEL_ITEM_HIGHT));
}
/**
* 通过位移计算被选项的id
* @param Distance {number} 要计算的位移
* @returns {number} 被选项id
*/
private calcDistanceBySelectedIndex(index: number): number {
return index * constant.WHEEL_ITEM_HIGHT;
}
/**
* 限制位移超过极限值
* @param distance {number} 要计算的位移
* @returns {number} 被选项id
*/
private rangeDistance(distance: number): number {
//修正位移,要求位移不能大于maxDistance,不能小于minDistance
distance = Math.max(this.minDistance, distance);
distance = Math.min(this.maxDistance, distance);
return distance;
}
/**
* 获取被选值
*/
getValue(){
return this.selectedValue;
}
/////////////////////////////设置前缀后缀
/**
* 设置后缀
* @param text 后缀显示的文本
*/
private setSuffix(text) {
this.dom.find('.picker-label .picker-text').eq(1).text(text);
}
/**
* 设置前缀
* @param text 前缀显示的文本
*/
private setPrefix(text) {
this.dom.find('.picker-label .picker-text').eq(0).text(text);
}
} | the_stack |
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class IdentifyFileTypeService {
constructor() { }
/*
Regular Expression Identification for some common file signatures
Manually compiled from data found at https://en.wikipedia.org/wiki/List_of_file_signatures
*/
identifyFileType(hex: string): string[][] {
/*
Input: hex string
Output: Array containing filetype ID and descriptoin
*/
var results: string[][] = [];
for (let details of this.fileSigs) {
let extension: string = details[0];
let description: string = details[1];
let regexp: RegExp = details[2];
if (hex.match(regexp)) {
results.push([extension, description]);
}
}
return results;
}
//ID - Description - Regex
fileSigs: any[][] = [
['TGA', "Truevision TGA Bitmap 2", new RegExp("^54525545564953494F4E2D5846494C452E00", "i")],
['pcap', "Libpcap File Format", new RegExp("^(?:a1b2c3d4|d4c3b2a1)", "i")],
['pcapng', "PCAP Next Generation Dump File Format", new RegExp("^0a0d0d0a", "i")],
['rpm', "RedHat Package Manager (RPM) package", new RegExp("^edabeedb", "i")],
['sqlitedb', "SQLite Database", new RegExp("^53514c69746520666f726d6174203300", "i")],
['bin', "Amazon Kindle Update Package", new RegExp("^53503031", "i")],
['DBA', "Palm Desktop Calendar Archive", new RegExp("^BEBAFECA", "i")],
['DBA', "Palm Desktop To Do Archive", new RegExp("^00014244", "i")],
['TDA', "Palm Desktop Calendar Archive", new RegExp("^00014454", "i")],
['3gp', "3rd Generation Partnership Project 3GPP and 3GPP2 multimedia files", new RegExp("^(?:..){4}667479703367", "i")],
['tar.z', "Compressed File (Often tar zip) using Lempel-Ziv-Welch algorithm", new RegExp("^1F9D", "i")],
['tar.z', "Compressed File (Often tar zip) using LZH algorithm", new RegExp("^1FA0", "i")],
['bac', "File or tape containing a backup done with AmiBack on an Amiga", new RegExp("^4241434B4D494B454449534B", "i")],
['bz2', "Compressed file using Bzip2 algorithm", new RegExp("^425A68", "i")],
['gif', "Image file encoded in the Graphics Interchange Format (GIF)", new RegExp("^47494638(?:37|39)61", "i")],
['tiff', "Tagged Image File Format", new RegExp("^(?:49492A00|4D4D002A)", "i")],
['cr2', "Canon RAW Format Version 2 (Based on TIFF)", new RegExp("^49492A00100000004352", "i")],
['cin', "Kodak Cineon image", new RegExp("^802A5FD7", "i")],
['rnc', "Compressed file using Rob Northen Compression algorithm (v1)", new RegExp("^524E4301", "i")],
['rnc', "Compressed file using Rob Northen Compression algorithm (v2)", new RegExp("^524E4302", "i")],
['dpx', "SMPTE DPX Image", new RegExp("^(?:53445058|58504453)", "i")],
['exr', "OpenEXR Image", new RegExp("^762F3101", "i")],
['bpg', "Better Portable Graphics", new RegExp("^425047FB", "i")],
['jpg', "JPEG Raw", new RegExp("^FFD8FF(?:DB|EE)", "i")],
['jpg', "JPEG in JFIF format", new RegExp("^FFD8FFE000104A4649460001", "i")],
['jpg', "JPEG in Exif format", new RegExp("^FFD8FFE1....457869660000", "i")],
['ilbm', "IFF Interleaved Bitmap Image", new RegExp("^464F524D(?:.){8}494C424D", "i")],
['8svx', "IFF 8-Bit Sampled Voice", new RegExp("^464F524D(?:.){8}38535658", "i")],
['acbm', "Amiga Contiguous Bitmap", new RegExp("^464F524D(?:.){8}4143424D", "i")],
['anbm', "IFF Animated Bitmap", new RegExp("^464F524D(?:.){8}414E424D", "i")],
['anim', "IFF CEL Animation", new RegExp("^464F524D(?:.){8}414E494D", "i")],
['faxx', "IFF Facsimile Image", new RegExp("^464F524D(?:.){8}46415858", "i")],
['ftxt', "IFF Formatted Text", new RegExp("^464F524D(?:.){8}46545854", "i")],
['smus', "IFF Simple Musical Score", new RegExp("^464F524D(?:.){8}534D5553", "i")],
['cmus', "IFF Musical Score", new RegExp("^464F524D(?:.){8}434D5553", "i")],
['yuvn', "IFF YUV Image", new RegExp("^464F524D(?:.){8}5955564E", "i")],
['iff', "Amiga Fantavision Movie", new RegExp("^464F524D(?:.){8}46414E54", "i")],
['aiff', "Audio Interchange File Format", new RegExp("^464F524D(?:.){8}41494646", "i")],
['idx', "Index file to a file or tape containing a backup done with AmiBack on an Amiga.", new RegExp("^494E4458", "i")],
['lz', "lzip compressed file", new RegExp("^4C5A4950", "i")],
['exe', "DOS MZ executable file format and its descendants (including NE and PE)", new RegExp("^4D5A", "i")],
['zip', "zip file format or format based on it, e.g. jar, zip, jar, odt, ods, odp, docx, xlsx, pptx, vsdx, apk, aar", new RegExp("^504B0304", "i")],
['zip', "EMPTY zip file format or format based on it, e.g. jar, zip, jar, odt, ods, odp, docx, xlsx, pptx, vsdx, apk, aar", new RegExp("^504B0506", "i")],
['zip', "SPANNED zip file format or format based on it, e.g. jar, zip, jar, odt, ods, odp, docx, xlsx, pptx, vsdx, apk, aar", new RegExp("^504B0708", "i")],
['rar', "RAR archive version 1.50 onwards", new RegExp("^526172211A0700", "i")],
['rar', "RAR archive version 5.0 onwards", new RegExp("^526172211A070100", "i")],
['elf', "Executable and Linkable Format (ELF)", new RegExp("^7F454C46", "i")],
['png', "Image encoded in the Portable Network Graphics format", new RegExp("^89504E470D0A1A0A", "i")],
['class', "Java class file", new RegExp("^CAFEBABE", "i")],
['txt', "UTF-8 encoded Unicode byte order mark, commonly seen in text files.", new RegExp("^EFBBBF", "i")],
['machO32', "Mach-O binary (32-bit)", new RegExp("^FEEDFACE", "i")],
['machO32', "Mach-O binary (Reverse byte ordering scheme, 32-bit)", new RegExp("^CEFAEDFE", "i")],
['machO64', "Mach-O binary (64-bit)", new RegExp("^FEEDFACF", "i")],
['machO64', "Mach-O binary (Reverse byte ordering scheme, 64-bit)", new RegExp("^CFFAEDFE", "i")],
['jks', "JavakeyStore (JKS)", new RegExp("^FEEDFEED", "i")],
['ps', "PostScript", new RegExp("^25215053", "i")],
['pdf', "PDF document", new RegExp("^255044462D", "i")],
['asf', "Advanced Systems Format", new RegExp("^3026B2758E66CF11A6D900AA0062CE6C", "i")],
['sdi', "System Deployment Image, a disk image format used by Microsoft", new RegExp("^2453444930303031", "i")],
['ogg', "Ogg, an open source media container format", new RegExp("^4F676753", "i")],
['psd', "Photoshop Document file, Adobe Photoshop's native file format", new RegExp("^38425053", "i")],
['wav', "Waveform Audio File Format", new RegExp("^52494646(?:.){8}57415645", "i")],
['avi', "Audio Video Interleave video format", new RegExp("^52494646(?:.){8}41564920", "i")],
['mp3', "MPEG-1 Layer 3 file without an ID3 tag or with an ID3v1 tag", new RegExp("^FF FB", "i")],
['mp3', "MP3 file with an ID3v2 container", new RegExp("^494433", "i")],
['bmp', "BMP file, a bitmap format", new RegExp("^424D", "i")],
['iso', "ISO9660 CD/DVD image file", new RegExp("^(?:(?:..){32768})(?:^4344303031)", "i")],
['fits', "Flexible Image Transport System", new RegExp("^53494D504C4520203D(?:20){20}4344303031", "i")], //TODO: Test this
['flac', "Free Lossless Audio Codec", new RegExp("^664C6143", "i")],
['midi', "MIDI sound file", new RegExp("^4D546864", "i")],
['ms', "Compound File Binary Format: Used by older versions of Microsoft Office, e.g. xls, ppt, msg", new RegExp("^D0CF11E0A1B11AE1", "i")],
['dex', "Dalvik Executable", new RegExp("^6465780A30333500", "i")],
['vmdk', "VMDK Files", new RegExp("^4B444D", "i")],
['crx', "Google Chrome extension or packaged app", new RegExp("^43723234", "i")],
['fh8', "Freehand 8 document", new RegExp("^41474433", "i")],
['cwk', "AppleWorks 5 document", new RegExp("^05070000424F424F0507(?:00){11}01", "i")],
['cwk', "AppleWorks 6 document", new RegExp("^06070000424F424F0607(?:00){11}01", "i")],
['toast', "Roxio Toast disc image file, also some .dmg-files begin with same bytes", new RegExp("^(?:455202000000|8B455202000000)", "i")],
['dmg', "Apple Disk Image file", new RegExp("^7801730D626260", "i")],
['xar', "eXtensible ARchive format", new RegExp("^78617221", "i")],
['dat', "Windows Files And Settings Transfer Repository", new RegExp("^504D4F43434D4F43", "i")],
['nes', "Nintendo Entertainment System ROM file", new RegExp("^4E45531A", "i")],
['tar', "tar archive", new RegExp("^7573746172(?:003030|202000)", "i")], //TODO: Fix, needs 0x101 offset
['tox', "Open source portable voxel file", new RegExp("^746F7833", "i")],
['mlv', "Magic Lantern Video file", new RegExp("^4D4C5649", "i")],
['ms', "Windows Update Binary Delta Compression", new RegExp("^44434D0150413330", "i")],
['7z', "7-Zip File Format", new RegExp("^377ABCAF271C", "i")],
['gz', "GZIP compressed file", new RegExp("^1F8B", "i")],
['xz', "XZ compression utility", new RegExp("^FD377A585A0000", "i")],
['lz4', "LZ4 Frame Format", new RegExp("^04224D18", "i")],
['cab', "Microsoft Cabinet file", new RegExp("^4D534346", "i")],
['Q', "Microsoft compressed file in Quantum format, used prior to Windows XP.", new RegExp("^535A444488F02733", "i")],
['flif', "Free Lossless Image Format", new RegExp("^464C4946", "i")],
['webm', "Matroska media container, e.g. mkv, webm, mks, mka, mk3d", new RegExp("^1A45DFA3", "i")],
['stg', "\"SEAN : Session Analysis\" Training file.", new RegExp("^4D494C20", "i")],
['djvu', "DjVu document", new RegExp("^41542654464F524D(?:.){8}444A56", "i")],
['der', "DER encoded X.509 certificate", new RegExp("^3082", "i")],
['dcm', "DICOM Medical File Format", new RegExp("^4449434D", "i")],
['woff', "WOFF File Format 1.0", new RegExp("^774F4646", "i")],
['woff2', "WOFF File Format 2.0", new RegExp("^774F4632", "i")],
['xml', "eXtensible Markup Language when using the ASCII character encoding", new RegExp("^3c3f786d6c20", "i")],
['wasm', "WebAssembly binary format", new RegExp("^0061736d", "i")],
['lep', "Lepton compressed JPEG image", new RegExp("^cf8401", "i")],
['swf', "flash .swf", new RegExp("^4(?:3|6)5753", "i")],
['deb', "linux deb file", new RegExp("^213C617263683E", "i")],
['webp', "Google WebP image file", new RegExp("^52494646(?:.){8}57454250", "i")],
['uboot', "U-Boot / uImage. Das U-Boot Universal Boot Loader.", new RegExp("^27051956", "i")],
['rtf', "Rich Text Format", new RegExp("^7B5C72746631", "i")],
['tape', "Microsoft Tape Format", new RegExp("^54415045", "i")],
// ['ts', "MPEG Transport Stream (MPEG-2 Part 1)", new RegExp("", "i")], //Too slow, has to check for "47" every 188 bytes :(
['m2p', "MPEG Program Stream", new RegExp("^000001BA", "i")],
['mpeg', "MPEG Program/Transport Stream", new RegExp("^000001B(?:A|3)", "i")],
['zlib', "zlib with no/low compression", new RegExp("^7801", "i")],
['zlib', "zlib with default compression", new RegExp("^789C", "i")],
['zlib', "zlib with best compression", new RegExp("^78DA", "i")],
['lzfse', "LZFSE - Lempel-Ziv style data compression algorithm using Finite State Entropy coding. OSS by Apple", new RegExp("^62767832", "i")],
['orc', "Apache ORC (Optimized Row Columnar) file format", new RegExp("^4F5243", "i")],
['avro', "Apache Avro binary file format", new RegExp("^4F626A01", "i")],
['rc', "RCFile columnar file format", new RegExp("^53455136", "i")],
['p25', "PhotoCap Object Templates", new RegExp("^65877856", "i")],
['pcv', "PhotoCap Vector", new RegExp("^5555aaaa", "i")],
['pbt', "PhotoCap Template (pbt, pdt, pea, peb, pet, pgt, pict, pjt, pkt, pmt)", new RegExp("^785634", "i")],
['par', "Apache Parquet columnar file format", new RegExp("^50415231", "i")],
['ez2', "Emulator Emaxsynth samples", new RegExp("^454D5832", "i")],
['ez3', "Emulator III synth samples", new RegExp("^454D5533", "i")],
['luac', "Lua bytecode", new RegExp("^1B4C7561", "i")],
['alias', "macOS file Alias (Symbolic Link)", new RegExp("^626F6F6B(?:00){4}6D61726B(?:00){4}", "i")],
['identifier', "Microsoft Zone Identifier for URL Security Zones", new RegExp("^5B5A6F6E655472616E736665725D", "i")],
['eml', "Email Message var5", new RegExp("^5265636569766564", "i")],
['tde', "Tableau Datasource", new RegExp("^20020162A01EAB0702000000", "i")],
['kdb', "KDB file", new RegExp("^3748030200000000583530394B4559", "i")],
['zst', "Zstandard compressed file", new RegExp("^28B52FFD", "i")],
['ooxml', "Microsoft Office Open XML Format, e.g. DOCX, PPTX, XLSX", new RegExp("^504B030414000600", "i")]
];
} | the_stack |
let workingInput: any = null;
let workingInputTransform: string[] = [];
let stopValidation = false;
import resourcesSpec = require('./resourcesSpec');
import logger = require('./logger');
import parser = require('./parser');
const mockArnPrefix = "arn:aws:mock:region:123456789012:";
import {
awsParameterTypes as parameterTypesSpec,
awsRefOverrides,
awsIntrinsicFunctions,
PrimitiveAttribute,
ListAttribute,
AWSResourcesSpecification,
} from './awsData';
import * as awsData from './awsData';
import * as samData from './samData';
import docs = require('./docs');
import util = require('util');
import CustomError = require('./util/CustomError');
import sms = require('source-map-support');
sms.install();
const clone = require('clone');
const mergeOptions = require('merge-options');
const arrayIntersection = require('array-intersection');
const shajs = require('sha.js');
require('./util/polyfills');
export type ParameterValue = string | string[];
export type ImportValue = ParameterValue;
let parameterRuntimeOverride: {[parameter: string]: ParameterValue | undefined} = {};
let importRuntimeOverride: {[parameter: string]: ImportValue | undefined} = {};
// Todo: Allow override for RefOverrides ex. Regions
export interface ErrorRecord {
message: string,
resource: string,
documentation: string
}
export interface ErrorObject {
templateValid: boolean,
errors: {
crit: ErrorRecord[],
warn: ErrorRecord[],
info: ErrorRecord[]
},
outputs: {[outputName: string]: string},
exports: {[outputName: string]: string}
}
let errorObject: ErrorObject = {
"templateValid": true,
"errors": {
"info": [],
"warn": [],
"crit": []
},
"outputs": {},
"exports": {}
};
export function resetValidator(){
errorObject = {"templateValid": true, "errors": {"info": [], "warn": [], "crit": []}, outputs: {}, exports: {}};
workingInput = null;
workingInputTransform = [];
stopValidation = false;
parameterRuntimeOverride = {};
importRuntimeOverride = {};
};
export interface ValidateOptions {
/**
* List of parameters for which guessing is allowed.
* undefined implies all parameters can be guessed.
*/
guessParameters: string[] | undefined;
}
const defaultValidateOptions: ValidateOptions = {
guessParameters: undefined
};
export function validateFile(path: string, options?: Partial<ValidateOptions>){
// Convert to object, this will throw an exception on an error
workingInput = parser.openFile(path);
// Let's go!
return validateWorkingInput(options);
};
export function validateJsonObject(obj: any, options?: Partial<ValidateOptions>){
workingInput = obj;
return validateWorkingInput(options);
};
export function addParameterValue(parameter: string, value: ParameterValue){
addParameterOverride(parameter, value);
};
export function addImportValue(parameter: string, value: ImportValue){
addImportOverride(parameter, value);
}
export function addPseudoValue(parameter: string, value: string){
// Silently drop requests to change AWS::NoValue
if(parameter == 'AWS::NoValue') {
return;
}
// Only process items which are already defined in overrides
if(parameter in awsRefOverrides){
// Put NotificationARNs in an array if required
if(parameter == 'AWS::NotificationARNs'){
if(awsRefOverrides['AWS::NotificationARNs'][0] == 'arn:aws:sns:us-east-1:123456789012:MyTopic'){
awsRefOverrides['AWS::NotificationARNs'][0] = value;
}else{
awsRefOverrides['AWS::NotificationARNs'].push(value);
}
}else{
// By default, replace the value
awsRefOverrides[parameter] = value;
}
}else{
addError('crit', parameter + " is not an allowed pseudo parameter", ['cli-options'], 'pseudo parameters');
}
};
export function addCustomResourceAttributeValue(resource: string, attribute: string, value: any){
let attrType = inferValueType(value, []);
let newSpec = {
'Attributes': {
[attribute]: {
PrimitiveType: attrType,
Value: value
}
}
};
// register resource type or logical name override
if (!!~resource.indexOf('::')) {
resourcesSpec.registerTypeOverride(resource, newSpec);
} else {
resourcesSpec.registerLogicalNameOverride(resource, newSpec);
}
};
function addParameterOverride(parameter: string, value: ParameterValue){
parameterRuntimeOverride[parameter] = value;
}
function addImportOverride(parameter: string, value: ImportValue){
importRuntimeOverride[parameter] = value;
}
function validateWorkingInput(passedOptions?: Partial<ValidateOptions>) {
// Ensure we are working from a clean slate
//exports.resetValidator();
const options = Object.assign({}, defaultValidateOptions, passedOptions);
// Check AWS Template Format Version
if(workingInput.hasOwnProperty(['AWSTemplateFormatVersion'])){
let testValue = workingInput['AWSTemplateFormatVersion'];
if(typeof workingInput['AWSTemplateFormatVersion'] == 'object'){
addError('warn', 'AWSTemplateFormatVersion is recommended to be of type string \'2010-09-09\'', ['AWSTemplateFormatVersion'], 'AWSTemplateFormatVersion')
testValue = testValue.toUTCString();
}
let allowedDateRegex = /^Thu, 09 Sep 2010 00:00:00 GMT$|^2010-09-09$/;
if(!allowedDateRegex.test(testValue)){
addError('crit', 'AWSTemplateFormatVersion should be \'2010-09-09\'', ['AWSTemplateFormatVersion'], 'AWSTemplateFormatVersion');
}
}
// Check Transform
if (workingInput.hasOwnProperty(['Transform'])) {
// assign defined transforms to the validator
workingInputTransform = workingInput['Transform'];
// initialize transform output
if (!!~workingInputTransform.indexOf('AWS::Serverless-2016-10-31')) {
workingInput['SAMOutput'] = {}
}
}
// TODO: Check keys for parameter are valid, ex. MinValue/MaxValue
// Apply specification overrides
applySpecificationOverrides();
// Process SAM Globals section
processSAMGlobals();
// Apply template overrides
applyTemplateOverrides();
// Check parameters and assign outputs
assignParametersOutput(options.guessParameters);
// Evaluate Conditions
assignConditionsOutputs();
// Assign outputs to all the resources
assignResourcesOutputs();
if(stopValidation) {
// Stop the validation early, we can't join stuff if we don't know what to expect
if(process.env.DEBUG) {
logger.error("Stopping validation early as a resource type is invalid.");
}
return errorObject;
}
// Use the outputs assigned to resources to resolve references
resolveReferences();
// Re-Apply template overrides
applyTemplateOverrides();
// Go through the hopefully resolved properties of each resource
checkResourceProperties();
// Assign template outputs to the error object
collectOutputs();
return errorObject;
}
function applySpecificationOverrides() {
// extend resources specification with SAM specifics
if (!!~workingInputTransform.indexOf('AWS::Serverless-2016-10-31')) {
resourcesSpec.extendSpecification(samData.samResources20161031);
}
// normalize Tag property type access
let tagPropertyTypes: any = {};
for (let resourceKey of Object.keys(awsData.awsResources['ResourceTypes'])) {
tagPropertyTypes[`${resourceKey}.Tag`] = awsData.awsResources['PropertyTypes']['Tag'];
}
resourcesSpec.extendSpecification({'PropertyTypes': tagPropertyTypes});
}
/*
* Validation and processing of the Globals section in SAM templates
* Based on https//github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
*/
function processSAMGlobals() {
if (!~workingInputTransform.indexOf('AWS::Serverless-2016-10-31')) { return; }
// process input
if (workingInput.hasOwnProperty('Globals')) {
let workingInputGlobals = workingInput['Globals'];
if (!!workingInputGlobals && (typeof workingInputGlobals == 'object')) {
for (let resourceType of Object.keys(workingInputGlobals)) {
let resourceTemplate = workingInputGlobals[resourceType];
if (!!resourceTemplate) {
let targetType: string | undefined;
let allowedProperties: string[] = [];
switch(resourceType) {
case 'Function':
targetType = 'AWS::Serverless::Function';
allowedProperties = samData.samGlobals20161031.AllowedProperties[resourceType];
break;
case 'Api':
targetType = 'AWS::Serverless::Api';
allowedProperties = samData.samGlobals20161031.AllowedProperties[resourceType];
break;
case 'SimpleTable':
targetType = 'AWS::Serverless::SimpleTable';
allowedProperties = samData.samGlobals20161031.AllowedProperties[resourceType];
break;
}
if (!!targetType) {
let resourceProperties: any = Object.keys(resourceTemplate);
let inheritableProperties: any = {};
// validate and extract properties that are inheritable by the given type
for (let resourceProperty of resourceProperties) {
if (!!~allowedProperties.indexOf(resourceProperty)) {
inheritableProperties[resourceProperty] = resourceTemplate[resourceProperty];
} else {
addError('crit', `Invalid or unsupported SAM Globals property name: ${resourceProperty}`,
['Globals', resourceType], 'Globals');
}
}
// override inheritable properties of matching resource type in template
let templateOverride = {
'Properties': inheritableProperties
};
if (workingInput.hasOwnProperty('Resources')) {
let workingInputResources = workingInput['Resources'];
if (!!workingInputResources && (typeof workingInputResources == 'object')) {
for (let workingInputResource of Object.keys(workingInputResources)) {
let WIRTemplate = workingInputResources[workingInputResource];
if (!!WIRTemplate && (typeof WIRTemplate == 'object')) {
if (WIRTemplate.hasOwnProperty('Type') &&
WIRTemplate['Type'] == targetType) {
Object.assign(WIRTemplate, mergeOptions(templateOverride, WIRTemplate));
}
}
}
}
}
} else {
addError('crit', `Invalid SAM Globals resource type: ${resourceType}.`, ['Globals'], 'Globals');
}
}
}
}
}
}
function inferPrimitiveValueType(v: any) {
if (isInteger(v)) {
return 'Integer';
}
if (isDouble(v)) {
return 'Double';
}
if (isBoolean(v)) {
return 'Boolean';
}
if (isJson(v)) {
return 'Json';
}
if (isTimestamp(v)) {
return 'Timestamp';
}
if (isString(v)) {
return 'String';
}
return null;
}
function inferStructureValueType(v: any, candidateTypes: string[]) {
let type: string | null = null;
if (isObject(v)) {
if (v.hasOwnProperty('Type')) {
let objectType = v['Type'];
for (let candidateType of candidateTypes!) {
if (!!~candidateType.indexOf(objectType)) {
type = candidateType;
}
}
} else {
let objectKeys = [];
if (v.hasOwnProperty('Properties')) {
objectKeys = Object.keys(v['Properties']);
} else {
objectKeys = Object.keys(v);
}
let lastMatchCount = 0;
for (let candidateType of candidateTypes!) {
let candidate = resourcesSpec.getType(candidateType);
let candidateKeys = Object.keys(candidate['Properties']);
let matchCount = arrayIntersection(objectKeys, candidateKeys).length;
if (matchCount > lastMatchCount) {
type = candidateType;
lastMatchCount = matchCount;
}
}
}
}
return type;
}
function inferAggregateValueType(v: any, candidateItemTypes: string[]): string | null {
let item: any = null;
let type: string | null = null;
let itemType: string | null = null;
if (isList(v)) {
type = 'List';
item = v[0];
}
else if (isObject(v)) {
type = 'Map';
item = v[Object.keys(v)[0]!];
}
if (!!item) {
itemType = inferValueType(item, candidateItemTypes);
// aggregate type nesting is not currently supported
if (!!itemType && resourcesSpec.isAggregateType(itemType)) {
itemType = 'Json';
}
}
return (!!type && !!itemType) ? `${type}<${itemType}>` : null;
}
function inferValueType(v: any, candidateTypes: string[]) {
candidateTypes = candidateTypes.filter((x) => !resourcesSpec.isPrimitiveType(x));
let candidateStructureTypes: string[] = candidateTypes.filter((x) => {
if (resourcesSpec.isParameterizedTypeFormat(x) &&
resourcesSpec.isAggregateType(resourcesSpec.getParameterizedTypeName(x))) {
return false;
}
return true;
});
let candidateAggregateTypes: string[] = candidateTypes.filter((x) => {
if (resourcesSpec.isParameterizedTypeFormat(x) &&
resourcesSpec.isAggregateType(resourcesSpec.getParameterizedTypeName(x))) {
return true;
}
return false;
});
candidateAggregateTypes = candidateAggregateTypes.map((x) => resourcesSpec.getParameterizedTypeArgument(x));
let type: string | null = inferStructureValueType(v, candidateStructureTypes);
if (!type) {
type = inferAggregateValueType(v, candidateAggregateTypes);
if (!type) {
type = inferPrimitiveValueType(v);
}
}
return type;
}
function formatCandidateTypes(baseType: string, candidateTypes: string[]) {
// remove generic name part
candidateTypes = candidateTypes.map((x) => resourcesSpec.getParameterizedTypeArgument(x));
// format property types
candidateTypes = candidateTypes.map((x) => resourcesSpec.rebaseTypeFormat(baseType, x));
return candidateTypes;
}
function templateHasUnresolvedIntrinsics(template: any): boolean {
if (typeof template == 'object') {
const templateKeys = Object.keys(template);
const awsIntrinsicFunctionNames = Object.keys(awsIntrinsicFunctions);
for (const templateKey of templateKeys) {
const nestedTemplate: any = template[templateKey];
if (!!~awsIntrinsicFunctionNames.indexOf(templateKey) || templateHasUnresolvedIntrinsics(nestedTemplate)) {
return true;
}
}
}
return false;
}
function applySAMPropertyOverrides(baseType: string, baseName: string, type: string, name: string,
spec: awsData.Property, template: any) {
// early exit for unsupported template or base type
if (!~workingInputTransform.indexOf('AWS::Serverless-2016-10-31') || !~baseType.indexOf('AWS::Serverless')) { return; }
const localizedType = (baseType == type) ? `${baseType}<${baseName}>` : `${baseType}.${type}<${baseName}>`;
// specialize property based on inferred Type
const specType: any = spec['Type'];
if (Array.isArray(specType)) {
// skip if template has unresolved intrinsic functions
if (templateHasUnresolvedIntrinsics(template)) {
return;
}
let candidateTypes = formatCandidateTypes(baseType, specType);
// infer property spec based on value in template
let inferredCandidateType: string | null;
if (!!(inferredCandidateType = inferValueType(template, candidateTypes))) {
inferredCandidateType = inferredCandidateType.replace(`${baseType}.`, '');
// determine spec based on a parameterized type matching the inferred candidate type
if (resourcesSpec.hasProperty(localizedType, `${name}<${inferredCandidateType}>`)) {
let candidateSpec = resourcesSpec.getProperty(localizedType, `${name}<${inferredCandidateType}>`);
// override property spec
for (let property of Object.keys(spec)) {
if (!candidateSpec.hasOwnProperty(property)) {
delete (<any>spec)[property];
}
}
Object.assign(spec, clone(candidateSpec));
}
}
}
}
function doSAMTransform(baseType:string, type: string, name: string, template: any, parentTemplate: any) {
// early exit for unsupported template or base type
if (!~workingInputTransform.indexOf('AWS::Serverless-2016-10-31') || !~baseType.indexOf('AWS::Serverless')) { return; }
// destructure name
let nameParts = name.split('#');
let logicalID = nameParts.shift();
let propertyName = nameParts.shift();
let itemID = nameParts.shift();
// determine transform key
let transformKey = baseType;
if (!!propertyName) {
transformKey = `${transformKey}#${propertyName}`;
}
if (!!itemID) {
let itemType = type;
transformKey = `${transformKey}#ItemID<${itemType}>`;
}
// determine available properties
let localProperties: any = null;
if (!!template && template.hasOwnProperty('Properties')) {
localProperties = template['Properties'];
}
let parentProperties: any = null;
if (!!parentTemplate && parentTemplate.hasOwnProperty('Properties')) {
parentProperties = parentTemplate['Properties'];
}
// create supporting resources
let output = workingInput['SAMOutput'];
let transform = samData.samImplicitResources20161031[transformKey];
if (!!transform) {
let resourceTypes = Object.keys(transform);
for (let resourceType of resourceTypes) {
// build resource logical ID
let resourceLogicalID = transform[resourceType]['logicalId'];
resourceLogicalID = resourceLogicalID.replace('<LogicalID>', logicalID);
resourceLogicalID = resourceLogicalID.replace('<ItemID>', itemID);
switch (transformKey) {
case 'AWS::Serverless::Function#AutoPublishAlias':
switch (resourceType) {
case 'AWS::Lambda::Alias':
if (!!parentProperties && parentProperties.hasOwnProperty('AutoPublishAlias')) {
let autoPublishAlias = parentProperties['AutoPublishAlias'];
resourceLogicalID = resourceLogicalID.replace('<AutoPublishAlias>', autoPublishAlias);
}
break;
case 'AWS::Lambda::Version':
// TODO: this may be non-deterministic and does not handle the case when CodeUri refers to local path
let codeDict: any = null;
if (!!parentProperties && parentProperties.hasOwnProperty('CodeUri')) {
if (parentProperties['CodeUri'].hasOwnProperty('Bucket')) {
codeDict['S3Bucket'] = parentProperties['CodeUri']['Bucket'];
}
if (parentProperties['CodeUri'].hasOwnProperty('Key')) {
codeDict['S3Key'] = parentProperties['CodeUri']['Key'];
}
if (parentProperties['CodeUri'].hasOwnProperty('Version')) {
codeDict['S3ObjectVersion'] = parentProperties['CodeUri']['Version'];
}
} else if (!!parentProperties && parentProperties.hasOwnProperty('InlineCode')) {
codeDict['ZipFile'] = parentProperties['InlineCode'];
} else {
// TODO: perhaps raise validation error if neither CodeUri or InlineCode have been provided
}
if (!!codeDict) {
codeDict = JSON.stringify(codeDict);
let codeID = shajs('sha256').update(codeDict).digest('hex').substr(0, 10);
resourceLogicalID = resourceLogicalID.replace('<CodeID>', codeID);
}
break;
}
break;
case 'AWS::Serverless::Function#Events#ItemID<ApiEvent>':
// TODO: we currently have no way of knowing the DefinitionID
break;
case 'AWS::Serverless::Api':
// TODO: this may be non-deterministic and does not handle the case when DefinitionUri refers to local path
switch (resourceType) {
case 'AWS::ApiGateway::Deployment':
let definition: any = null;
if (!!localProperties && localProperties.hasOwnProperty('DefinitionUri')) {
// S3 object type
if (!!localProperties['DefinitionUri'] && (typeof localProperties['DefinitionUri'] == 'object')) {
definition = {};
if (localProperties['DefinitionUri'].hasOwnProperty('Bucket')) {
definition['Bucket'] = localProperties['DefinitionUri']['Bucket'];
}
if (localProperties['DefinitionUri'].hasOwnProperty('Key')) {
definition['Key'] = localProperties['DefinitionUri']['Key'];
}
if (localProperties['DefinitionUri'].hasOwnProperty('Version')) {
definition['Version'] = localProperties['DefinitionUri']['Version'];
}
// S3 protocol string
} else {
definition = localProperties['DefinitionUri'];
}
} else if (!!localProperties && localProperties.hasOwnProperty('DefinitionBody')) {
definition = localProperties['DefinitionBody'];
} else {
// TODO: perhaps raise validation error if neither DefinitionUri or DefinitionBody have been provided
}
if (!!definition) {
definition = JSON.stringify(definition);
let definitionID = shajs('sha256').update(definition).digest('hex').substr(0, 10);
resourceLogicalID = resourceLogicalID.replace('<DefinitionID>', definitionID);
}
break;
case 'AWS::ApiGateway::Stage':
if (!!localProperties && localProperties.hasOwnProperty('StageName')) {
let stageName = localProperties['StageName'];
resourceLogicalID = resourceLogicalID.replace('<StageName>', stageName);
}
break;
}
break;
}
// build resource template
let resourceTemplate: any = {
'Type': resourceType,
'Attributes': {
'Ref': 'mockAttr_Ref' // some CFN definitions are missing the Ref attribute, so we force it here
}
};
let resourceSpec: any = resourcesSpec.getType(resourceType);
if (resourceSpec.hasOwnProperty('Attributes')) {
for (let attribute of Object.keys(resourceSpec['Attributes'])) {
let attributeValue = `mockAttr_${attribute}`;
if (!!~attribute.indexOf('Arn')) {
attributeValue = mockArnPrefix;
}
resourceTemplate['Attributes'][attribute] = attributeValue;
}
}
// assign resource output
output[resourceLogicalID] = resourceTemplate;
// link supporting resource to referable property of source
let sourceRefProperty = transform[resourceType]['refProperty']
if (!!sourceRefProperty) {
output[`${logicalID}.${sourceRefProperty}`] = output[resourceLogicalID];
}
}
}
}
function applyTemplatePropertyOverrides(baseType: string, baseName:string, type: string, name: string, spec: awsData.Property,
template: any, parentTemplate: any) {
applySAMPropertyOverrides(baseType, baseName, type, name, spec, template);
doSAMTransform(baseType, type, `${baseName}#${name}`, template, parentTemplate);
}
function applyTemplateTypeOverrides(baseType: string, type: string, name: string, template: any, parentTemplate: any) {
// process type overrides
doSAMTransform(baseType, type, name, template, parentTemplate);
// early exit for invalid type
const localizedType = (baseType == type) ? `${baseType}<${name}>` : `${baseType}.${type}<${name}>`;
if (!resourcesSpec.hasType(localizedType)) {
return;
}
// initialize specification override
const originalSpec = resourcesSpec.getType(localizedType);
const overrideSpec = clone(originalSpec);
// determine properties section
let templateProperties = template;
if (baseType == type) {
templateProperties = template['Properties'];
}
// apply property overrides
if (!!templateProperties && (typeof templateProperties == 'object')) {
for (const propertyName of Object.keys(templateProperties)) {
// acquire property template
const templateProperty = templateProperties[propertyName];
if (!templateProperty) {
continue;
}
// process property
const specProperty = overrideSpec['Properties'][propertyName] as awsData.Property;
if (!!specProperty) {
applyTemplatePropertyOverrides(baseType, name, type, propertyName, specProperty, templateProperty, template);
// descend into nested types
if (specProperty.hasOwnProperty('ItemType')) {
const subType = specProperty['ItemType'] as string;
for (const subKey of Object.keys(templateProperty)) {
const subTemplate = templateProperty[subKey];
applyTemplateTypeOverrides(baseType, subType, `${name}#${propertyName}#${subKey}`, subTemplate, template);
}
} else if (specProperty.hasOwnProperty('Type')) {
const subType = specProperty['Type'] as string;
applyTemplateTypeOverrides(baseType, subType, `${name}#${propertyName}`, templateProperty, template);
}
}
}
}
// register specification overrides
if (JSON.stringify(originalSpec) !== JSON.stringify(overrideSpec)) {
resourcesSpec.registerLogicalNameOverride(name, overrideSpec);
}
}
function applyTemplateOverrides() {
// process input
if (workingInput.hasOwnProperty('Resources')) {
let workingInputResources = workingInput['Resources'];
if (!!workingInputResources && (typeof workingInputResources == 'object')) {
for (let name of Object.keys(workingInputResources)) {
let template = workingInputResources[name];
if (!!template) {
if (template.hasOwnProperty('Type')) {
let type = template['Type'];
if (!!type) {
applyTemplateTypeOverrides(type, type, name, template, null);
}
}
}
}
}
}
}
function assignParametersOutput(guessParameters?: string[]) {
if(!workingInput.hasOwnProperty('Parameters')){
return false; // This isn't an issue
}
const guessAll = (guessParameters === undefined);
const guessParametersSet = new Set(guessParameters || []);
// For through each parameter
for(let parameterName in workingInput['Parameters']) {
const parameter = workingInput['Parameters'][parameterName];
if (!parameter.hasOwnProperty('Type')) {
// We are going to assume type if a string to continue validation, but will throw a critical
addError('crit', `Parameter ${parameterName} does not have a Type defined.`, ['Parameters', parameterName], "Parameters");
parameter['Type'] = 'String';
}
// if the user hasn't specified any parameters to mock, assume all are ok; otherwise,
// only mock the allowed ones.
const okToGuess = (guessAll) || (guessParametersSet.has(parameterName));
let parameterValue = inferParameterValue(parameterName, parameter, okToGuess);
if (parameter.hasOwnProperty('AllowedValues') && parameter['AllowedValues'].indexOf(parameterValue) < 0) {
addError('crit', `Parameter value '${parameterValue}' for ${parameterName} is`
+ ` not within the parameters AllowedValues`, ['Parameters', parameterName], "Parameters");
}
if(parameter['Type'] === "CommaDelimitedList" && typeof parameterValue === 'string') {
parameterValue = parameterValue.split(',').map(x => x.trim());
parameterValue.forEach(val => {
if (val === ""){
addError('crit', `Parameter ${parameterName} contains a CommaDelimitedList where the number of commas appears to be equal or greater than the list of items.`, ['Parameters', parameterName], "Parameters");
}
})
}
// The List<type> parameter value is inferred as string with comma delimited values and must be converted to array
let listParameterTypesSpec = Object.keys(parameterTypesSpec).filter((x) => !!x.match(/List<.*>/));
if (!!~listParameterTypesSpec.indexOf(parameter['Type']) && (typeof parameterValue === 'string')) {
parameterValue = parameterValue.split(',').map(x => x.trim());
parameterValue.forEach(val => {
if (val === ""){
addError('crit', `Parameter ${parameterName} contains a List<${parameter['Type']}> where the number of commas appears to be equal or greater than the list of items.`, ['Parameters', parameterName], "Parameters");
}
})
}
// Assign an Attribute Ref regardless of any failures above
workingInput['Parameters'][parameterName]['Attributes'] = {};
workingInput['Parameters'][parameterName]['Attributes']['Ref'] = parameterValue;
}
}
function inferParameterValue(parameterName: string, parameter: any, okToGuess: boolean): string | string[] {
const parameterDefaultsByType = {
'string': `string_input_${parameterName}`,
'array': undefined,
'number': '42'
}
// Check if the Ref for the parameter has been defined at runtime
const parameterOverride = parameterRuntimeOverride[parameterName]
if (parameterOverride !== undefined) {
// Check the parameter provided at runtime is within the allowed property list (if specified)
return parameterOverride;
} else if (parameter.hasOwnProperty('Default')) {
// See if Default property is present and populate
return parameter['Default'];
} else {
if (!okToGuess) {
addError('crit', 'Value for parameter was not provided', ['Parameters', parameterName], 'Parameters')
}
if (parameter.hasOwnProperty('AllowedValues') && parameter['AllowedValues'].length > 0) {
// See if AllowedValues has been specified
return parameter['AllowedValues'][0];
} else {
const rawParameterType = parameter['Type'];
const listMatch = /^List<(.+)>$/.exec(rawParameterType);
let isList: boolean;
let parameterType: string;
if (listMatch) {
isList = true;
parameterType = listMatch[1];
} else {
parameterType = rawParameterType;
isList = false;
}
if (!parameterTypesSpec.hasOwnProperty(parameterType)) {
addError('crit', `Parameter ${parameterName} has an invalid type of ${rawParameterType}.`, ['Parameters', parameterName], "Parameters");
parameterType = 'String';
}
let normalizedType = parameterTypesSpec[parameterType!];
if (normalizedType == 'array') {
isList = true;
parameterType = 'String';
normalizedType = 'string';
}
const parameterDefault = parameterDefaultsByType[parameterTypesSpec[parameterType]!]!
if (isList) {
return [parameterDefault];
} else {
return parameterDefault;
}
}
}
}
type Severity = keyof typeof errorObject.errors;
function addError(severity: Severity, message : string, resourceStack: typeof placeInTemplate = [], help: string = ''){
let obj = {
'message': resourcesSpec.stripTypeParameters(message),
'resource': resourceStack.join(' > '),
'documentation': docs.getUrls(resourcesSpec.stripTypeParameters(help)).join(', ')
};
// Set the information
errorObject.errors[severity].push(obj);
// Template invalid if critical error
if(severity == 'crit'){
errorObject.templateValid = false;
}
// Debug
if(process.env.DEBUG) {
let strResourceStack = resourceStack.join(' > ');
logger.debug(`Error thrown: ${severity}: ${message} (${strResourceStack})`);
}
}
function assignConditionsOutputs(){
let allowedIntrinsicFunctions = ['Fn::And', 'Fn::Equals', 'Fn::If', 'Fn::Not', 'Fn::Or'];
if(!workingInput.hasOwnProperty('Conditions')){
return;
}
// For through each condition
placeInTemplate.push('Conditions');
for(let cond in workingInput['Conditions']) {
if (workingInput['Conditions'].hasOwnProperty(cond)) {
placeInTemplate.push(cond);
let condition = workingInput['Conditions'][cond];
// Check the value of condition is an object
if(typeof condition != 'object'){
addError('crit', `Condition should consist of an intrinsic function of type ${allowedIntrinsicFunctions.join(', ')}`,
placeInTemplate,
'Conditions');
workingInput['Conditions'][cond] = {};
workingInput['Conditions'][cond]['Attributes'] = {};
workingInput['Conditions'][cond]['Attributes']['Output'] = false;
}else{
// Check the value of this is Fn::And, Fn::Equals, Fn::If, Fn::Not or Fn::Or
let keys = Object.keys(condition);
if(allowedIntrinsicFunctions.indexOf(keys[0]) != -1){
// Resolve recursively
let val = resolveIntrinsicFunction(condition, keys[0]);
// Check is boolean type
workingInput['Conditions'][cond]['Attributes'] = {};
workingInput['Conditions'][cond]['Attributes']['Output'] = false;
if(val === true || val === false){
workingInput['Conditions'][cond]['Attributes']['Output'] = val;
}else{
addError('crit', `Condition did not resolve to a boolean value, got ${val}`, placeInTemplate, 'Conditions');
}
}else{
// Invalid intrinsic function
addError('crit', `Condition does not allow function '${keys[0]}' here`, placeInTemplate, 'Conditions');
}
}
placeInTemplate.pop();
}
}
placeInTemplate.pop();
}
function assignResourcesOutputs(){
if(!workingInput.hasOwnProperty('Resources')){
addError('crit', 'Resources section is not defined', [], "Resources");
stopValidation = true;
return false;
}
if(workingInput['Resources'].length == 0){
addError('crit', 'Resources is empty', [], "Resources");
stopValidation = true;
return false;
}
// For through each resource
for(let res in workingInput['Resources']){
if(workingInput['Resources'].hasOwnProperty(res)){
// Check if Type is defined
let resourceType = '';
let spec = null;
if(!workingInput['Resources'][res].hasOwnProperty('Type')){
stopValidation = true;
addError('crit',
`Resource ${res} does not have a Type.`,
['Resources', res],
"Resources"
);
}else{
// Check if Type is valid
resourceType = `${workingInput['Resources'][res]['Type']}<${res}>`;
try {
spec = resourcesSpec.getResourceType(resourceType);
} catch (e) {
if (e instanceof resourcesSpec.NoSuchResourceType) {
addError('crit',
`Resource ${res} has an invalid Type of ${resourceType}.`,
['Resources', res],
"Resources"
);
} else {
throw e;
}
}
}
// Create a map for storing the output attributes for this Resource
let refValue = "mock-ref-" + res;
let refOverride = resourcesSpec.getRefOverride(resourcesSpec.getParameterizedTypeName(resourceType));
if(refOverride !== null){
if(refOverride == "arn"){
refValue = mockArnPrefix + res;
}else{
refValue = refOverride;
}
}
// Create a return attributes for the resource, assume every resource has a Ref
workingInput['Resources'][res]['Attributes'] = {};
workingInput['Resources'][res]['Attributes']['Ref'] = refValue;
// Go through the attributes of the specification, and assign them
if(spec != null && spec.Attributes){
for(let attr in spec.Attributes){
let value: any = null;
// use user-defined attribute value if provided for the specific type
try {
let attrSpec: any = resourcesSpec.getResourceTypeAttribute(resourceType, attr);
if (attrSpec.hasOwnProperty('Value')) {
value = attrSpec['Value'];
}
} catch(e) {}
// otherwise use an implicit mock value
if (!value) {
if (attr.indexOf('Arn') != -1) {
value = mockArnPrefix + res;
}else {
value = "mockAttr_" + res;
}
}
workingInput['Resources'][res]['Attributes'][attr] = value;
}
}
}
}
}
function resolveReferences(){
// TODO: Go through and resolve...
// TODO: Ref, Attr, Join,
// Resolve all Ref
lastPositionInTemplate = workingInput;
recursiveDecent(lastPositionInTemplate);
let stop = workingInput;
}
let placeInTemplate: (string|number)[] = [];
let lastPositionInTemplate: any = null;
let lastPositionInTemplateKey: string | null = null;
function recursiveDecent(ref: any){
// Save the current variables to allow for nested decents
let placeInTemplateX = placeInTemplate;
let lastPositionInTemplateX = lastPositionInTemplate;
let lastPositionInTemplateKeyX = lastPositionInTemplateKey;
// Step into next attribute
for(let i=0; i < Object.keys(ref).length; i++){
let key = Object.keys(ref)[i];
// Resolve the function
if(awsIntrinsicFunctions.hasOwnProperty(key)){
// Check if an Intrinsic function is allowed here
let inResourceProperty = (placeInTemplate[0] == "Resources" || placeInTemplate[2] == "Properties");
let inResourceMetadata = (placeInTemplate[0] == "Resources" || placeInTemplate[2] == "Metadata");
let inGlobalEnvironment = (placeInTemplate[0] == "Globals" && placeInTemplate[2] == "Environment");
let inOutputs = (placeInTemplate[0] == "Outputs");
let inConditions = (placeInTemplate[0] == "Conditions");
// TODO Check for usage inside update policy
if(!(inGlobalEnvironment || inResourceProperty || inResourceMetadata || inOutputs || inConditions)){
addError("crit", `Intrinsic function ${key} is not supported here`, placeInTemplate, key);
}else {
// Resolve the function
let functionOutput = resolveIntrinsicFunction(ref, key);
if (functionOutput !== null && lastPositionInTemplateKey !== null) {
// Overwrite the position with the resolved value
lastPositionInTemplate[lastPositionInTemplateKey] = functionOutput;
}
}
}else if(key != 'Attributes' && ref[key] instanceof Object){
placeInTemplate.push(key);
lastPositionInTemplate = ref;
lastPositionInTemplateKey = key;
recursiveDecent(ref[key]);
}
}
placeInTemplate.pop();
// Restore the variables to support nested resolving
placeInTemplate = placeInTemplateX;
lastPositionInTemplate = lastPositionInTemplateX;
lastPositionInTemplateKey = lastPositionInTemplateKeyX;
}
function resolveCondition(ref: any, key: string){
let toGet = ref[key];
let condition = false;
if(workingInput.hasOwnProperty('Conditions') && workingInput['Conditions'].hasOwnProperty(toGet)){
// Check the valid of the condition, returning argument 1 on true or 2 on failure
if(typeof workingInput['Conditions'][toGet] == 'object') {
if (workingInput['Conditions'][toGet].hasOwnProperty('Attributes') &&
workingInput['Conditions'][toGet]['Attributes'].hasOwnProperty('Output')) {
condition = workingInput['Conditions'][toGet]['Attributes']['Output'];
} // If invalid, we will default to false, a previous error would have been thrown
}else{
condition = workingInput['Conditions'][toGet];
}
}else{
addError('crit', `Condition '${toGet}' must reference a valid condition`, placeInTemplate, 'Condition');
}
return condition;
}
function resolveIntrinsicFunction(ref: any, key: string) : string | boolean | string[] | undefined | null{
switch(key){
case 'Ref':
return doIntrinsicRef(ref, key);
case 'Condition':
return resolveCondition(ref, key);
case 'Fn::Join':
return doIntrinsicJoin(ref, key);
case 'Fn::Base64':
return doIntrinsicBase64(ref, key);
case 'Fn::GetAtt':
return doIntrinsicGetAtt(ref, key);
case 'Fn::FindInMap':
return doIntrinsicFindInMap(ref, key);
case 'Fn::GetAZs':
return doIntrinsicGetAZs(ref, key);
case 'Fn::Sub':
return doIntrinsicSub(ref, key);
case 'Fn::If':
return doIntrinsicIf(ref, key);
case 'Fn::Equals':
return doIntrinsicEquals(ref, key);
case 'Fn::Or':
return doIntrinsicOr(ref, key);
case 'Fn::Not':
return doIntrinsicNot(ref, key);
case 'Fn::ImportValue':
return doIntrinsicImportValue(ref, key);
case 'Fn::Select':
return doIntrinsicSelect(ref, key);
case 'Fn::Split':
return doInstrinsicSplit(ref, key);
default:
addError("warn", `Unhandled Intrinsic Function ${key}, this needs implementing. Some errors might be missed.`, placeInTemplate, "Functions");
return null;
}
}
function doIntrinsicRef(ref: any, key: string){
let refValue = ref[key];
let resolvedVal = "INVALID_REF";
// Check if it's of a String type
if(typeof refValue != "string"){
addError("crit", "Intrinsic Function Ref expects a string", placeInTemplate, "Ref");
}else {
// Check if the value of the Ref exists
resolvedVal = getRef(refValue);
if (resolvedVal === null) {
addError('crit', `Referenced value ${refValue} does not exist`, placeInTemplate, "Ref");
resolvedVal = "INVALID_REF";
}
}
// Return the resolved value
return resolvedVal;
}
function doIntrinsicBase64(ref: any, key: string){
// Only base64 encode strings
let toEncode = ref[key];
if(typeof toEncode != "string"){
toEncode = resolveIntrinsicFunction(ref[key], Object.keys(ref[key])[0]);
if(typeof toEncode != "string"){
addError("crit", "Parameter of Fn::Base64 does not resolve to a string", placeInTemplate, "Fn::Base64");
return "INVALID_FN_BASE64";
}
}
// Return base64
return Buffer.from(toEncode).toString('base64');
}
function doIntrinsicJoin(ref: any, key: string){
// Ensure that all objects in the join array have been resolved to string, otherwise
// we need to resolve them.
// Expect 2 parameters
let join = ref[key][0];
let parts = ref[key][1] || null;
if(ref[key].length != 2 || parts == null){
addError('crit', 'Invalid parameters for Fn::Join', placeInTemplate, "Fn::Join");
// Specify this as an invalid string
return "INVALID_JOIN";
}else{
// Join
return fnJoin(join, parts);
}
}
function doIntrinsicGetAtt(ref: any, key: string){
let toGet = ref[key];
if(toGet.length < 2){
addError("crit", "Invalid parameters for Fn::GetAtt", placeInTemplate, "Fn::GetAtt");
return "INVALID_GET_ATT"
}else{
if(typeof toGet[0] != "string"){ // TODO Implement unit test for this
addError("crit", "Fn::GetAtt does not support functions for the logical resource name", placeInTemplate, "Fn::GetAtt");
}
// If we have more than 2 parameters, merge other parameters
if(toGet.length > 2){
let root = toGet[0];
let parts = toGet.slice(1).join('.');
toGet = [root, parts];
}
// The AttributeName could be a Ref, so check if it needs resolving
if(typeof toGet[1] != "string"){
let keys = Object.keys(toGet[1]);
if(keys[0] == "Ref") { // TODO Implement unit test for this
toGet[1] = resolveIntrinsicFunction(toGet[1], "Ref");
}else{ // TODO Implement unit test for this
addError("crit", "Fn::GetAtt only supports Ref within the AttributeName", placeInTemplate, "Fn::GetAtt");
}
}
let attr = fnGetAtt(toGet[0], toGet[1]);
if(attr != null){
return attr;
}else{
return "INVALID_REFERENCE_OR_ATTR_ON_GET_ATT";
}
}
}
function doIntrinsicFindInMap(ref: any, key: string){
let toGet = ref[key];
if(toGet.length != 3){
addError("crit", "Invalid parameters for Fn::FindInMap", placeInTemplate, "Fn::FindInMap");
return "INVALID_FN_FIND_IN_MAP"
}else {
for(let x in toGet){
if(toGet.hasOwnProperty(x)) {
if (typeof toGet[x] != "string") {
toGet[x] = resolveIntrinsicFunction(toGet[x], Object.keys(toGet[x])[0]);
}
}
}
// Find in map
let val = fnFindInMap(toGet[0], toGet[1], toGet[2]);
if(val == null){
addError("crit",
`Could not find value in map ${toGet[0]}|${toGet[1]}|${toGet[2]}. Have you tried specifying input parameters?`,
placeInTemplate,
"Fn::FindInMap");
return "INVALID_MAPPING";
}else{
return val;
}
}
}
function doIntrinsicGetAZs(ref: any, key: string){
let toGet = ref[key];
let region = awsRefOverrides['AWS::Region'];
// If the argument is not a string, check it's Ref and resolve
if(typeof toGet != "string"){
let key = Object.keys(toGet)[0];
if(key == "Ref") {
if(toGet[key] != 'AWS::Region'){
addError("warn", "Fn::GetAZs expects a region, ensure this reference returns a region", placeInTemplate, "Fn::GetAZs");
}
region = resolveIntrinsicFunction(toGet, "Ref") as string;
}else{ // TODO Implement unit test for this
addError("crit", "Fn::GetAZs only supports Ref or string as a parameter", placeInTemplate, "Fn::GetAZs");
}
}else{
if(toGet != ""){ // TODO: Implement unit test
region = toGet;
}
}
// We now have a string, assume it's a real region
// Lets create an array with 3 AZs
let AZs = [];
AZs.push(region + 'a');
AZs.push(region + 'b');
AZs.push(region + 'c');
return AZs;
}
function doIntrinsicSelect(ref: any, key: string){
let toGet = ref[key];
if(!Array.isArray(toGet) || toGet.length < 2) {
addError('crit', "Fn::Select only supports an array of two elements", placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
if (toGet[0] === undefined || toGet[0] === null) {
addError('crit', "Fn::Select first element cannot be null or undefined", placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
let index: number;
if (typeof toGet[0] == 'object' && !Array.isArray(toGet[0])) {
let keys = Object.keys(toGet[0]);
if(awsIntrinsicFunctions['Fn::Select::Index']['supportedFunctions'].indexOf(keys[0]) != -1) {
let resolvedIndex = resolveIntrinsicFunction(toGet[0], keys[0]);
if(typeof resolvedIndex === 'string') {
index = parseInt(resolvedIndex);
} else if (typeof resolvedIndex === 'number') {
index = resolvedIndex;
} else {
addError('crit', "Fn::Select's first argument did not resolve to a string for parsing or a numeric value.", placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
} else {
addError('crit', `Fn::Select does not support the ${keys[0]} function in argument 1`);
return 'INVALID_SELECT';
}
} else if (typeof toGet[0] === 'string') {
index = parseInt(toGet[0])
} else if (typeof toGet[0] === 'number'){
index = toGet[0];
} else {
addError('crit', `Fn:Select's first argument must be a number or resolve to a number, it appears to be a ${typeof(toGet[0])}`, placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
if (typeof index === undefined || typeof index !== 'number' || isNaN(index)) {
addError('crit', "First element of Fn::Select must be a number, or it must use an intrinsic fuction that returns a number", placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
if (toGet[1] === undefined || toGet[1] === null) {
addError('crit', "Fn::Select Second element cannot be null or undefined", placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
let list = toGet[1]
if (!Array.isArray(list)) {
//we may need to resolve it
if (typeof list !== 'object') {
addError('crit', `Fn::Select requires the second element to resolve to a list, it appears to be a ${typeof list}`, placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
} else if(typeof list == 'object'){
let keys = Object.keys(list);
if(awsIntrinsicFunctions['Fn::Select::List']['supportedFunctions'].indexOf(keys[0]) != -1) {
list = resolveIntrinsicFunction(list, keys[0]);
} else {
addError('crit', `Fn::Select does not support the ${keys[0]} function in argument 2`);
return 'INVALID_SELECT';
}
if (keys[0] === "Ref" ) {
// check if it was a paramter which might be converted to a list
const parameterName = toGet[1][keys[0]];
if (workingInput['Parameters'][parameterName] !== undefined ) {
list = workingInput['Parameters'][parameterName]['Attributes']['Ref'];
}
}
}
if (!Array.isArray(list)) {
addError('crit', `Fn::Select requires the second element to be a list, function call did not resolve to a list. It contains value ${list}`, placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
} else if (list.indexOf(null) > -1) {
addError('crit', "Fn::Select requires that the list be free of null values", placeInTemplate, "Fn::Select");
}
if (index >= 0 && index < list.length) {
return list[index];
} else {
addError('crit', "First element of Fn::Select exceeds the length of the list.", placeInTemplate, "Fn::Select");
return 'INVALID_SELECT';
}
}
/**
* Resolves the string part of the `Fn::Sub` intrinsic function into mappings of placeholders and their corresponding CFN
* literal values or intrinsic functions, according to the provided list of `Fn::Sub` specific variables; the resulting intrinsic
* functions are compatible with and can later be resolved using the `resolveIntrinsicFunction` function.
* e.g.: `{ '${AWS::Region}': {'Ref': 'AWS::Region'} }`.
*/
function parseFnSubStr(sub: string, vars: any = {}) {
// Extract the placeholders within the ${} and store in matches
const regex = /\${([A-Za-z0-9:.!]+)}/gm;
const matches = [];
let match;
while (match = regex.exec(sub)) {
matches.push(match[1]);
}
// Process each of the matches into a literal value or an intrinsic function
const results: any = {};
for (let m of matches) {
let result: any = null;
// literal value
if(m.indexOf('!') == 0) {
result = m.substring(1);
// Fn::Sub variable value
} else if(vars.hasOwnProperty(m)) {
result = m;
// Fn::GetAtt intrinsic function
} else if(resourcesSpec.isPropertyTypeFormat(m)) {
result = {
'Fn::GetAtt': [
resourcesSpec.getPropertyTypeBaseName(m),
resourcesSpec.getPropertyTypePropertyName(m),
]
};
// Ref intrinsic function
} else {
result = {
'Ref': m
};
}
results[m] = result;
}
return results;
}
function doIntrinsicSub(ref: any, key: string){
let toGet = ref[key];
let replacementStr = null;
let definedParams = null;
// We have a simple replace
// Ex. !Sub MyInput-${AWS::Region}
if(typeof toGet == 'string'){
replacementStr = toGet;
}else{
// We should have an array of parameters
// Ex.
// Prop: !Sub
// - "MyInput-${Something}-${Else}
// - Something: aa
// Else: bb
if(toGet[0]){
// Check the given values are the correct types for an array style Sub, otherwise
// throw errors.
if(typeof toGet[0] == 'string'){
replacementStr = toGet[0];
}else{
addError('crit', 'Fn::Sub expects first argument to be a string', placeInTemplate, 'Fn::Sub');
}
if(typeof toGet[1] == 'object'){
definedParams = toGet[1];
}else{
addError('crit', 'Fn::Sub expects second argument to be a variable map', placeInTemplate, 'Fn::Sub');
}
}else{
addError('crit', 'Fn::Sub function malformed, first array element should be present', placeInTemplate, "Fn::Sub");
}
}
const placeholderValues = parseFnSubStr(replacementStr, definedParams ? definedParams : {});
// do rendition
for(const placeholder in placeholderValues){
let placeholderValue: any = placeholderValues[placeholder];
// resolve intrinsics
if(typeof placeholderValue == 'object'){
const fnName = Object.keys(placeholderValue)[0];
placeholderValue = resolveIntrinsicFunction(placeholderValue, fnName);
}
if(placeholderValue == 'INVALID_REFERENCE_OR_ATTR_ON_GET_ATT' || placeholderValue == null){
addError('crit', `Intrinsic Sub does not reference a valid resource, attribute nor mapping '${placeholder}'.`,
placeInTemplate, 'Fn::Sub');
}
replacementStr = replacementStr.replace(placeholder, placeholderValue);
}
// Set the resolved value as a string
return replacementStr;
}
function doIntrinsicIf(ref: any, key: string){
let toGet = ref[key];
// Check the value of the condition
if(toGet.length == 3){
// Check toGet[0] is a valid condition
toGet[0] = resolveCondition({'Condition': toGet[0]}, 'Condition');
// Set the value
let value = null;
if(toGet[0]){
value = toGet[1];
}else{
value = toGet[2];
}
if(value instanceof Array){
// Go through each element in the array, resolving if needed.
let resolvedValue = [];
for(let i=0; i < value.length; i++) {
let keys = Object.keys(value[i]);
if (awsIntrinsicFunctions['Fn::If']['supportedFunctions'].indexOf(keys[0]) !== -1) {
resolvedValue.push(resolveIntrinsicFunction(value[i], keys[0]));
}else{
addError('crit', `Fn::If does not allow ${keys[0]} as a nested function within an array`, placeInTemplate, 'Fn::If');
}
}
// Return the resolved array
return resolvedValue;
}else if(typeof value === "object") {
let keys = Object.keys(value);
if (awsIntrinsicFunctions['Fn::If']['supportedFunctions'].indexOf(keys[0]) !== -1) {
return resolveIntrinsicFunction(value, keys[0]);
}else{
// TODO: Do we need to make sure this isn't an attempt at an invalid supportedFunction?
recursiveDecent(value);
return value
}
}else {
return value;
}
}else{
addError('crit', `Fn::If must have 3 arguments, only ${toGet.length} given.`, placeInTemplate, 'Fn::If');
}
// Set the 1st or 2nd param as according to the condition
return "INVALID_IF_STATEMENT";
}
function doIntrinsicEquals(ref: any, key: string) {
let toGet = ref[key];
// Check the value of the condition
if (toGet.length == 2) {
// Resolve first argument
if(typeof toGet[0] == 'object'){
let keys = Object.keys(toGet[0]);
if(awsIntrinsicFunctions['Fn::If']['supportedFunctions'].indexOf(keys[0]) != -1) {
toGet[0] = resolveIntrinsicFunction(toGet[0], keys[0]);
}else{
addError('crit', `Fn::Equals does not support the ${keys[0]} function in argument 1`);
}
}
// Resolve second argument
if(typeof toGet[1] == 'object'){
let keys = Object.keys(toGet[1]);
if(awsIntrinsicFunctions['Fn::If']['supportedFunctions'].indexOf(keys[0]) != -1) {
toGet[0] = resolveIntrinsicFunction(toGet[1], keys[0]);
}else{
addError('crit', `Fn::Equals does not support the ${keys[1]} function in argument 2`);
}
}
// Compare
return (toGet[0] == toGet[1]);
}else{
addError('crit', `Fn::Equals expects 2 arguments, ${toGet.length} given.`, placeInTemplate, 'Fn::Equals');
}
return false;
}
function doIntrinsicOr(ref: any, key: string) {
let toGet = ref[key];
// Check the value of the condition
if (toGet.length > 1 && toGet.length < 11) {
let argumentIsTrue = false;
// Resolve each argument
for(let arg in toGet){
if(toGet.hasOwnProperty(arg)) {
if (typeof toGet[arg] == 'object') {
let keys = Object.keys(toGet[arg]);
if(awsIntrinsicFunctions['Fn::Or']['supportedFunctions'].indexOf(keys[0]) != -1) {
toGet[arg] = resolveIntrinsicFunction(toGet[arg], keys[0]);
}else{
addError('crit', `Fn::Or does not support function '${keys[0]}' here`, placeInTemplate, 'Fn::Or');
}
}
// Set to true if needed
if (toGet[arg] === true) {
argumentIsTrue = true;
}
}
}
return argumentIsTrue;
}else{
addError('crit', `Expecting Fn::Or to have between 2 and 10 arguments`, placeInTemplate, 'Fn::Or');
}
}
function doIntrinsicNot(ref: any, key: string){
let toGet = ref[key];
// Check the value of the condition
if (toGet.length == 1){
// Resolve if an object
if(typeof toGet[0] == 'object') {
let keys = Object.keys(toGet[0]);
if (awsIntrinsicFunctions['Fn::Not']['supportedFunctions'].indexOf(keys[0]) != -1) {
toGet[0] = resolveIntrinsicFunction(toGet[0], keys[0]);
} else {
addError('crit', `Fn::Not does not support function '${keys[0]}' here`, placeInTemplate, 'Fn::Or');
}
}
// Negate
if (toGet[0] === true || toGet[0] === false) {
return !toGet[0];
} else {
addError('crit', `Fn::Not did not resolve to a boolean value, ${toGet[0]} given`, placeInTemplate, 'Fn::Not');
}
}else{
addError('crit', `Expecting Fn::Not to have exactly 1 argument`, placeInTemplate, 'Fn::Not');
}
return false;
}
function doIntrinsicImportValue(ref: any, key: string){
let toGet = ref[key];
// If not string, resolve using the supported functions
if(typeof toGet == 'object') {
let keys = Object.keys(toGet);
if (awsIntrinsicFunctions['Fn::ImportValue']['supportedFunctions'].indexOf(keys[0]) != -1) {
toGet = resolveIntrinsicFunction(toGet, keys[0]);
} else {
addError('crit', `Fn::ImportValue does not support function '${keys[0]}' here`, placeInTemplate, 'Fn::ImportValue');
return 'INVALID_FN_IMPORTVALUE';
}
}
// Resolve
if(typeof toGet == 'string'){
const importValue = importRuntimeOverride[toGet];
if(importValue !== undefined) {
return importValue;
}
// If an import wasn't provided, construct a default value for backwards compatibility
return "IMPORTEDVALUE" + toGet;
}else{
addError('warn', `Something went wrong when resolving references for a Fn::ImportValue`, placeInTemplate, 'Fn::ImportValue');
return 'INVALID_FN_IMPORTVALUE';
}
}
export function doInstrinsicSplit(ref: any, key: string): string[] {
const args = ref[key];
if (!Array.isArray(args) || args.length !== 2) {
addError('crit', 'Invalid parameter for Fn::Split. It needs an Array of length 2.', placeInTemplate, 'Fn::Split');
return ['INVALID_SPLIT'];
}
const delimiter: string = args[0];
if (typeof delimiter !== 'string') {
addError ('crit', `Invalid parameter for Fn::Split. The delimiter, ${util.inspect(delimiter)}, needs to be a string.`, placeInTemplate, 'Fn::Split');
return ['INVALID_SPLIT'];
}
const stringOrInstrinsic = args[1];
let stringToSplit: string;
if (typeof stringOrInstrinsic === 'object') {
const fnName = Object.keys(stringOrInstrinsic)[0];
if (awsIntrinsicFunctions['Fn::Split']['supportedFunctions'].indexOf(fnName) == -1) {
addError('crit', `Fn::Split does not support function '${fnName}' here`, placeInTemplate, 'Fn::Split');
return ['INVALID_SPLIT'];
}
stringToSplit = resolveIntrinsicFunction(stringOrInstrinsic, fnName) as string;
} else if (typeof stringOrInstrinsic === 'string') {
stringToSplit = stringOrInstrinsic;
} else {
addError('crit', `Invalid parameters for Fn::Split. The parameter, ${stringOrInstrinsic}, needs to be a string or a supported intrinsic function.`, placeInTemplate, 'Fn::Split');
return ['INVALID_SPLIT'];
}
return fnSplit(delimiter, stringToSplit);
}
function fnSplit(delimiter: string, stringToSplit: string): string[] {
return stringToSplit.split(delimiter);
}
function fnJoin(join: any, parts: any){
// Resolve instrinsic functions that return the parts array
if (!Array.isArray(parts)) {
// TODO Check the key is within the valid functions which can be called from a Fn::Join
parts = resolveIntrinsicFunction(parts, Object.keys(parts)[0]);
if (!Array.isArray(parts)) {
addError('crit', 'Invalid parameters for Fn::Join', placeInTemplate, "Fn::Join");
// Specify this as an invalid string
return "INVALID_JOIN";
}
}
// Otherwise go through each parts and ensure they are resolved
for(let p in parts){
if(parts.hasOwnProperty(p)) {
if (typeof parts[p] == "object") {
// Something needs resolving
// TODO Check the key is within the valid functions which can be called from a Fn::Join
parts[p] = resolveIntrinsicFunction(parts[p], Object.keys(parts[p])[0]);
}
}
}
return parts.join(join);
}
export function fnGetAtt(reference: string, attributeName: string){
// determine resource template
let resource: any;
if (!!~workingInputTransform.indexOf('AWS::Serverless-2016-10-31') &&
workingInput['SAMOutput'].hasOwnProperty(reference)) {
resource = workingInput['SAMOutput'][reference];
} else if (workingInput['Resources'].hasOwnProperty(reference)) {
resource = workingInput['Resources'][reference];
} else {
addError('crit',
`No resource with logical name of ${reference}!`,
placeInTemplate,
reference);
}
// determine attribute value
if (!!resource) {
const resourceType = `${resource['Type']}<${reference}>`;
try {
// Lookup attribute
const attribute = resourcesSpec.getResourceTypeAttribute(resourceType, attributeName)
const primitiveAttribute = attribute as PrimitiveAttribute
if(!!primitiveAttribute['PrimitiveType']) {
return resource['Attributes'][attributeName];
}
const listAttribute = attribute as ListAttribute
if(listAttribute['Type'] == 'List') {
return [ resource['Attributes'][attributeName], resource['Attributes'][attributeName] ]
}
} catch (e) {
// Coerce missing custom resource attribute value to string
if ((resourceType.indexOf('Custom::') == 0) ||
(resourceType.indexOf('AWS::CloudFormation::CustomResource') == 0) ||
(resourceType.indexOf('AWS::CloudFormation::Stack') == 0)) {
return `mockAttr_${reference}_${attributeName}`;
}
if (e instanceof resourcesSpec.NoSuchResourceTypeAttribute) {
addError('crit',
e.message,
placeInTemplate,
resourceType
);
} else {
throw e;
}
}
}
// Return null if not found
return null;
}
function fnFindInMap(map: any, first: string, second: string){
if(workingInput.hasOwnProperty('Mappings')){
if(workingInput['Mappings'].hasOwnProperty(map)){
if(workingInput['Mappings'][map].hasOwnProperty(first)){
if(workingInput['Mappings'][map][first].hasOwnProperty(second)){
return workingInput['Mappings'][map][first][second];
}
}
}
}
return null;
}
function getRef(reference: string){
// Check in SAMOutput
if (!!~workingInputTransform.indexOf('AWS::Serverless-2016-10-31') &&
workingInput['SAMOutput'].hasOwnProperty(reference)) {
return workingInput['SAMOutput'][reference]['Attributes']['Ref'];
// Check in Resources
} else if(workingInput['Resources'].hasOwnProperty(reference)){
return workingInput['Resources'][reference]['Attributes']['Ref'];
}
// Check in Parameters
if(workingInput['Parameters'] && workingInput['Parameters'].hasOwnProperty(reference)){
return workingInput['Parameters'][reference]['Attributes']['Ref'];
}
// Check for customs refs
if(awsRefOverrides.hasOwnProperty(reference)){
return awsRefOverrides[reference];
}
// We have not found a ref
return null;
}
function getImportValue(reference: string) {
if(workingInput['Imports'] && workingInput['Imports'].hasOwnProperty(reference)) {
return workingInput['Imports'][reference];
}
}
function collectOutputs() {
placeInTemplate.push('Outputs');
const outputs = workingInput['Outputs'] || {};
for (let outputName in outputs) {
placeInTemplate.push(outputName);
try {
const output = outputs[outputName];
const outputValue = output['Value'];
if (outputValue === undefined) { continue; }
errorObject['outputs'][outputName] = outputValue;
if (output['Export']) {
const exportName = output['Export']['Name']
if (!exportName) {
addError('crit', `Output ${outputName} exported with no Name`, placeInTemplate, 'Outputs');
continue;
}
errorObject['exports'][exportName] = outputValue;
}
} finally {
placeInTemplate.pop();
}
}
placeInTemplate.pop();
}
let baseResourceType: string = null!;
// these types all represent schemas that the working input may need to be validated against.
export interface ResourceType {
type: 'RESOURCE',
resourceType: string
}
export interface NamedProperty {
type: 'PROPERTY',
resourceType: string,
parentType: string // perhaps property type or resource type
propertyName: string
}
export interface PropertyType {
type: 'PROPERTY_TYPE',
propertyType: string,
resourceType: string
}
export interface PrimitiveType {
type: 'PRIMITIVE_TYPE',
resourceType: string,
primitiveType: string
}
export type ObjectType = ResourceType | NamedProperty | PropertyType | PrimitiveType;
/**
* get the name of the ResourceType or PropertyType that this ObjectType refers to.
*/
function getTypeName(objectType: ResourceType | NamedProperty | PropertyType ): string | undefined {
switch (objectType.type) {
case 'RESOURCE':
return objectType.resourceType
case 'PROPERTY':
return resourcesSpec.getPropertyType(objectType.resourceType, objectType.parentType, objectType.propertyName);
case 'PROPERTY_TYPE':
return objectType.propertyType
default:
throw new Error('unknown type!');
}
}
/**
*
*/
function getItemType(objectType: NamedProperty): PrimitiveType | PropertyType {
const maybePrimitiveType = resourcesSpec.getPrimitiveItemType(objectType.parentType, objectType.propertyName);
const maybePropertyType = resourcesSpec.getItemType(objectType.resourceType, objectType.parentType, objectType.propertyName);
if (maybePrimitiveType) {
return {
type: 'PRIMITIVE_TYPE',
primitiveType: maybePrimitiveType,
resourceType: objectType.resourceType
}
} else if (maybePropertyType) {
return {
type: 'PROPERTY_TYPE',
propertyType: maybePropertyType,
resourceType: objectType.resourceType
}
} else {
throw new Error(`${objectType.parentType}.${objectType.propertyName} is not a container type, but we tried to get an item type for it anyway.`);
}
}
function checkResourceProperties() {
// Go into resources
placeInTemplate.push('Resources');
let resources = workingInput['Resources'];
// Go through each resource
for (let res in resources) {
const resourceType = `${resources[res]['Type']}<${res}>`;
// Check the property exists
try {
let spec = resourcesSpec.getType(resourceType);
} catch (e) {
if (e instanceof resourcesSpec.NoSuchResourceType) {
continue;
} else {
throw e;
}
}
// Add the resource name to stack
placeInTemplate.push(res);
// Set the baseResourceType for PropertyType derivation
baseResourceType = resourceType;
// Do property validation if Properties in present
if(resources[res].hasOwnProperty('Properties')) {
// Add Properties to the location stack
placeInTemplate.push('Properties');
check({type: 'RESOURCE', resourceType}, resources[res]['Properties']);
// Remove Properties
placeInTemplate.pop();
}
// Remove resources
placeInTemplate.pop();
}
// Remove Resource
placeInTemplate.pop();
}
export enum KnownTypes {
ComplexObject,
List,
Map,
Arn,
String,
Integer,
Boolean,
Json,
Double,
Timestamp
}
export function getPropertyType(objectType: NamedProperty | PrimitiveType) {
if (objectType.type === 'PROPERTY' && isPropertySchema(objectType)) {
return KnownTypes.ComplexObject;
} else if (objectType.type === 'PROPERTY' && isListSchema(objectType)) {
return KnownTypes.List;
} else if (objectType.type === 'PROPERTY' && isMapSchema(objectType)) {
return KnownTypes.Map;
} else if (objectType.type === 'PROPERTY' && isArnSchema(objectType)) {
return KnownTypes.Arn;
} else if (isStringSchema(objectType)) {
return KnownTypes.String;
} else if (isIntegerSchema(objectType)) {
return KnownTypes.Integer;
} else if (isBooleanSchema(objectType)) {
return KnownTypes.Boolean;
} else if (isJsonSchema(objectType)) {
return KnownTypes.Json
} else if (isDoubleSchema(objectType)) {
return KnownTypes.Double;
} else if (isTimestampSchema(objectType)) {
return KnownTypes.Timestamp;
} else {
// this should never happen in production; there are tests in place to ensure
// we can determine the type of every property in the resources and propertytype specs.
throw new Error (`could not determine type of ${util.inspect(objectType)}`);
}
}
function check(objectType: ObjectType, objectToCheck: any) {
try {
// if we are checking against a resource or propertytype, it must be against
// an object with subproperties.
if ((objectType.type === 'RESOURCE') || (objectType.type === 'PROPERTY_TYPE')) {
verify(isObject, objectToCheck);
checkComplexObject(objectType, objectToCheck);
// otherwise, we have a named property of some resource or propertytype,
// or just a primitive.
} else {
const propertyType = getPropertyType(objectType);
switch (propertyType) {
case KnownTypes.ComplexObject:
verify(isObject, objectToCheck);
checkComplexObject(objectType as NamedProperty, objectToCheck);
break;
case KnownTypes.Map:
verify(isObject, objectToCheck);
checkMap(objectType as NamedProperty, objectToCheck);
break;
case KnownTypes.List:
verify(isList, objectToCheck);
checkList(objectType as NamedProperty, objectToCheck);
break;
case KnownTypes.Arn:
verify(isArn, objectToCheck);
break;
case KnownTypes.String:
verify(isString, objectToCheck);
break;
case KnownTypes.Integer:
verify(isInteger, objectToCheck);
break;
case KnownTypes.Boolean:
verify(isBoolean, objectToCheck);
break;
case KnownTypes.Json:
verify(isJson, objectToCheck);
break;
case KnownTypes.Double:
verify(isDouble, objectToCheck);
break;
case KnownTypes.Timestamp:
verify(isTimestamp, objectToCheck);
break;
default:
// this causes a typescript error if we forget to handle a KnownType.
const check: never = propertyType;
}
}
} catch (e) {
if (e instanceof VerificationError) {
addError('crit', e.message+`, got ${util.inspect(objectToCheck)}`, placeInTemplate, objectType.resourceType);
} else {
// generic error handler; let us keep checking what we can instead of crashing.
addError('crit', `Unexpected error: ${e.message} while checking ${util.inspect(objectToCheck)} against ${util.inspect(objectType)}`, placeInTemplate, objectType.resourceType);
console.error(e);
}
}
}
//
// Functions to work out what types our properties are expecting.
//
function isPropertySchema(objectType: NamedProperty | PrimitiveType) {
if (objectType.type === 'PRIMITIVE_TYPE') {
return false;
} else {
return !(resourcesSpec.isPrimitiveProperty(objectType.parentType, objectType.propertyName))
&& !(resourcesSpec.isPropertyTypeList(objectType.parentType, objectType.propertyName))
&& !(resourcesSpec.isPropertyTypeMap(objectType.parentType, objectType.propertyName))
}
}
const isListSchema = (property: NamedProperty) =>
resourcesSpec.isPropertyTypeList(property.parentType, property.propertyName);
const isMapSchema = (property: NamedProperty) =>
resourcesSpec.isPropertyTypeMap(property.parentType, property.propertyName);
const isArnSchema = (property: NamedProperty) =>
resourcesSpec.isArnProperty(property.propertyName);
function wrapCheck(f: (primitiveType: string) => boolean) {
function wrapped(objectType: NamedProperty | PrimitiveType) {
const primitiveType = (objectType.type === 'PRIMITIVE_TYPE')
? objectType.primitiveType
: resourcesSpec.getPrimitiveType(objectType.parentType, objectType.propertyName)!;
return f(primitiveType);
}
return wrapped;
}
const isStringSchema = wrapCheck((primitiveType) => primitiveType == 'String');
const isIntegerSchema = wrapCheck((primitiveType) => primitiveType == 'Integer' || primitiveType == 'Long');
const isBooleanSchema = wrapCheck((primitiveType) => primitiveType == 'Boolean');
const isJsonSchema = wrapCheck((primitiveType) => primitiveType == 'Json');
const isDoubleSchema = wrapCheck((primitiveType) => primitiveType == 'Double');
const isTimestampSchema = wrapCheck((primitiveType) => primitiveType == 'Timestamp');
//
// Functions to verify incoming data shapes against their expected types.
//
class VerificationError extends CustomError {
constructor(message: string) {
super(message)
CustomError.fixErrorInheritance(this, VerificationError);
}
}
export interface VerificationFunction {
(o: any): boolean,
failureMessage: string
}
function verify(verifyTypeFunction: VerificationFunction, object: any) {
if (!verifyTypeFunction(object)) {
throw new VerificationError(verifyTypeFunction.failureMessage);
}
}
function verificationFunction(f: (o: any) => boolean, message: string): VerificationFunction {
return Object.assign(f, {failureMessage: message});
}
export const isList = verificationFunction(
(o: any) => (o instanceof Object && o.constructor === Array),
'Expecting a list'
);
export const isObject = verificationFunction(
(o: any) => (o instanceof Object && o.constructor === Object),
'Expecting an object'
);
export const isString = verificationFunction(
(o: any) => (typeof o === 'string') || (typeof o === 'number'), // wtf cfn.
'Expecting a string'
);
export const isArn = verificationFunction(
(o: any) => (typeof o === 'string') && o.indexOf('arn:aws') == 0,
'Expecting an ARN'
);
const integerRegex = /^-?\d+$/;
export const isInteger = verificationFunction(
(o: any) => {
if (typeof o === 'number') {
return (o === Math.round(o));
} else if (typeof o === 'string') {
return integerRegex.test(o);
} else {
return false;
}
},
'Expecting an integer'
);
const doubleRegex = /^-?\d+(.\d*)?([eE][-+]?\d+)?$/;
export const isDouble = verificationFunction(
(o: any) => {
if (typeof o === 'number') {
return !isNaN(o);
} else if (typeof o === 'string') {
return doubleRegex.test(o);
} else {
return false;
}
},
'Expecting a double'
);
export const isBoolean = verificationFunction(
(o: any) => {
if (typeof o === 'boolean') {
return true
} else if (typeof o === 'string') {
const oLower = o.toLowerCase();
return oLower === 'true' || oLower === 'false';
} else {
return false;
}
},
'Expecting a Boolean'
);
export const isJson = verificationFunction(
(o: any) => {
if (isObject(o)) {
return true;
} else if (typeof o === 'string') {
try {
const obj = JSON.parse(o);
return isObject(obj);
} catch (e) {
return false;
}
} else {
return false;
}
},
'Expecting a JSON object'
);
const r = String.raw;
// adapted from https://github.com/segmentio/is-isodate (and fixed slightly)
const timestampRegex = RegExp(
r`^\d{4}-\d{2}-\d{2}` + // Match YYYY-MM-DD
r`(` + // time part
r`(T\d{2}:\d{2}(:\d{2})?)` + // Match THH:mm:ss
r`(\.\d{1,6})?` + // Match .sssss
r`(Z|(\+|-)\d{2}(\:?\d{2}))?` + // Time zone (Z or +hh:mm or +hhmm)
r`)?$`
);
export const isTimestamp = verificationFunction(
(o: any) => (typeof o === 'string') && timestampRegex.test(o) && !isNaN(Date.parse(o)),
'Expecting an ISO8601-formatted string'
);
//
// Functions to descend into complex structures (schema'd objects, Maps, and Lists).
//
function _isKnownProperty(objectTypeName: string, objectType: ObjectType, isCustomPropertyAllowed: boolean, subPropertyName: string) {
const isKnownProperty = resourcesSpec.isValidProperty(objectTypeName, subPropertyName);
if (!isKnownProperty && !isCustomPropertyAllowed) {
addError("crit", `${subPropertyName} is not a valid property of ${objectTypeName}`, placeInTemplate, objectType.resourceType);
}
return isKnownProperty;
}
function _checkForMissingProperties(properties: {[k: string]: any}, objectTypeName: string){
const requiredProperties = resourcesSpec.getRequiredProperties(objectTypeName);
// Remove the properties we have from the required property list
const remainingProperties = requiredProperties.filter((propertyName) => properties[propertyName] === undefined);
// If we have any items left over, they have not been defined
if(remainingProperties.length > 0){
for(let prop of remainingProperties){
addError(`crit`, `Required property ${prop} missing for type ${objectTypeName}`, placeInTemplate, objectTypeName);
}
}
}
function localizeType(type: string) {
// determine localized name
let typePlaceInTemplate: any = clone(placeInTemplate);
typePlaceInTemplate.splice(0, 1); // remove 'Resources'
typePlaceInTemplate.splice(1, 1); // remove 'Properties'
typePlaceInTemplate = typePlaceInTemplate.join('#');
// don't localize primitive, complex or already localized types
let localType = type;
if (!resourcesSpec.isPrimitiveType(type) &&
!resourcesSpec.isAggregateType(type) &&
!resourcesSpec.isParameterizedTypeFormat(type)) {
localType = `${type}<${typePlaceInTemplate}>`;
}
return localType
}
function checkComplexObject(objectType: ResourceType | NamedProperty | PropertyType, objectToCheck: any) {
let objectTypeName = getTypeName(objectType);
if (!objectTypeName) {
const namedProperty = objectType as NamedProperty;
throw new Error(`${namedProperty.parentType}.${namedProperty.propertyName} is not a ResourceType or PropertyType, but we tried to get its type anyway.`);
}
objectTypeName = localizeType(objectTypeName);
// Check for missing required properties
_checkForMissingProperties(objectToCheck, objectTypeName);
const isCustomPropertyAllowed = resourcesSpec.isAdditionalPropertiesEnabled(objectTypeName);
for (const subPropertyName in objectToCheck) {
placeInTemplate.push(subPropertyName);
const propertyValue = objectToCheck[subPropertyName];
try {
// check if property is recognized
if (!_isKnownProperty(objectTypeName, objectType, isCustomPropertyAllowed, subPropertyName)) { continue; }
// already handled in check for missing properties, above.
if (propertyValue === undefined) { continue; }
const subPropertyObjectType = {
type: 'PROPERTY',
resourceType: objectType.resourceType,
parentType: objectTypeName,
propertyName: subPropertyName
} as NamedProperty;
check(subPropertyObjectType, propertyValue)
} finally {
placeInTemplate.pop();
}
}
// TODO How to handle optional required parameters
}
function checkList(objectType: NamedProperty, listToCheck: any[]) {
for (const [index, item] of listToCheck.entries()) {
placeInTemplate.push(index);
if(!util.isUndefined(item)){
let itemType = getItemType(objectType);
if (itemType.type == 'PROPERTY_TYPE') {
itemType.propertyType = localizeType(itemType.propertyType);
}
check(itemType, item);
}
placeInTemplate.pop();
}
}
function checkMap(objectType: NamedProperty, mapToCheck: {[k: string]: any}) {
for (let key in mapToCheck) {
placeInTemplate.push(key);
const item = mapToCheck[key];
let itemType = getItemType(objectType);
if (itemType.type == 'PROPERTY_TYPE') {
itemType.propertyType = localizeType(itemType.propertyType);
}
check(itemType, item);
placeInTemplate.pop();
}
}
// EXPOSE INTERNAL FUNCTIONS FOR TESTING PURPOSES
export const __TESTING__: any = {
'resourcesSpec': resourcesSpec,
'inferPrimitiveValueType': inferPrimitiveValueType,
'inferStructureValueType': inferStructureValueType,
'inferAggregateValueType': inferAggregateValueType,
'inferValueType': inferValueType,
'templateHasUnresolvedIntrinsics': templateHasUnresolvedIntrinsics
}; | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://cloudkms.googleapis.com/$discovery/rest?version=v1
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Google Cloud Key Management Service (KMS) API v1 */
function load(name: "cloudkms", version: "v1"): PromiseLike<void>;
function load(name: "cloudkms", version: "v1", callback: () => any): void;
const projects: cloudkms.ProjectsResource;
namespace cloudkms {
interface AuditConfig {
/**
* The configuration for logging of each type of permission.
* Next ID: 4
*/
auditLogConfigs?: AuditLogConfig[];
exemptedMembers?: string[];
/**
* Specifies a service that will be enabled for audit logging.
* For example, `storage.googleapis.com`, `cloudsql.googleapis.com`.
* `allServices` is a special value that covers all services.
*/
service?: string;
}
interface AuditLogConfig {
/**
* Specifies the identities that do not cause logging for this type of
* permission.
* Follows the same format of Binding.members.
*/
exemptedMembers?: string[];
/** The log type that this config enables. */
logType?: string;
}
interface Binding {
/**
* The condition that is associated with this binding.
* NOTE: an unsatisfied condition will not allow user access via current
* binding. Different bindings, including their conditions, are examined
* independently.
* This field is GOOGLE_INTERNAL.
*/
condition?: Expr;
/**
* Specifies the identities requesting access for a Cloud Platform resource.
* `members` can have the following values:
*
* * `allUsers`: A special identifier that represents anyone who is
* on the internet; with or without a Google account.
*
* * `allAuthenticatedUsers`: A special identifier that represents anyone
* who is authenticated with a Google account or a service account.
*
* * `user:{emailid}`: An email address that represents a specific Google
* account. For example, `alice@gmail.com` or `joe@example.com`.
*
*
* * `serviceAccount:{emailid}`: An email address that represents a service
* account. For example, `my-other-app@appspot.gserviceaccount.com`.
*
* * `group:{emailid}`: An email address that represents a Google group.
* For example, `admins@example.com`.
*
*
* * `domain:{domain}`: A Google Apps domain name that represents all the
* users of that domain. For example, `google.com` or `example.com`.
*/
members?: string[];
/**
* Role that is assigned to `members`.
* For example, `roles/viewer`, `roles/editor`, or `roles/owner`.
* Required
*/
role?: string;
}
interface CryptoKey {
/** Output only. The time at which this CryptoKey was created. */
createTime?: string;
/** Labels with user defined metadata. */
labels?: Record<string, string>;
/**
* Output only. The resource name for this CryptoKey in the format
* `projects/*/locations/*/keyRings/*/cryptoKeys/*`.
*/
name?: string;
/**
* At next_rotation_time, the Key Management Service will automatically:
*
* 1. Create a new version of this CryptoKey.
* 2. Mark the new version as primary.
*
* Key rotations performed manually via
* CreateCryptoKeyVersion and
* UpdateCryptoKeyPrimaryVersion
* do not affect next_rotation_time.
*/
nextRotationTime?: string;
/**
* Output only. A copy of the "primary" CryptoKeyVersion that will be used
* by Encrypt when this CryptoKey is given
* in EncryptRequest.name.
*
* The CryptoKey's primary version can be updated via
* UpdateCryptoKeyPrimaryVersion.
*/
primary?: CryptoKeyVersion;
/**
* The immutable purpose of this CryptoKey. Currently, the only acceptable
* purpose is ENCRYPT_DECRYPT.
*/
purpose?: string;
/**
* next_rotation_time will be advanced by this period when the service
* automatically rotates a key. Must be at least one day.
*
* If rotation_period is set, next_rotation_time must also be set.
*/
rotationPeriod?: string;
}
interface CryptoKeyVersion {
/** Output only. The time at which this CryptoKeyVersion was created. */
createTime?: string;
/**
* Output only. The time this CryptoKeyVersion's key material was
* destroyed. Only present if state is
* DESTROYED.
*/
destroyEventTime?: string;
/**
* Output only. The time this CryptoKeyVersion's key material is scheduled
* for destruction. Only present if state is
* DESTROY_SCHEDULED.
*/
destroyTime?: string;
/**
* Output only. The resource name for this CryptoKeyVersion in the format
* `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*`.
*/
name?: string;
/** The current state of the CryptoKeyVersion. */
state?: string;
}
interface DecryptRequest {
/**
* Optional data that must match the data originally supplied in
* EncryptRequest.additional_authenticated_data.
*/
additionalAuthenticatedData?: string;
/**
* Required. The encrypted data originally returned in
* EncryptResponse.ciphertext.
*/
ciphertext?: string;
}
interface DecryptResponse {
/** The decrypted data originally supplied in EncryptRequest.plaintext. */
plaintext?: string;
}
interface EncryptRequest {
/**
* Optional data that, if specified, must also be provided during decryption
* through DecryptRequest.additional_authenticated_data. Must be no
* larger than 64KiB.
*/
additionalAuthenticatedData?: string;
/** Required. The data to encrypt. Must be no larger than 64KiB. */
plaintext?: string;
}
interface EncryptResponse {
/** The encrypted data. */
ciphertext?: string;
/** The resource name of the CryptoKeyVersion used in encryption. */
name?: string;
}
interface Expr {
/**
* An optional description of the expression. This is a longer text which
* describes the expression, e.g. when hovered over it in a UI.
*/
description?: string;
/**
* Textual representation of an expression in
* Common Expression Language syntax.
*
* The application context of the containing message determines which
* well-known feature set of CEL is supported.
*/
expression?: string;
/**
* An optional string indicating the location of the expression for error
* reporting, e.g. a file name and a position in the file.
*/
location?: string;
/**
* An optional title for the expression, i.e. a short string describing
* its purpose. This can be used e.g. in UIs which allow to enter the
* expression.
*/
title?: string;
}
interface KeyRing {
/** Output only. The time at which this KeyRing was created. */
createTime?: string;
/**
* Output only. The resource name for the KeyRing in the format
* `projects/*/locations/*/keyRings/*`.
*/
name?: string;
}
interface ListCryptoKeyVersionsResponse {
/** The list of CryptoKeyVersions. */
cryptoKeyVersions?: CryptoKeyVersion[];
/**
* A token to retrieve next page of results. Pass this value in
* ListCryptoKeyVersionsRequest.page_token to retrieve the next page of
* results.
*/
nextPageToken?: string;
/**
* The total number of CryptoKeyVersions that matched the
* query.
*/
totalSize?: number;
}
interface ListCryptoKeysResponse {
/** The list of CryptoKeys. */
cryptoKeys?: CryptoKey[];
/**
* A token to retrieve next page of results. Pass this value in
* ListCryptoKeysRequest.page_token to retrieve the next page of results.
*/
nextPageToken?: string;
/** The total number of CryptoKeys that matched the query. */
totalSize?: number;
}
interface ListKeyRingsResponse {
/** The list of KeyRings. */
keyRings?: KeyRing[];
/**
* A token to retrieve next page of results. Pass this value in
* ListKeyRingsRequest.page_token to retrieve the next page of results.
*/
nextPageToken?: string;
/** The total number of KeyRings that matched the query. */
totalSize?: number;
}
interface ListLocationsResponse {
/** A list of locations that matches the specified filter in the request. */
locations?: Location[];
/** The standard List next-page token. */
nextPageToken?: string;
}
interface Location {
/**
* Cross-service attributes for the location. For example
*
* {"cloud.googleapis.com/region": "us-east1"}
*/
labels?: Record<string, string>;
/** The canonical id for this location. For example: `"us-east1"`. */
locationId?: string;
/**
* Service-specific metadata. For example the available capacity at the given
* location.
*/
metadata?: Record<string, any>;
/**
* Resource name for the location, which may vary between implementations.
* For example: `"projects/example-project/locations/us-east1"`
*/
name?: string;
}
interface Policy {
/** Specifies cloud audit logging configuration for this policy. */
auditConfigs?: AuditConfig[];
/**
* Associates a list of `members` to a `role`.
* `bindings` with no members will result in an error.
*/
bindings?: Binding[];
/**
* `etag` is used for optimistic concurrency control as a way to help
* prevent simultaneous updates of a policy from overwriting each other.
* It is strongly suggested that systems make use of the `etag` in the
* read-modify-write cycle to perform policy updates in order to avoid race
* conditions: An `etag` is returned in the response to `getIamPolicy`, and
* systems are expected to put that etag in the request to `setIamPolicy` to
* ensure that their change will be applied to the same version of the policy.
*
* If no `etag` is provided in the call to `setIamPolicy`, then the existing
* policy is overwritten blindly.
*/
etag?: string;
iamOwned?: boolean;
/** Version of the `Policy`. The default version is 0. */
version?: number;
}
interface SetIamPolicyRequest {
/**
* REQUIRED: The complete policy to be applied to the `resource`. The size of
* the policy is limited to a few 10s of KB. An empty policy is a
* valid policy but certain Cloud Platform services (such as Projects)
* might reject them.
*/
policy?: Policy;
/**
* OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only
* the fields in the mask will be modified. If no mask is provided, the
* following default mask is used:
* paths: "bindings, etag"
* This field is only used by Cloud IAM.
*/
updateMask?: string;
}
interface TestIamPermissionsRequest {
/**
* The set of permissions to check for the `resource`. Permissions with
* wildcards (such as '*' or 'storage.*') are not allowed. For more
* information see
* [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions).
*/
permissions?: string[];
}
interface TestIamPermissionsResponse {
/**
* A subset of `TestPermissionsRequest.permissions` that the caller is
* allowed.
*/
permissions?: string[];
}
interface UpdateCryptoKeyPrimaryVersionRequest {
/** The id of the child CryptoKeyVersion to use as primary. */
cryptoKeyVersionId?: string;
}
interface CryptoKeyVersionsResource {
/**
* Create a new CryptoKeyVersion in a CryptoKey.
*
* The server will assign the next sequential id. If unset,
* state will be set to
* ENABLED.
*/
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Required. The name of the CryptoKey associated with
* the CryptoKeyVersions.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<CryptoKeyVersion>;
/**
* Schedule a CryptoKeyVersion for destruction.
*
* Upon calling this method, CryptoKeyVersion.state will be set to
* DESTROY_SCHEDULED
* and destroy_time will be set to a time 24
* hours in the future, at which point the state
* will be changed to
* DESTROYED, and the key
* material will be irrevocably destroyed.
*
* Before the destroy_time is reached,
* RestoreCryptoKeyVersion may be called to reverse the process.
*/
destroy(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The resource name of the CryptoKeyVersion to destroy. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<CryptoKeyVersion>;
/** Returns metadata for a given CryptoKeyVersion. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the CryptoKeyVersion to get. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<CryptoKeyVersion>;
/** Lists CryptoKeyVersions. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Optional limit on the number of CryptoKeyVersions to
* include in the response. Further CryptoKeyVersions can
* subsequently be obtained by including the
* ListCryptoKeyVersionsResponse.next_page_token in a subsequent request.
* If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* Optional pagination token, returned earlier via
* ListCryptoKeyVersionsResponse.next_page_token.
*/
pageToken?: string;
/**
* Required. The resource name of the CryptoKey to list, in the format
* `projects/*/locations/*/keyRings/*/cryptoKeys/*`.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListCryptoKeyVersionsResponse>;
/**
* Update a CryptoKeyVersion's metadata.
*
* state may be changed between
* ENABLED and
* DISABLED using this
* method. See DestroyCryptoKeyVersion and RestoreCryptoKeyVersion to
* move between other states.
*/
patch(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* Output only. The resource name for this CryptoKeyVersion in the format
* `projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*`.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required list of fields to be updated in this request. */
updateMask?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<CryptoKeyVersion>;
/**
* Restore a CryptoKeyVersion in the
* DESTROY_SCHEDULED,
* state.
*
* Upon restoration of the CryptoKeyVersion, state
* will be set to DISABLED,
* and destroy_time will be cleared.
*/
restore(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The resource name of the CryptoKeyVersion to restore. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<CryptoKeyVersion>;
}
interface CryptoKeysResource {
/**
* Create a new CryptoKey within a KeyRing.
*
* CryptoKey.purpose is required.
*/
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/**
* Required. It must be unique within a KeyRing and match the regular
* expression `[a-zA-Z0-9_-]{1,63}`
*/
cryptoKeyId?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Required. The name of the KeyRing associated with the
* CryptoKeys.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<CryptoKey>;
/** Decrypts data that was protected by Encrypt. */
decrypt(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* Required. The resource name of the CryptoKey to use for decryption.
* The server will choose the appropriate version.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<DecryptResponse>;
/** Encrypts data, so that it can only be recovered by a call to Decrypt. */
encrypt(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* Required. The resource name of the CryptoKey or CryptoKeyVersion
* to use for encryption.
*
* If a CryptoKey is specified, the server will use its
* primary version.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<EncryptResponse>;
/**
* Returns metadata for a given CryptoKey, as well as its
* primary CryptoKeyVersion.
*/
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the CryptoKey to get. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<CryptoKey>;
/**
* Gets the access control policy for a resource.
* Returns an empty policy if the resource exists and does not have a policy
* set.
*/
getIamPolicy(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/**
* REQUIRED: The resource for which the policy is being requested.
* See the operation documentation for the appropriate value for this field.
*/
resource: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Policy>;
/** Lists CryptoKeys. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Optional limit on the number of CryptoKeys to include in the
* response. Further CryptoKeys can subsequently be obtained by
* including the ListCryptoKeysResponse.next_page_token in a subsequent
* request. If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* Optional pagination token, returned earlier via
* ListCryptoKeysResponse.next_page_token.
*/
pageToken?: string;
/**
* Required. The resource name of the KeyRing to list, in the format
* `projects/*/locations/*/keyRings/*`.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListCryptoKeysResponse>;
/** Update a CryptoKey. */
patch(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* Output only. The resource name for this CryptoKey in the format
* `projects/*/locations/*/keyRings/*/cryptoKeys/*`.
*/
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Required list of fields to be updated in this request. */
updateMask?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<CryptoKey>;
/**
* Sets the access control policy on the specified resource. Replaces any
* existing policy.
*/
setIamPolicy(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/**
* REQUIRED: The resource for which the policy is being specified.
* See the operation documentation for the appropriate value for this field.
*/
resource: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Policy>;
/**
* Returns permissions that a caller has on the specified resource.
* If the resource does not exist, this will return an empty set of
* permissions, not a NOT_FOUND error.
*
* Note: This operation is designed to be used for building permission-aware
* UIs and command-line tools, not for authorization checking. This operation
* may "fail open" without warning.
*/
testIamPermissions(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/**
* REQUIRED: The resource for which the policy detail is being requested.
* See the operation documentation for the appropriate value for this field.
*/
resource: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<TestIamPermissionsResponse>;
/** Update the version of a CryptoKey that will be used in Encrypt */
updatePrimaryVersion(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The resource name of the CryptoKey to update. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<CryptoKey>;
cryptoKeyVersions: CryptoKeyVersionsResource;
}
interface KeyRingsResource {
/** Create a new KeyRing in a given Project and Location. */
create(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* Required. It must be unique within a location and match the regular
* expression `[a-zA-Z0-9_-]{1,63}`
*/
keyRingId?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Required. The resource name of the location associated with the
* KeyRings, in the format `projects/*/locations/*`.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<KeyRing>;
/** Returns metadata for a given KeyRing. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The name of the KeyRing to get. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<KeyRing>;
/**
* Gets the access control policy for a resource.
* Returns an empty policy if the resource exists and does not have a policy
* set.
*/
getIamPolicy(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/**
* REQUIRED: The resource for which the policy is being requested.
* See the operation documentation for the appropriate value for this field.
*/
resource: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Policy>;
/** Lists KeyRings. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* Optional limit on the number of KeyRings to include in the
* response. Further KeyRings can subsequently be obtained by
* including the ListKeyRingsResponse.next_page_token in a subsequent
* request. If unspecified, the server will pick an appropriate default.
*/
pageSize?: number;
/**
* Optional pagination token, returned earlier via
* ListKeyRingsResponse.next_page_token.
*/
pageToken?: string;
/**
* Required. The resource name of the location associated with the
* KeyRings, in the format `projects/*/locations/*`.
*/
parent: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListKeyRingsResponse>;
/**
* Sets the access control policy on the specified resource. Replaces any
* existing policy.
*/
setIamPolicy(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/**
* REQUIRED: The resource for which the policy is being specified.
* See the operation documentation for the appropriate value for this field.
*/
resource: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Policy>;
/**
* Returns permissions that a caller has on the specified resource.
* If the resource does not exist, this will return an empty set of
* permissions, not a NOT_FOUND error.
*
* Note: This operation is designed to be used for building permission-aware
* UIs and command-line tools, not for authorization checking. This operation
* may "fail open" without warning.
*/
testIamPermissions(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/**
* REQUIRED: The resource for which the policy detail is being requested.
* See the operation documentation for the appropriate value for this field.
*/
resource: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<TestIamPermissionsResponse>;
cryptoKeys: CryptoKeysResource;
}
interface LocationsResource {
/** Get information about a location. */
get(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** Resource name for the location. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<Location>;
/** Lists information about the supported locations for this service. */
list(request: {
/** V1 error format. */
"$.xgafv"?: string;
/** OAuth access token. */
access_token?: string;
/** Data format for response. */
alt?: string;
/** OAuth bearer token. */
bearer_token?: string;
/** JSONP */
callback?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** The standard list filter. */
filter?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** The resource that owns the locations collection, if applicable. */
name: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The standard list page size. */
pageSize?: number;
/** The standard list page token. */
pageToken?: string;
/** Pretty-print response. */
pp?: boolean;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */
quotaUser?: string;
/** Legacy upload protocol for media (e.g. "media", "multipart"). */
uploadType?: string;
/** Upload protocol for media (e.g. "raw", "multipart"). */
upload_protocol?: string;
}): Request<ListLocationsResponse>;
keyRings: KeyRingsResource;
}
interface ProjectsResource {
locations: LocationsResource;
}
}
} | the_stack |
import { check } from '../../../lib/check'
import { RundownId } from '../../../lib/collections/Rundowns'
import { AdLibPiece } from '../../../lib/collections/AdLibPieces'
import { protectString, waitForPromise, ProtectedString } from '../../../lib/lib'
import { AdLibAction, AdLibActionId } from '../../../lib/collections/AdLibActions'
import { updateExpectedMediaItemsOnRundown } from './expectedMediaItems'
import {
ExpectedPackageDB,
ExpectedPackageDBBase,
ExpectedPackageDBFromAdLibAction,
ExpectedPackageDBFromBaselineAdLibAction,
ExpectedPackageDBFromBucketAdLib,
ExpectedPackageDBFromBucketAdLibAction,
ExpectedPackageDBFromPiece,
ExpectedPackageDBFromRundownBaselineObjects,
ExpectedPackageDBFromStudioBaselineObjects,
ExpectedPackageDBType,
ExpectedPackages,
getContentVersionHash,
} from '../../../lib/collections/ExpectedPackages'
import { Studio, Studios } from '../../../lib/collections/Studios'
import { BlueprintResultBaseline, ExpectedPackage } from '@sofie-automation/blueprints-integration'
import { Piece, PieceId } from '../../../lib/collections/Pieces'
import { BucketAdLibAction, BucketAdLibActionId, BucketAdLibActions } from '../../../lib/collections/BucketAdlibActions'
import { Meteor } from 'meteor/meteor'
import { BucketAdLib, BucketAdLibId, BucketAdLibs } from '../../../lib/collections/BucketAdlibs'
import { RundownBaselineAdLibAction } from '../../../lib/collections/RundownBaselineAdLibActions'
import {
updateBaselineExpectedPlayoutItemsOnRundown,
updateBaselineExpectedPlayoutItemsOnStudio,
updateExpectedPlayoutItemsOnRundown,
} from './expectedPlayoutItems'
import { PartInstance } from '../../../lib/collections/PartInstances'
import { PieceInstances } from '../../../lib/collections/PieceInstances'
import { CacheForIngest } from './cache'
import { asyncCollectionRemove, saveIntoDb } from '../../lib/database'
import { saveIntoCache } from '../../cache/lib'
import { ReadonlyDeep } from 'type-fest'
import { CacheForPlayout } from '../playout/cache'
import { CacheForStudio } from '../studio/cache'
export function updateExpectedPackagesOnRundown(cache: CacheForIngest): void {
// @todo: this call is for backwards compatibility and soon to be removed
updateExpectedMediaItemsOnRundown(cache)
updateExpectedPlayoutItemsOnRundown(cache)
const studio = cache.Studio.doc
const pieces = cache.Pieces.findFetch({})
const adlibs = cache.AdLibPieces.findFetch({})
const actions = cache.AdLibActions.findFetch({})
const baselineAdlibs = cache.RundownBaselineAdLibPieces.findFetch({})
const baselineActions = cache.RundownBaselineAdLibActions.findFetch({})
// todo: keep expectedPackage of the currently playing partInstance
const expectedPackages: ExpectedPackageDB[] = [
...generateExpectedPackagesForPiece(studio, cache.RundownId, pieces),
...generateExpectedPackagesForPiece(studio, cache.RundownId, adlibs),
...generateExpectedPackagesForAdlibAction(studio, cache.RundownId, actions),
...generateExpectedPackagesForPiece(studio, cache.RundownId, baselineAdlibs),
...generateExpectedPackagesForBaselineAdlibAction(studio, cache.RundownId, baselineActions),
]
saveIntoCache<ExpectedPackageDB, ExpectedPackageDB>(
cache.ExpectedPackages,
{
// RUNDOWN_BASELINE_OBJECTS follow their own flow
fromPieceType: { $ne: ExpectedPackageDBType.RUNDOWN_BASELINE_OBJECTS },
},
expectedPackages
)
}
export function generateExpectedPackagesForPartInstance(
studio: Studio,
rundownId: RundownId,
partInstance: PartInstance
) {
const packages: ExpectedPackageDBFromPiece[] = []
const pieceInstances = PieceInstances.find({
rundownId: rundownId,
partInstanceId: partInstance._id,
}).fetch()
for (const pieceInstance of pieceInstances) {
if (pieceInstance.piece.expectedPackages) {
const bases = generateExpectedPackageBases(
studio,
pieceInstance.piece._id,
pieceInstance.piece.expectedPackages
)
for (const base of bases) {
packages.push({
...base,
rundownId,
pieceId: pieceInstance.piece._id,
fromPieceType: ExpectedPackageDBType.PIECE,
})
}
}
}
return packages
}
function generateExpectedPackagesForPiece(
studio: ReadonlyDeep<Studio>,
rundownId: RundownId,
pieces: (Piece | AdLibPiece)[]
) {
const packages: ExpectedPackageDBFromPiece[] = []
for (const piece of pieces) {
if (piece.expectedPackages) {
const bases = generateExpectedPackageBases(studio, piece._id, piece.expectedPackages)
for (const base of bases) {
packages.push({
...base,
rundownId,
pieceId: piece._id,
fromPieceType: ExpectedPackageDBType.PIECE,
})
}
}
}
return packages
}
function generateExpectedPackagesForAdlibAction(
studio: ReadonlyDeep<Studio>,
rundownId: RundownId,
actions: AdLibAction[]
) {
const packages: ExpectedPackageDBFromAdLibAction[] = []
for (const action of actions) {
if (action.expectedPackages) {
const bases = generateExpectedPackageBases(studio, action._id, action.expectedPackages)
for (const base of bases) {
packages.push({
...base,
rundownId,
pieceId: action._id,
fromPieceType: ExpectedPackageDBType.ADLIB_ACTION,
})
}
}
}
return packages
}
function generateExpectedPackagesForBaselineAdlibAction(
studio: ReadonlyDeep<Studio>,
rundownId: RundownId,
actions: RundownBaselineAdLibAction[]
) {
const packages: ExpectedPackageDBFromBaselineAdLibAction[] = []
for (const action of actions) {
if (action.expectedPackages) {
const bases = generateExpectedPackageBases(studio, action._id, action.expectedPackages)
for (const base of bases) {
packages.push({
...base,
rundownId,
pieceId: action._id,
fromPieceType: ExpectedPackageDBType.BASELINE_ADLIB_ACTION,
})
}
}
}
return packages
}
function generateExpectedPackagesForBucketAdlib(studio: Studio, adlibs: BucketAdLib[]) {
const packages: ExpectedPackageDBFromBucketAdLib[] = []
for (const adlib of adlibs) {
if (adlib.expectedPackages) {
const bases = generateExpectedPackageBases(studio, adlib._id, adlib.expectedPackages)
for (const base of bases) {
packages.push({
...base,
pieceId: adlib._id,
fromPieceType: ExpectedPackageDBType.BUCKET_ADLIB,
})
}
}
}
return packages
}
function generateExpectedPackagesForBucketAdlibAction(studio: Studio, adlibActions: BucketAdLibAction[]) {
const packages: ExpectedPackageDBFromBucketAdLibAction[] = []
for (const action of adlibActions) {
if (action.expectedPackages) {
const bases = generateExpectedPackageBases(studio, action._id, action.expectedPackages)
for (const base of bases) {
packages.push({
...base,
pieceId: action._id,
fromPieceType: ExpectedPackageDBType.BUCKET_ADLIB_ACTION,
})
}
}
}
return packages
}
function generateExpectedPackageBases(
studio: ReadonlyDeep<Studio>,
ownerId: ProtectedString<any>,
expectedPackages: ExpectedPackage.Any[]
) {
const bases: Omit<ExpectedPackageDBBase, 'pieceId' | 'fromPieceType'>[] = []
let i = 0
for (const expectedPackage of expectedPackages) {
let id = expectedPackage._id
if (!id) id = '__unnamed' + i++
bases.push({
...expectedPackage,
_id: protectString(`${ownerId}_${id}`),
blueprintPackageId: id,
contentVersionHash: getContentVersionHash(expectedPackage),
studioId: studio._id,
})
}
return bases
}
export function updateExpectedPackagesForBucketAdLib(adlibId: BucketAdLibId): void {
check(adlibId, String)
const adlib = BucketAdLibs.findOne(adlibId)
if (!adlib) {
waitForPromise(cleanUpExpectedPackagesForBucketAdLibs([adlibId]))
throw new Meteor.Error(404, `Bucket Adlib "${adlibId}" not found!`)
}
const studio = Studios.findOne(adlib.studioId)
if (!studio) throw new Meteor.Error(404, `Studio "${adlib.studioId}" not found!`)
const packages = generateExpectedPackagesForBucketAdlib(studio, [adlib])
saveIntoDb(ExpectedPackages, { pieceId: adlibId }, packages)
}
export function updateExpectedPackagesForBucketAdLibAction(actionId: BucketAdLibActionId): void {
check(actionId, String)
const action = BucketAdLibActions.findOne(actionId)
if (!action) {
waitForPromise(cleanUpExpectedPackagesForBucketAdLibsActions([actionId]))
throw new Meteor.Error(404, `Bucket Action "${actionId}" not found!`)
}
const studio = Studios.findOne(action.studioId)
if (!studio) throw new Meteor.Error(404, `Studio "${action.studioId}" not found!`)
const packages = generateExpectedPackagesForBucketAdlibAction(studio, [action])
saveIntoDb(ExpectedPackages, { pieceId: actionId }, packages)
}
export async function cleanUpExpectedPackagesForBucketAdLibs(adLibIds: PieceId[]): Promise<void> {
check(adLibIds, [String])
await asyncCollectionRemove(ExpectedPackages, {
pieceId: {
$in: adLibIds,
},
})
}
export async function cleanUpExpectedPackagesForBucketAdLibsActions(adLibIds: AdLibActionId[]): Promise<void> {
check(adLibIds, [String])
await asyncCollectionRemove(ExpectedPackages, {
pieceId: {
$in: adLibIds,
},
})
}
export function updateBaselineExpectedPackagesOnRundown(
cache: CacheForIngest,
baseline: BlueprintResultBaseline
): void {
// @todo: this call is for backwards compatibility and soon to be removed
updateBaselineExpectedPlayoutItemsOnRundown(cache, baseline.expectedPlayoutItems)
const bases = generateExpectedPackageBases(cache.Studio.doc, cache.RundownId, baseline.expectedPackages ?? [])
saveIntoCache<ExpectedPackageDB, ExpectedPackageDB>(
cache.ExpectedPackages,
{
fromPieceType: ExpectedPackageDBType.RUNDOWN_BASELINE_OBJECTS,
},
bases.map(
(item): ExpectedPackageDBFromRundownBaselineObjects => {
return {
...item,
fromPieceType: ExpectedPackageDBType.RUNDOWN_BASELINE_OBJECTS,
rundownId: cache.RundownId,
pieceId: null,
}
}
)
)
}
export function updateBaselineExpectedPackagesOnStudio(
cache: CacheForStudio | CacheForPlayout,
baseline: BlueprintResultBaseline
): void {
// @todo: this call is for backwards compatibility and soon to be removed
updateBaselineExpectedPlayoutItemsOnStudio(cache, baseline.expectedPlayoutItems)
const bases = generateExpectedPackageBases(cache.Studio.doc, cache.Studio.doc._id, baseline.expectedPackages ?? [])
cache.deferAfterSave(() => {
saveIntoDb<ExpectedPackageDB, ExpectedPackageDB>(
ExpectedPackages,
{
studioId: cache.Studio.doc._id,
fromPieceType: ExpectedPackageDBType.STUDIO_BASELINE_OBJECTS,
},
bases.map(
(item): ExpectedPackageDBFromStudioBaselineObjects => {
return {
...item,
fromPieceType: ExpectedPackageDBType.STUDIO_BASELINE_OBJECTS,
pieceId: null,
}
}
)
)
})
} | the_stack |
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { AssetGroupObservableService } from '../../../core/services/asset-group-observable.service';
import { AutorefreshService } from '../../services/autorefresh.service';
import { environment } from './../../../../environments/environment';
import { Router, ActivatedRoute } from '@angular/router';
import { LoggerService } from '../../../shared/services/logger.service';
import { UtilsService } from '../../../shared/services/utils.service';
import { WorkflowService } from '../../../core/services/workflow.service';
import { CommonResponseService } from '../../../shared/services/common-response.service';
@Component({
selector: 'app-overall-vulnerabilities',
templateUrl: './overall-vulnerabilities.component.html',
styleUrls: ['./overall-vulnerabilities.component.css'],
providers: [AutorefreshService]
})
export class OverallVulnerabilitiesComponent implements OnInit, OnDestroy {
subscriptionToAssetGroup: Subscription;
dataSubscription: Subscription;
selectedAssetGroup;
durationParams;
autoRefresh;
autorefreshInterval;
errorVal = 0;
errorMessage = 'apiResponseError';
urlToRedirect;
routeTo = 'vulnerabilities';
vulnData;
donutData = {};
widgetWidth = 210;
widgetHeight = 250;
innerRadius: any = 0;
selectedLink = 0;
outerRadius: any = 50;
errorSumVal = 0;
cntInterval;
selectedLevel = 0;
lastLevelData;
lastLevelSelectedKeys;
modifiedResponse;
selectedGraph = 'total';
colorsData = {
inscope: '#00B946',
exempted: '#BA808A',
S3: '#ffe003',
S4: '#f75c03',
S5: '#da0c0c',
compliant: '#00B946',
noncompliant: '#E60127',
scanned: '#00B946',
unscanned: '#BA808A'
};
donutObj;
linksData = [{name: 'Total', level: 0, key: 'total'}, {name: 'Inscope', level: 1, key: 'inscope'}, {name: 'Scanned', level: 2, key: 'scanned'}, {name: 'Non Compliant', level: 3, key: 'noncompliant'}, {name: 'Compliant', level: 3, key: 'compliant'}];
constructor(private commonResponseService: CommonResponseService,
private assetGroupObservableService: AssetGroupObservableService,
private autorefreshService: AutorefreshService,
private logger: LoggerService,
private router: Router,
private utils: UtilsService,
private activatedRoute: ActivatedRoute,
private workflowService: WorkflowService) {
this.subscriptionToAssetGroup = this.assetGroupObservableService.getAssetGroup().subscribe(
assetGroupName => {
this.selectedAssetGroup = assetGroupName;
this.updateComponent();
});
this.durationParams = this.autorefreshService.getDuration();
this.durationParams = parseInt(this.durationParams, 10);
this.autoRefresh = this.autorefreshService.autoRefresh;
}
ngOnInit() {
this.urlToRedirect = this.router.routerState.snapshot.url;
const afterLoad = this;
if (this.autoRefresh !== undefined) {
if ((this.autoRefresh === true ) || (this.autoRefresh.toString() === 'true')) {
this.autorefreshInterval = setInterval(function() {
afterLoad.getData();
}, this.durationParams);
}
}
}
navigatePage() {
try {
this.workflowService.addRouterSnapshotToLevel(this.router.routerState.snapshot.root);
const eachParams = {};
const newParams = this.utils.makeFilterObj(eachParams);
if (this.routeTo !== undefined ) {
this.router.navigate(['../vulnerabilities-compliance', this.routeTo], { relativeTo: this.activatedRoute, queryParams: newParams, queryParamsHandling: 'merge'});
}
} catch (error) {
this.logger.log('error', error);
}
}
updateComponent() {
this.errorVal = 0;
this.errorSumVal = 0;
this.selectedLink = 0;
this.selectedGraph = 'total';
this.donutData = {};
this.selectedLevel = 0;
if (this.cntInterval) {
clearInterval(this.cntInterval);
}
this.getData();
}
clearLinkInterval() {
if (this.cntInterval) {
clearInterval(this.cntInterval);
}
this.widgetWidth = 210 - this.linksData[this.selectedLink].level * 10;
this.selectedLevel = this.linksData[this.selectedLink].level;
this.selectedGraph = this.linksData[this.selectedLink].key;
}
getData() {
this.getSummaryData();
this.getGraphData();
}
getSummaryData() {
if (this.dataSubscription) {
this.dataSubscription.unsubscribe();
}
const queryParams = {
'ag': this.selectedAssetGroup
};
const vulnerabilitySummaryUrl = environment.vulnerabilitySummary.url;
const vulnerabilitySummaryMethod = environment.vulnerabilitySummary.method;
this.dataSubscription = this.commonResponseService.getData(vulnerabilitySummaryUrl, vulnerabilitySummaryMethod, {}, queryParams).subscribe(
response => {
try {
if (!response.distribution) {
this.errorSumVal = -1;
this.errorMessage = 'noDataAvailable';
this.logger.log('error', 'noDataAvailable');
} else {
this.errorSumVal = 1;
this.vulnData = response.distribution;
}
} catch (error) {
this.errorMessage = 'jsError';
this.logger.log('error', error);
this.errorSumVal = -1;
}
},
error => {
this.errorMessage = 'apiResponseError';
this.logger.log('error', error);
this.errorSumVal = -1;
});
}
getGraphData() {
const queryParams = {
'ag': this.selectedAssetGroup
};
const vulnerabilitySummaryUrl = environment.vulnerabilityGraphSummary.url;
const vulnerabilitySummaryMethod = environment.vulnerabilityGraphSummary.method;
this.commonResponseService.getData(vulnerabilitySummaryUrl, vulnerabilitySummaryMethod, {}, queryParams).subscribe(
response => {
try {
if (!response.count && response.count !== 0 && response.count !== '0') {
this.errorVal = -1;
this.errorMessage = 'noDataAvailable';
this.logger.log('error', 'noDataAvailable');
} else {
this.createObjectForVulSummary(response);
const self = this;
this.cntInterval = setInterval(function(){
if (self.selectedLink < self.linksData.length - 1) {
self.selectedLink++;
} else {
self.selectedLink = 0;
}
self.widgetWidth = 210 - self.linksData[self.selectedLink].level * 10;
self.selectedLevel = self.linksData[self.selectedLink].level;
self.selectedGraph = self.linksData[self.selectedLink].key;
}, 7000);
this.errorVal = 1;
}
} catch (error) {
this.errorMessage = 'jsError';
this.logger.log('error', error);
this.errorVal = -1;
}
},
error => {
this.errorMessage = 'apiResponseError';
this.logger.log('error', error);
this.errorVal = -1;
});
}
createObjectForVulSummary(apiResponse) {
this.lastLevelSelectedKeys = [];
this.lastLevelData = {};
this.donutData = {};
this.modifiedResponse = this.processGraphData(apiResponse, null, this.donutData);
}
processGraphData(data, parent, donutData) {
this.donutObj = {};
if (data) {
const currentData = JSON.parse(JSON.stringify(data));
const currentObj = Object.keys(currentData);
this.donutObj = {
'color': [],
'data': [], 'legendWithText': [],
'legendTextcolor': '#000',
'legend': '',
'totalCount': 0,
'centerText': 'Total',
'link': false,
'styling': {
'cursor': 'pointer'
},
'cursor': []
};
const selectedKeys = [];
for (let i = 0; i < currentObj.length; i++) {
if (currentObj[i].toLowerCase() !== 'total' && currentObj[i].toLowerCase() !== 'count') {
this.donutObj['legendWithText'].push(currentObj[i]);
this.donutObj['color'].push(this.colorsData[currentObj[i]]);
this.donutObj['data'].push(currentData[currentObj[i]].count);
this.donutObj['totalCount'] += currentData[currentObj[i]].count;
if (currentObj[i].toLowerCase() === 'inscope' || currentObj[i].toLowerCase() === 'scanned' || currentObj[i].toLowerCase() === 'compliant' || currentObj[i].toLowerCase() === 'noncompliant' ) {
this.donutObj['cursor'].push('pointer');
} else {
this.donutObj['cursor'].push('default');
}
if (Object.keys(currentData[currentObj[i]]).length > 1) {
selectedKeys.push(currentObj[i]);
}
}
}
if (parent) {
donutData[parent] = this.donutObj;
} else {
donutData['total'] = this.donutObj;
}
for (let j = selectedKeys.length - 1; j >= 0; j--) {
if (j === selectedKeys.length - 1) {
this.lastLevelData = currentData;
this.lastLevelSelectedKeys = selectedKeys;
}
const pop = this.lastLevelSelectedKeys[j];
this.processGraphData(this.lastLevelData[pop], pop, donutData);
}
}
return donutData;
}
pieClicked(data) {
const type = data.legend;
if (type === 'inscope' || type === 'scanned' || type === 'noncompliant' || type === 'compliant') {
if (this.cntInterval) {
clearInterval(this.cntInterval);
}
this.selectedGraph = type;
for (let i = 0; i < this.linksData.length; i++ ) {
if (this.selectedGraph === this.linksData[i].key) {
this.selectedLink = i;
break;
}
this.widgetWidth = 210 - this.linksData[this.selectedLink].level * 10;
this.selectedLevel = this.linksData[this.selectedLink].level;
}
}
}
ngOnDestroy() {
this.subscriptionToAssetGroup.unsubscribe();
if (this.dataSubscription) {
this.dataSubscription.unsubscribe();
}
clearInterval(this.autorefreshInterval);
clearInterval(this.cntInterval);
}
} | the_stack |
import {
ChangeDetectorRef,
ElementRef,
EventEmitter,
Injectable,
OnDestroy,
} from '@angular/core';
import { WindowRef } from '@spartacus/core';
import {
SceneNodeToProductLookupService,
VisualizationLookupService,
} from '@spartacus/epd-visualization/core';
import {
ContentType,
EpdVisualizationConfig,
EpdVisualizationInnerConfig,
Ui5Config,
VisualizationApiConfig,
VisualizationInfo,
} from '@spartacus/epd-visualization/root';
import { BehaviorSubject, Observable, of, Subscription } from 'rxjs';
import {
catchError,
filter,
first,
mergeMap,
shareReplay,
} from 'rxjs/operators';
import type Core from 'sap/ui/core/Core';
import type { CSSColor } from 'sap/ui/core/library';
import type UIArea from 'sap/ui/core/UIArea';
import type AnimationPlayer from 'sap/ui/vk/AnimationPlayer';
import type ContentConnector from 'sap/ui/vk/ContentConnector';
import type ContentResource from 'sap/ui/vk/ContentResource';
import type DrawerToolbar from 'sap/ui/vk/DrawerToolbar';
import NodeHierarchy from 'sap/ui/vk/NodeHierarchy';
import type Scene from 'sap/ui/vk/Scene';
import type Viewport from 'sap/ui/vk/Viewport';
import type ViewStateManager from 'sap/ui/vk/ViewStateManager';
import { NavigationMode } from './models/navigation-mode';
import { NodeContentType } from './models/node-content-type';
import { LoadedSceneInfo, SceneLoadInfo } from './models/scene-load-info';
import { SceneLoadState } from './models/scene-load-state';
import { SelectionMode } from './models/selection-mode';
import {
VisualizationLoadInfo,
VisualizationLoadStatus,
VisualizationLookupResult,
} from './models/visualization-load-info';
import { ZoomTo } from './models/zoom-to';
type ViewManager = any;
type NodeRef = any;
type ViewInfo = any;
interface VisualContentChangesFinishedEvent {
content: any;
failureReason: any;
}
interface VisualContentLoadFinishedEvent {}
@Injectable({
providedIn: 'any',
})
export class VisualViewerService implements OnDestroy {
constructor(
protected epdVisualizationConfig: EpdVisualizationConfig,
protected _sceneNodeToProductLookupService: SceneNodeToProductLookupService,
protected visualizationLookupService: VisualizationLookupService,
protected elementRef: ElementRef,
protected changeDetectorRef: ChangeDetectorRef,
protected windowRef: WindowRef
) {
if (!this.windowRef.isBrowser()) {
return;
}
const ui5BootStrapped$: Observable<void> =
this.bootstrapUi5('ui5bootstrap');
const ui5Initialized$: Observable<void> = ui5BootStrapped$.pipe(
mergeMap(this.initializeUi5.bind(this))
);
this.viewportAdded$ = ui5Initialized$.pipe(
mergeMap(this.addViewport.bind(this)),
shareReplay()
);
this.executeWhenSceneLoaded(this.setInitialPropertyValues.bind(this));
}
ngOnDestroy(): void {
this.selectedNodeIdsSubscription?.unsubscribe();
}
private selectedNodeIdsSubscription?: Subscription;
private get sceneNodeToProductLookupService(): SceneNodeToProductLookupService {
return this._sceneNodeToProductLookupService;
}
private set sceneNodeToProductLookupService(
value: SceneNodeToProductLookupService
) {
this._sceneNodeToProductLookupService = value;
}
private _scene: Scene;
private get scene(): Scene {
return this._scene;
}
private set scene(value: Scene) {
this._scene = value;
}
private _nodeHierarchy: NodeHierarchy;
private get nodeHierarchy(): NodeHierarchy {
return this._nodeHierarchy;
}
private set nodeHierarchy(value: NodeHierarchy) {
this._nodeHierarchy = value;
}
private _contentConnector: ContentConnector;
private get contentConnector(): ContentConnector {
return this._contentConnector;
}
private set contentConnector(value: ContentConnector) {
this._contentConnector = value;
}
private _viewport: Viewport;
private get viewport(): Viewport {
return this._viewport;
}
private set viewport(value: Viewport) {
this._viewport = value;
}
private _viewStateManager: ViewStateManager;
private get viewStateManager(): ViewStateManager {
return this._viewStateManager;
}
private set viewStateManager(value: ViewStateManager) {
this._viewStateManager = value;
}
private _animationPlayer: AnimationPlayer;
private get animationPlayer(): AnimationPlayer {
return this._animationPlayer;
}
private set animationPlayer(value: AnimationPlayer) {
this._animationPlayer = value;
}
private _viewManager: ViewManager;
private get viewManager(): ViewManager {
return this._viewManager;
}
private set viewManager(value: ViewManager) {
this._viewManager = value;
}
private _drawerToolbar: DrawerToolbar;
private get drawerToolbar(): DrawerToolbar {
return this._drawerToolbar;
}
private set drawerToolbar(value: DrawerToolbar) {
this._drawerToolbar = value;
}
private _sceneId: string;
private get sceneId(): string {
return this._sceneId;
}
private set sceneId(value: string) {
this._sceneId = value;
}
private _contentType: ContentType;
private get contentType(): ContentType {
return this._contentType;
}
private set contentType(value: ContentType) {
this._contentType = value;
}
private _initialViewInfo: ViewInfo;
private get initialViewInfo(): ViewInfo {
return this._initialViewInfo;
}
private set initialViewInfo(value: ViewInfo) {
this._initialViewInfo = value;
}
private _leafNodeRefs: NodeRef[];
private get leafNodeRefs(): NodeRef[] {
return this._leafNodeRefs;
}
private set leafNodeRefs(value: NodeRef[]) {
this._leafNodeRefs = value;
}
private _viewPriorToIsolateViewInfo: any;
private get viewPriorToIsolateViewInfo(): any {
return this._viewPriorToIsolateViewInfo;
}
private set viewPriorToIsolateViewInfo(value: any) {
this._viewPriorToIsolateViewInfo = value;
}
private _viewportAdded$: Observable<void>;
private get viewportAdded$(): Observable<void> {
return this._viewportAdded$;
}
private set viewportAdded$(value: Observable<void>) {
this._viewportAdded$ = value;
}
private _selectedNodeIds$ = new BehaviorSubject<string[]>([]);
private get selectedNodeIds$(): BehaviorSubject<string[]> {
return this._selectedNodeIds$;
}
private set selectedNodeIds$(value: BehaviorSubject<string[]>) {
this._selectedNodeIds$ = value;
}
private _sceneLoadInfo$ = new BehaviorSubject<SceneLoadInfo>({
sceneLoadState: SceneLoadState.NotStarted,
});
public get sceneLoadInfo$(): BehaviorSubject<SceneLoadInfo> {
return this._sceneLoadInfo$;
}
protected readonly DEFAULT_BACKGROUND_TOP_COLOR = '--cx-color-inverse';
protected readonly DEFAULT_BACKGROUND_BOTTOM_COLOR = '--cx-color-inverse';
protected readonly DEFAULT_HOTSPOT_SELECTION_HIGHLIGHT_COLOR =
'rgba(255, 0, 0, 0.6)';
protected readonly DEFAULT_SHOW_ALL_HOTSPOTS_COLOR = 'rgba(255, 255, 0, 0.3)';
protected readonly DEFAULT_OUTLINE_COLOR = 'red';
protected readonly DEFAULT_OUTLINE_WIDTH = 5;
protected readonly DEFAULT_SELECTION_MODE = SelectionMode.Exclusive;
protected readonly DEFAULT_SHOW_ALL_HOTSPOTS_ENABLED = false;
protected readonly DEFAULT_EXCLUDED_OPACITY = 0.2;
protected readonly DEFAULT_ZOOM_TO_MARGIN = 0.2;
protected readonly DEFAULT_FLY_TO_DURATION = 1;
private _flyToDurationInSeconds = this.DEFAULT_FLY_TO_DURATION;
private get flyToDurationInSeconds() {
return this._flyToDurationInSeconds;
}
private set flyToDurationInSeconds(value) {
this._flyToDurationInSeconds = value;
}
private _zoomToMargin = this.DEFAULT_ZOOM_TO_MARGIN;
private get zoomToMargin() {
return this._zoomToMargin;
}
private set zoomToMargin(value) {
this._zoomToMargin = value;
}
/**
* The top colour of the background gradient.
* Can be passed in the CSS color format or as a Spartacus theme color i.e. '--cx-color-background' with the quotes.
*/
public set backgroundTopColor(backgroundTopColor: string) {
if (!this.windowRef.isBrowser()) {
return;
}
if (this._backgroundTopColor === backgroundTopColor) {
return;
}
this._backgroundTopColor = backgroundTopColor;
this.executeWhenSceneLoaded(() => {
this.viewport.setBackgroundColorTop(this.getCSSColor(backgroundTopColor));
});
}
public get backgroundTopColor(): string {
return this._backgroundTopColor;
}
private _backgroundTopColor: string;
/**
* The bottom colour of the background gradient.
* Can be passed in the CSS color format or as a Spartacus theme color i.e. '--cx-color-background' with the quotes.
*/
public set backgroundBottomColor(backgroundBottomColor: string) {
if (!this.windowRef.isBrowser()) {
return;
}
if (this._backgroundBottomColor === backgroundBottomColor) {
return;
}
this._backgroundBottomColor = backgroundBottomColor;
this.executeWhenSceneLoaded(() => {
this.viewport.setBackgroundColorBottom(
this.getCSSColor(backgroundBottomColor)
);
});
}
public get backgroundBottomColor(): string {
return this._backgroundBottomColor;
}
private _backgroundBottomColor: string;
/**
* The colour applied to selected 2D hotspots in 2D content.
* Can be passed in the CSS color format or as a Spartacus theme color i.e. '--cx-color-primary' with the quotes.
*/
public set hotspotSelectionColor(hotspotSelectionColor: string) {
if (!this.windowRef.isBrowser()) {
return;
}
if (this._hotspotSelectionColor === hotspotSelectionColor) {
return;
}
this._hotspotSelectionColor = hotspotSelectionColor;
this.executeWhenSceneLoaded(() => {
this.viewStateManager.setHighlightColor(
this.getCSSColor(hotspotSelectionColor)
);
});
}
public get hotspotSelectionColor(): string {
return this._hotspotSelectionColor;
}
private _hotspotSelectionColor: string;
/**
* Highlights all hotspots in 2D content that are included in the includedProductCodes property using the colour specified by the showAllHotspotsColor property.
*/
public set showAllHotspotsEnabled(showAllHotspotsEnabled: boolean) {
if (!this.windowRef.isBrowser()) {
return;
}
if (this._showAllHotspotsEnabled === showAllHotspotsEnabled) {
return;
}
this._showAllHotspotsEnabled = showAllHotspotsEnabled;
this.executeWhenSceneLoaded(() => {
this.applyInclusionStyle(this._includedProductCodes);
});
}
public get showAllHotspotsEnabled(): boolean {
return this._showAllHotspotsEnabled;
}
private _showAllHotspotsEnabled: boolean;
/**
* The colour used to highlight hotspots in 2D content when the showAllHotspotsEnabled property has a value of true.
* Can be passed in the CSS color format or as a Spartacus theme color i.e. '--cx-color-primary' with the quotes.
*/
public set showAllHotspotsColor(showAllHotspotsColor: string) {
if (!this.windowRef.isBrowser()) {
return;
}
if (this._showAllHotspotsColor === showAllHotspotsColor) {
return;
}
this._showAllHotspotsColor = showAllHotspotsColor;
this.executeWhenSceneLoaded(() => {
const cssColor = this.getCSSColor(showAllHotspotsColor);
this.viewport.setShowAllHotspotsTintColor(cssColor);
});
}
public get showAllHotspotsColor(): string {
return this._showAllHotspotsColor;
}
private _showAllHotspotsColor: string;
/**
* The outline colour used to indicate selected objects in 3D content.
* Can be passed in the CSS color format or as a Spartacus theme color i.e. '--cx-color-primary' with the quotes.
*/
public set outlineColor(outlineColor: string) {
if (!this.windowRef.isBrowser()) {
return;
}
if (this._outlineColor === outlineColor) {
return;
}
this._outlineColor = outlineColor;
this.executeWhenSceneLoaded(() => {
this.viewStateManager.setOutlineColor(this.getCSSColor(outlineColor));
});
}
public get outlineColor(): string {
return this._outlineColor;
}
private _outlineColor: string;
/**
* The width of the outline used to indicate selected objects in 3D content.
*/
public set outlineWidth(outlineWidth: number) {
if (!this.windowRef.isBrowser()) {
return;
}
if (this._outlineWidth === outlineWidth) {
return;
}
this._outlineWidth = outlineWidth;
this.executeWhenSceneLoaded(() => {
this.viewStateManager.setOutlineWidth(outlineWidth);
});
}
public get outlineWidth(): number {
return this._outlineWidth;
}
private _outlineWidth: number;
/**
* The selection mode.
* None - Selection is disabled.
* Exclusive - When selecting objects in the viewport, at most one object can be selected at a time. Clicking/tapping to select a new object will deselect any previously selected objects.
* Sticky - A multiple selection mode in which clicking/tapping on an object that is not part of the current selection will toggle its selection state without modifying the selection state of the currently selected objects.
*/
public set selectionMode(selectionMode: SelectionMode) {
if (!this.windowRef.isBrowser()) {
return;
}
if (this._selectionMode === selectionMode) {
return;
}
this._selectionMode = selectionMode;
this.executeWhenSceneLoaded(() => {
this.viewport.setSelectionMode(selectionMode);
});
}
public get selectionMode(): SelectionMode {
return this._selectionMode;
}
private _selectionMode: SelectionMode;
/**
* Gets/sets the selection in terms of product codes.
* Gets the set of product codes applied to the selected scene nodes.
* Sets the selection set based on the set of supplied product codes.
*/
public set selectedProductCodes(selectedProductCodes: string[]) {
if (!this.windowRef.isBrowser()) {
return;
}
this._selectedProductCodes = selectedProductCodes;
this.sceneNodeToProductLookupService
.lookupNodeIds(selectedProductCodes)
.pipe(first())
.subscribe((selectedNodeIds: string[]) => {
this.selectedNodeIds$.next(selectedNodeIds);
});
}
public get selectedProductCodes(): string[] {
return this._selectedProductCodes;
}
private _selectedProductCodes: string[];
selectedProductCodesChange = new EventEmitter<string[]>();
/**
* Gets/sets which objects should be selectable (in terms of product codes).
* For 3D content:
* - objects that are included will be selectable and opaque
* - objects that are not included will not be selectable and will have an opacity specified by the excludedOpacity property.
*
* For 2D content:
* - hotspots that are included will be selectable and can be made visible
* - hotspots that are not included will not be selectable or visible
*/
public set includedProductCodes(includedProductCodes: string[]) {
if (!this.windowRef.isBrowser()) {
return;
}
this._includedProductCodes = includedProductCodes;
this.executeWhenSceneLoaded(() => {
this.applyInclusionStyle(includedProductCodes);
});
}
public get includedProductCodes(): string[] {
return this._includedProductCodes;
}
private _includedProductCodes: string[];
/**
* Gets/sets the opacity to apply to 3D objects that are not in the set specified by the includedProductCodes property.
*/
public set excludedOpacity(excludedOpacity: number) {
if (!this.windowRef.isBrowser()) {
return;
}
this._excludedOpacity = excludedOpacity;
}
public get excludedOpacity(): number {
return this._excludedOpacity;
}
private _excludedOpacity: number = this.DEFAULT_EXCLUDED_OPACITY;
/**
* The current time position in seconds in the animation (if there is one).
*/
public set animationTime(animationTime: number) {
if (!this.windowRef.isBrowser()) {
return;
}
this._animationTime = animationTime;
}
public get animationTime(): number {
return this._animationTime;
}
private _animationTime: number;
animationTimeChange = new EventEmitter<number>();
/**
* The total duration of the animation in seconds.
* Returns 0 when there is no animation present (or when a scene has not been loaded).
*/
public get animationTotalDuration(): number {
if (this.animationPlayer) {
return this.animationPlayer.getTotalDuration();
}
return 0;
}
/**
* The animation playback position as a fractional value between 0 (start) and 1 (end).
*/
public set animationPosition(position: number) {
if (!this.windowRef.isBrowser()) {
return;
}
if (this._animationPosition === position) {
return;
}
this._animationPosition = position;
this.executeWhenSceneLoaded(() => {
const time = position * this.animationPlayer.getTotalDuration();
this.animationPlayerSetTime(time, false);
});
}
public get animationPosition(): number {
return this._animationPosition;
}
private _animationPosition: number = 0;
animationPositionChange = new EventEmitter<number>();
/**
* Gets/sets whether the animation (if there is one) is currently playing.
*/
public set animationPlaying(animationPlaying: boolean) {
if (!this.windowRef.isBrowser()) {
return;
}
if (this._animationPlaying === animationPlaying) {
return;
}
this._animationPlaying = animationPlaying;
this.executeWhenSceneLoaded(() => {
if (animationPlaying) {
if (this.animationPosition >= 1) {
this.animationPlayerSetTime(0, false);
}
this.animationPlayer.play();
} else {
this.animationPlayer.stop();
}
this.animationPlayingChange.emit(animationPlaying);
});
}
public get animationPlaying(): boolean {
return this._animationPlaying;
}
private _animationPlaying: boolean = false;
animationPlayingChange = new EventEmitter<boolean>();
/**
* Controls the behaviour when a left mouse button drag is initiated in the viewport.
* Turntable: A left mouse drag performs a turntable mode rotation.
* Pan: A left mouse drag pans the camera in the viewport.
* Zoom: A left mouse drag zooms the camera in the viewport in or out
*/
public set navigationMode(navigationMode: NavigationMode) {
if (!this.windowRef.isBrowser()) {
return;
}
if (this._navigationMode === navigationMode) {
return;
}
this._navigationMode = navigationMode;
this.executeWhenSceneLoaded(() => {
if (this.drawerToolbar && this.viewport) {
// sap.ui.vk library will have a public API to set the navigation mode in a future UI5 version
(this.drawerToolbar as any)._activateGesture(
(this.viewport as any).getImplementation(),
navigationMode
);
}
});
}
public get navigationMode(): NavigationMode {
return this._navigationMode;
}
private _navigationMode: NavigationMode;
/**
* Isolate mode allows a single object to be viewed in isolation.
*/
public set isolateModeEnabled(isolateModeEnabled: boolean) {
if (!this.windowRef.isBrowser()) {
return;
}
if (this._isolateModeEnabled === isolateModeEnabled) {
return;
}
this.executeWhenSceneLoaded(() => {
this._isolateModeEnabled = isolateModeEnabled;
if (isolateModeEnabled) {
this.viewPriorToIsolateViewInfo = this.viewport.getViewInfo({
camera: true,
visibility: true,
});
const selectedNodeRefs: NodeRef[] = [];
if (this.is2D) {
this.viewStateManager.enumerateSelection((nodeRef: NodeRef) =>
selectedNodeRefs.push(nodeRef)
);
} else {
this.viewStateManager.enumerateOutlinedNodes((nodeRef: NodeRef) =>
selectedNodeRefs.push(nodeRef)
);
}
this.isolateNodes(selectedNodeRefs);
} else {
this.viewport.setViewInfo(
this.viewPriorToIsolateViewInfo,
this.flyToDurationInSeconds
);
}
this.isolateModeEnabledChange.emit(this.isolateModeEnabled);
});
}
public get isolateModeEnabled(): boolean {
return this._isolateModeEnabled;
}
private _isolateModeEnabled = false;
isolateModeEnabledChange = new EventEmitter<boolean>();
/**
* Gets whether the viewport is displaying 2D content.
*/
public get is2D(): boolean {
return this._is2D;
}
private setIs2D(is2D: boolean) {
this._is2D = is2D;
}
private _is2D: boolean;
/**
* Indicates that a scene has been loaded and the viewport is ready for interaction.
*/
public get viewportReady(): boolean {
return this._viewportReady;
}
private setViewportReady(viewportReady: boolean) {
if (this._viewportReady === viewportReady) {
return;
}
this._viewportReady = viewportReady;
this.viewportReadyChange.emit(viewportReady);
}
private _viewportReady = false;
viewportReadyChange = new EventEmitter<boolean>();
/**
* Returns the user to the initial camera position used when a scene was first loaded.
*/
public activateHomeView(): void {
if (!this.windowRef.isBrowser()) {
return;
}
if (this.is2D) {
this.viewport.zoomTo(
ZoomTo.All,
null,
this.flyToDurationInSeconds,
this.zoomToMargin
);
} else {
this.viewport.setViewInfo(
this.initialViewInfo,
this.flyToDurationInSeconds
);
}
if (this.isolateModeEnabled) {
// Exit out of the isolate mode but don't restore the view that was
// saved before entering isolate mode
this._isolateModeEnabled = false;
this.isolateModeEnabledChange.emit(false);
}
}
/**
* Plays the animation (if one exists).
*/
public playAnimation(): void {
if (!this.windowRef.isBrowser()) {
return;
}
this.animationPlaying = true;
}
/**
* Pauses animation playback.
*/
public pauseAnimation(): void {
if (!this.windowRef.isBrowser()) {
return;
}
this.animationPlaying = false;
}
private contentChangesFinished =
new EventEmitter<VisualContentChangesFinishedEvent>();
private contentLoadFinished =
new EventEmitter<VisualContentLoadFinishedEvent>();
private setInitialPropertyValues(): void {
if (this.backgroundTopColor === undefined) {
this.backgroundTopColor = this.DEFAULT_BACKGROUND_TOP_COLOR;
}
if (this.backgroundBottomColor === undefined) {
this.backgroundBottomColor = this.DEFAULT_BACKGROUND_BOTTOM_COLOR;
}
if (this.hotspotSelectionColor === undefined) {
this.hotspotSelectionColor =
this.DEFAULT_HOTSPOT_SELECTION_HIGHLIGHT_COLOR;
}
if (this.showAllHotspotsColor === undefined) {
this.showAllHotspotsColor = this.DEFAULT_SHOW_ALL_HOTSPOTS_COLOR;
}
if (this.outlineColor === undefined) {
this.outlineColor = this.DEFAULT_OUTLINE_COLOR;
}
if (this.outlineWidth === undefined) {
this.outlineWidth = this.DEFAULT_OUTLINE_WIDTH;
}
if (this.selectionMode === undefined) {
this.selectionMode = this.DEFAULT_SELECTION_MODE;
}
if (this.showAllHotspotsEnabled === undefined) {
this.showAllHotspotsEnabled = this.DEFAULT_SHOW_ALL_HOTSPOTS_ENABLED;
}
if (this.is2D) {
if (
this.navigationMode === undefined ||
this.navigationMode === NavigationMode.Turntable
) {
this.navigationMode = NavigationMode.Pan;
}
} else if (this.navigationMode === undefined) {
this.navigationMode = NavigationMode.Turntable;
}
if (this.selectedProductCodes === undefined) {
this.selectedProductCodes = this.selectedNodeIds$.getValue();
}
}
private executeWhenSceneLoaded(
callback: (loadedSceneInfo: LoadedSceneInfo) => void
): void {
this.sceneLoadInfo$
.pipe(
filter(
(sceneLoadInfo: { sceneLoadState: SceneLoadState }) =>
sceneLoadInfo.sceneLoadState === SceneLoadState.Loaded ||
sceneLoadInfo.sceneLoadState === SceneLoadState.Failed
),
first()
)
.subscribe((sceneLoadInfo: SceneLoadInfo) => {
if (sceneLoadInfo.sceneLoadState === SceneLoadState.Loaded) {
callback(sceneLoadInfo.loadedSceneInfo as LoadedSceneInfo);
}
});
}
private applyInclusionStyle(productCodes: string[]): void {
if (productCodes === undefined) {
return;
}
this.sceneNodeToProductLookupService
.lookupNodeIds(productCodes)
.pipe(first())
.subscribe((sceneNodeIds: string[]) => {
if (this.is2D) {
this.applyInclusionStyle2D(sceneNodeIds);
} else {
this.applyInclusionStyle3D(sceneNodeIds);
}
});
}
private applyInclusionStyle2D(sceneNodeIds: string[]): void {
const nodeRefsToInclude: NodeRef[] = this.persistentIdToNodeRef(
sceneNodeIds,
true
);
const hotspotNodeRefs: NodeRef[] = this.nodeHierarchy.getHotspotNodeIds();
const hotspotNodeRefsSet: Set<NodeRef> = new Set(hotspotNodeRefs);
// Hotspot nodes can have descendants that are also Hotspot nodes.
// Ignore the descendant nodes and apply modifications at the highest level only.
const topLevelHotspotNodeRefs: NodeRef[] = hotspotNodeRefs.filter(
(hotspotNodeRef: NodeRef) =>
this.isTopLevelHotspotNode(hotspotNodeRef, hotspotNodeRefsSet)
);
if (this._showAllHotspotsEnabled) {
const nodeRefsToIncludeSet = new Set(nodeRefsToInclude);
const nodeRefsToExclude: NodeRef[] = topLevelHotspotNodeRefs.filter(
(nodeRef: NodeRef) => !nodeRefsToIncludeSet.has(nodeRef)
);
this.viewport.showHotspots(nodeRefsToExclude, false, null);
this.viewport.showHotspots(
nodeRefsToInclude,
true,
this.getCSSColor(this._showAllHotspotsColor)
);
} else {
this.viewport.showHotspots(topLevelHotspotNodeRefs, false, null);
}
}
private applyInclusionStyle3D(sceneNodeIds: string[]): void {
const nodeRefsToInclude: NodeRef[] = this.persistentIdToNodeRef(
sceneNodeIds,
true
);
if (!this.leafNodeRefs) {
this.leafNodeRefs = this.getAllLeafNodeRefs();
}
const leafNodeRefsToInclude = nodeRefsToInclude.flatMap(
(nodeRef: NodeRef) => this.getLeafDescendants(nodeRef, [])
);
const leafNodeRefsToIncludeSet = new Set(leafNodeRefsToInclude);
const leafNodeRefsToExclude = this.leafNodeRefs.filter(
(leafNodeRef: NodeRef) => !leafNodeRefsToIncludeSet.has(leafNodeRef)
);
this.viewStateManager.setOpacity(
leafNodeRefsToExclude,
this.excludedOpacity
);
leafNodeRefsToInclude.forEach((nodeRef: NodeRef) =>
this.viewStateManager.setOpacity(
nodeRef,
this.viewStateManager.getRestOpacity(nodeRef)
)
);
}
private isTopLevelHotspotNode(
hotspotNodeRef: NodeRef,
hotspotNodeRefs: Set<NodeRef>
): boolean {
return !this.nodeHierarchy
.getAncestors(hotspotNodeRef)
.some((ancestor: NodeRef) => hotspotNodeRefs.has(ancestor));
}
private isReferenceNode(nodeRef: NodeRef): boolean {
return (
this.nodeHierarchy.getNodeContentType(nodeRef) ===
NodeContentType.Reference
);
}
private getLeafDescendants(
nodeRef: NodeRef,
leafNodeRefs: NodeRef[]
): NodeRef[] {
if (!this.isReferenceNode(nodeRef)) {
const children = this.nodeHierarchy
.getChildren(nodeRef, false)
.filter((childNodeRef: NodeRef) => !this.isReferenceNode(childNodeRef));
if (children.length === 0) {
leafNodeRefs.push(nodeRef);
} else {
children.forEach((childNodeRef: NodeRef) =>
this.getLeafDescendants(childNodeRef, leafNodeRefs)
);
}
}
return leafNodeRefs;
}
private getAllLeafNodeRefs(): NodeRef[] {
return this.nodeHierarchy
.getChildren(undefined)
.flatMap((nodeRef: NodeRef) => this.getLeafDescendants(nodeRef, []));
}
private isolateNodes(nodeRefsToIsolate: object[]): void {
// isolate just the first selected node
nodeRefsToIsolate = nodeRefsToIsolate.slice(0, 1);
this.viewport.zoomTo(
ZoomTo.Node,
nodeRefsToIsolate,
this.flyToDurationInSeconds,
this.zoomToMargin
);
const currentVisibleSids: string[] =
this.viewPriorToIsolateViewInfo.visibility.visible || [];
const currentVisibleNodeRefs: NodeRef[] = this.persistentIdToNodeRef(
currentVisibleSids,
true
);
this.viewStateManager.setVisibilityState(
currentVisibleNodeRefs,
false,
true,
false
);
this.viewStateManager.setVisibilityState(
nodeRefsToIsolate,
true,
true,
true
);
}
private animationPlayerSetTime(time: number, blockEvents: boolean): void {
// bug workaround
// the overload with no sequence number parameter blows up
(this.animationPlayer as any).setTime(time, undefined, blockEvents);
}
private onViewActivated(): void {
this.initialViewInfo = this.viewport.getViewInfo({
camera: true,
visibility: true,
});
}
private onTimeChanged(oEvent: any): void {
let changes = false;
const time: number = oEvent.getParameters().time;
if (this.animationTime !== time) {
this.animationTime = time;
this.animationTimeChange.emit(time);
changes = true;
}
const position = this.animationTotalDuration
? this.animationTime / this.animationTotalDuration
: 0;
if (this.animationPosition !== position) {
this.animationPosition = position;
this.animationPositionChange.emit(position);
changes = true;
}
if (this.animationPlaying) {
if (this.animationPosition >= 1) {
this._animationPlaying = false;
this.animationPlayingChange.emit(this._animationPlaying);
}
}
if (changes) {
// This is needed for the animation slider handle position to get updated
// while an animation is playing.
// Otherwise it typically only moves once the animation playback has paused.
this.changeDetectorRef.detectChanges();
}
}
private setVisualizationLoadInfo(
visualizationLoadInfo: VisualizationLoadInfo
) {
this._visualizationLoadInfo = visualizationLoadInfo;
this.visualizationLoadInfoChange.emit(visualizationLoadInfo);
this.changeDetectorRef.detectChanges();
}
public get visualizationLoadInfo(): VisualizationLoadInfo {
return this._visualizationLoadInfo;
}
private _visualizationLoadInfo: VisualizationLoadInfo;
public visualizationLoadInfoChange =
new EventEmitter<VisualizationLoadInfo>();
public loadVisualization(
productCode: string
): Observable<VisualizationLoadInfo> {
if (!this.windowRef.isBrowser()) {
return of({
lookupResult: VisualizationLookupResult.UnexpectedError,
loadStatus: VisualizationLoadStatus.UnexpectedError,
errorMessage: 'Should not call loadVisualization in server side code',
});
}
this.selectedNodeIdsSubscription?.unsubscribe();
return this.viewportAdded$.pipe(
mergeMap(() =>
this.resolveVisualization(productCode).pipe(
mergeMap((visualizationLoadInfo: VisualizationLoadInfo) => {
if (
visualizationLoadInfo.lookupResult ===
VisualizationLookupResult.UniqueMatchFound
) {
this.sceneNodeToProductLookupService.populateMapsForScene(
this.sceneId
);
let mergedVisualizationLoadInfo: VisualizationLoadInfo = {
...visualizationLoadInfo,
loadStatus: VisualizationLoadStatus.Loading,
};
this.setVisualizationLoadInfo(mergedVisualizationLoadInfo);
return this.loadScene(this.sceneId, this.contentType).pipe(
mergeMap((sceneLoadInfo: SceneLoadInfo) => {
if (sceneLoadInfo.sceneLoadState === SceneLoadState.Failed) {
mergedVisualizationLoadInfo = {
...visualizationLoadInfo,
loadStatus: VisualizationLoadStatus.UnexpectedError,
errorMessage: sceneLoadInfo.errorMessage,
};
} else {
this.selectedNodeIdsSubscription =
this.selectedNodeIds$.subscribe(
this.handleSelectedNodeIds.bind(this)
);
mergedVisualizationLoadInfo = {
...visualizationLoadInfo,
loadStatus: VisualizationLoadStatus.Loaded,
};
}
this.setVisualizationLoadInfo(mergedVisualizationLoadInfo);
return of(mergedVisualizationLoadInfo);
})
);
} else {
return of(visualizationLoadInfo);
}
})
)
)
);
}
private isUi5BootStrapped(): boolean {
return (
!!this.windowRef.nativeWindow &&
!!(this.windowRef.nativeWindow as any).sap
);
}
private getCore(): Core {
return sap.ui.getCore();
}
private bootstrapUi5(scriptElementId: string): Observable<void> {
const epdVisualization = this.epdVisualizationConfig
.epdVisualization as EpdVisualizationInnerConfig;
const ui5Config = epdVisualization.ui5 as Ui5Config;
return new Observable((subscriber) => {
if (this.isUi5BootStrapped()) {
subscriber.next();
subscriber.complete();
return;
}
const script = this.windowRef.document.createElement('script');
script.setAttribute('id', scriptElementId);
this.windowRef.document
.getElementsByTagName('head')[0]
.appendChild(script);
script.onload = () => {
subscriber.next();
subscriber.complete();
};
script.onerror = (error: any) => {
subscriber.error(error);
subscriber.complete();
};
script.id = 'sap-ui-bootstrap';
script.type = 'text/javascript';
script.setAttribute('data-sap-ui-compatVersion', 'edge');
script.src = ui5Config.bootstrapUrl;
});
}
private initializeUi5(): Observable<void> {
return new Observable((subscriber) => {
const core: Core = this.getCore();
core.attachInit(() => {
const loadLibraryOptions = { async: true };
Promise.all([
core.loadLibrary('sap.m', loadLibraryOptions),
core.loadLibrary('sap.ui.layout', loadLibraryOptions),
core.loadLibrary('sap.ui.vk', loadLibraryOptions),
core.loadLibrary('sap.ui.richtexteditor', loadLibraryOptions),
]).then(() => {
subscriber.next();
subscriber.complete();
});
});
});
}
private destroyViewportAssociations(viewport: Viewport): void {
const core = this.getCore();
if (!core) {
return;
}
const contentConnectorId = viewport.getContentConnector();
if (contentConnectorId) {
const contentConnector = core.byId(contentConnectorId);
if (contentConnector) {
contentConnector.destroy();
}
}
const viewStateManagerId = viewport.getViewStateManager();
if (viewStateManagerId && core.byId(viewStateManagerId)) {
const viewStateManager = core.byId(
viewStateManagerId
) as ViewStateManager;
if (viewStateManager) {
const animationPlayer = viewStateManager.getAnimationPlayer();
if (animationPlayer) {
animationPlayer.destroy();
}
const viewManagerId = viewStateManager.getViewManager();
if (viewManagerId) {
const viewManager = core.byId(viewManagerId);
if (viewManager) {
viewManager.destroy();
}
}
viewStateManager.destroy();
}
}
}
private onContentChangesStarted(): void {
this.viewport.detachNodesPicked(this.onNodesPicked);
}
private onContentChangesFinished(event: any): void {
const content = event.getParameter('content');
const failureReason = event.getParameter('failureReason');
if (!!content && !failureReason) {
this.scene = content;
this.nodeHierarchy = this.scene.getDefaultNodeHierarchy();
this.viewport.attachNodesPicked(this.onNodesPicked, this);
if (content.loaders) {
content.loaders.forEach((contentLoader: any) => {
if (
contentLoader &&
contentLoader.attachLoadingFinished !== undefined
) {
contentLoader.attachLoadingFinished(
this.onContentLoadingFinished,
this
);
}
});
}
}
this.contentChangesFinished.emit({
content,
failureReason,
});
}
private onContentLoadingFinished(_event: any): void {
this.contentLoadFinished.emit({});
}
private onNodesPicked(event: any): void {
if (this.is2D) {
this.onNodesPicked2D(event);
} else {
this.onNodesPicked3D(event);
}
}
private isNodeIncluded(nodeRef: NodeRef): boolean {
const sids: string[] = this.nodeRefToPersistentId([nodeRef], true);
const productCodes =
this.sceneNodeToProductLookupService.syncLookupProductCodes(sids);
return (
!!productCodes &&
productCodes.some((productCode: string) =>
this.includedProductCodes.includes(productCode)
)
);
}
private onNodesPicked2D(event: any): void {
const pickedNodes = event.getParameter('picked');
if (pickedNodes.length === 0) {
return;
}
const hotSpots = pickedNodes.filter(
(node: any) =>
node.nodeContentType && node.nodeContentType === NodeContentType.Hotspot
);
if (hotSpots.length === 0) {
return;
}
const includedHotSpots: NodeRef[] = hotSpots.filter((nodeRef: NodeRef) =>
this.isNodeIncluded(nodeRef)
);
pickedNodes.splice(0);
includedHotSpots.forEach((includedHotSpot: any) =>
pickedNodes.push(includedHotSpot)
);
}
private onNodesPicked3D(event: any): void {
const picked: NodeRef[] = event.getParameter('picked');
const src: NodeRef[] = picked.splice(0, picked.length);
src.forEach((node: NodeRef) => {
while (!this.isNodeIncluded(node)) {
node = node.parent;
if (!node) {
break;
}
}
if (node) {
picked.push(node);
}
});
}
private addViewport(): Observable<void> {
return new Observable((subscriber) => {
sap.ui.require(
[
'sap/ui/vk/ViewManager',
'sap/ui/vk/Viewport',
'sap/ui/vk/ViewStateManager',
'sap/ui/vk/AnimationPlayer',
'sap/ui/vk/ContentConnector',
'sap/ui/vk/DrawerToolbar',
],
(
sap_ui_vk_ViewManager: any,
sap_ui_vk_Viewport: any,
sap_ui_vk_ViewStateManager: any,
sap_ui_vk_AnimationPlayer: any,
sap_ui_vk_ContentConnector: any,
sap_ui_vk_DrawerToolbar: any
) => {
const core: Core = this.getCore();
const uiArea: UIArea = core.getUIArea(this.elementRef.nativeElement);
if (uiArea) {
const oldViewport = uiArea.getContent()[0] as Viewport;
this.destroyViewportAssociations(oldViewport);
uiArea.destroyContent();
}
this.viewport = new sap_ui_vk_Viewport({ visible: false });
this.viewport.placeAt(this.elementRef.nativeElement);
this.contentConnector = new sap_ui_vk_ContentConnector();
this.contentConnector.attachContentChangesStarted(
this.onContentChangesStarted,
this
);
this.contentConnector.attachContentChangesFinished(
this.onContentChangesFinished,
this
);
this.contentConnector.attachContentLoadingFinished(
this.onContentLoadingFinished,
this
);
this.viewStateManager = new sap_ui_vk_ViewStateManager({
contentConnector: this.contentConnector,
});
this.viewport.setContentConnector(this.contentConnector);
this.viewport.setViewStateManager(this.viewStateManager);
this.animationPlayer = new sap_ui_vk_AnimationPlayer();
this.animationPlayer.setViewStateManager(this.viewStateManager);
this.animationPlayer.attachViewActivated(this.onViewActivated, this);
this.animationPlayer.attachTimeChanged(this.onTimeChanged, this);
this.viewManager = new sap_ui_vk_ViewManager({
contentConnector: this.contentConnector,
animationPlayer: this.animationPlayer,
});
this.viewStateManager.setViewManager(this.viewManager);
this.viewStateManager.attachSelectionChanged(
this.onSelectionChanged,
this
);
this.viewStateManager.attachOutliningChanged(
this.onOutliningChanged,
this
);
this.drawerToolbar = new sap_ui_vk_DrawerToolbar({
viewport: this.viewport,
visible: false,
});
this.viewport.addDependent(this.drawerToolbar);
subscriber.next();
subscriber.complete();
}
);
});
}
private getCSSPropertyValue(cssPropertyName: string): string {
const storefrontElement = document.getElementsByTagName('cx-storefront')[0];
return getComputedStyle(storefrontElement).getPropertyValue(
cssPropertyName
);
}
private getCSSColor(color: string): CSSColor {
return (this.getCSSPropertyValue(color) || color).trim() as CSSColor;
}
private resolveVisualization(
productCode: string
): Observable<VisualizationLoadInfo> {
return this.visualizationLookupService
.findMatchingVisualizations(productCode)
.pipe(
mergeMap((matches: VisualizationInfo[]) => {
let visualizationLoadInfo: VisualizationLoadInfo;
switch (matches.length) {
case 0:
visualizationLoadInfo = {
lookupResult: VisualizationLookupResult.NoMatchFound,
loadStatus: VisualizationLoadStatus.NotStarted,
matches,
};
break;
case 1:
const matchingVisualization = matches[0];
this.sceneId = matchingVisualization.sceneId;
this.contentType = matchingVisualization.contentType;
visualizationLoadInfo = {
lookupResult: VisualizationLookupResult.UniqueMatchFound,
loadStatus: VisualizationLoadStatus.NotStarted,
matches,
visualization: matchingVisualization,
};
break;
default:
visualizationLoadInfo = {
lookupResult: VisualizationLookupResult.MultipleMatchesFound,
loadStatus: VisualizationLoadStatus.NotStarted,
matches,
};
break;
}
this.setVisualizationLoadInfo(visualizationLoadInfo);
return of(visualizationLoadInfo);
}),
catchError(() => {
let visualizationLoadInfo = {
lookupResult: VisualizationLookupResult.UnexpectedError,
loadStatus: VisualizationLoadStatus.NotStarted,
};
this.setVisualizationLoadInfo(visualizationLoadInfo);
return of(visualizationLoadInfo);
})
);
}
private persistentIdToNodeRef(
nodeIds: string[],
filterUnresolvedValues: boolean
): NodeRef[] {
const nodeRefs: NodeRef[] = (this.scene as any).persistentIdToNodeRef(
nodeIds
);
return filterUnresolvedValues
? nodeRefs.filter((nodeRef) => !!nodeRef)
: nodeRefs;
}
private nodeRefToPersistentId(
nodeRefs: object[],
filterUnresolvedValues: boolean
): string[] {
const sids: string[] = (this.scene as any).nodeRefToPersistentId(nodeRefs);
return filterUnresolvedValues ? sids.filter((sid) => !!sid) : sids;
}
private getViewStateManagerImplementation(): any {
return (this.viewStateManager as any).getImplementation();
}
private handleSelectedNodeIds(nodeIds: string[]): void {
const nodeRefs = this.persistentIdToNodeRef(nodeIds, true);
if (this.is2D) {
this.handleSelectedNodes2D(nodeRefs);
} else {
this.handleSelectedNodes3D(nodeRefs);
}
if (this.isolateModeEnabled && nodeRefs.length > 0) {
this.isolateNodes(nodeRefs);
}
// Need to ensure a frame render occurs since we are blocking events
// when changing selection/outlining
this.setShouldRenderFrame();
}
private handleSelectedNodes2D(selectedNodes: NodeRef[]): void {
const existingSelection: NodeRef[] = [];
this.viewStateManager.enumerateSelection((nodeRef: NodeRef) =>
existingSelection.push(nodeRef)
);
this.viewStateManager.setSelectionStates(
[],
existingSelection,
false,
true
);
this.viewStateManager.setSelectionStates(selectedNodes, [], false, true);
}
private handleSelectedNodes3D(selectedNodes: NodeRef[]): void {
const existingOutlinedNodeRefs: NodeRef[] = [];
this.viewStateManager.enumerateOutlinedNodes((nodeRef: NodeRef) =>
existingOutlinedNodeRefs.push(nodeRef)
);
this.getViewStateManagerImplementation().setOutliningStates(
[],
existingOutlinedNodeRefs,
false,
true
);
this.getViewStateManagerImplementation().setOutliningStates(
selectedNodes,
[],
false,
true
);
}
private setShouldRenderFrame(): void {
(this.viewport as any).setShouldRenderFrame();
}
private is2DContentType(contentType: ContentType): boolean {
return contentType === ContentType.Drawing2D;
}
private loadScene(
sceneId: string,
contentType: ContentType
): Observable<SceneLoadInfo> {
const epdVisualization = this.epdVisualizationConfig
.epdVisualization as EpdVisualizationInnerConfig;
const visualizationApiConfig =
epdVisualization.apis as VisualizationApiConfig;
if (this.viewportReady) {
this.setViewportReady(false);
}
this.setIs2D(this.is2DContentType(contentType));
return new Observable((subscriber) => {
sap.ui.require(['sap/ui/vk/ContentResource'], (ContentResource: any) => {
this.sceneLoadInfo$.next({
sceneLoadState: SceneLoadState.Loading,
});
this.viewport.setSelectionDisplayMode(
this.is2D ? 'Highlight' : 'Outline'
);
const baseUrl: string = visualizationApiConfig.baseUrl;
const contentResource: ContentResource = new ContentResource({
useSecureConnection: false,
sourceType: this.is2D ? 'stream2d' : 'stream',
source: `${baseUrl}/vis/public/storage/v1`,
veid: sceneId,
});
this.contentChangesFinished
.pipe(first())
.subscribe(
(visualContentLoadFinished: {
content: any;
failureReason: any;
}) => {
const succeeded = !!visualContentLoadFinished.content;
const sceneLoadInfo: SceneLoadInfo = succeeded
? {
sceneLoadState: SceneLoadState.Loaded,
loadedSceneInfo: {
sceneId,
contentType,
},
}
: {
sceneLoadState: SceneLoadState.Failed,
errorMessage: visualContentLoadFinished.failureReason,
};
this.sceneLoadInfo$.next(sceneLoadInfo);
subscriber.next(sceneLoadInfo);
subscriber.complete();
}
);
this.contentLoadFinished.pipe(first()).subscribe(() => {
const sceneLoadInfo = this.sceneLoadInfo$.value;
if (sceneLoadInfo.sceneLoadState === SceneLoadState.Loaded) {
this.setViewportReady(true);
// Ensure that the spinner is hidden before the viewport becomes visible.
// Otherwise the position of the spinner changes
this.changeDetectorRef.detectChanges();
this.viewport.setVisible(true);
}
});
this.contentConnector.addContentResource(contentResource);
});
});
}
private onSelectionChanged(): void {
const nodeRefs: NodeRef[] = [];
this.viewStateManager.enumerateSelection((nodeRef: NodeRef) =>
nodeRefs.push(nodeRef)
);
const nodeIds: string[] = this.nodeRefToPersistentId(nodeRefs, true);
this.sceneNodeToProductLookupService
.lookupProductCodes(nodeIds)
.pipe(first())
.subscribe((productCodes: string[]) => {
this.selectedProductCodesChange.emit(productCodes);
});
}
private onOutliningChanged(): void {
const nodeRefs: NodeRef[] = [];
this.viewStateManager.enumerateOutlinedNodes((nodeRef: NodeRef) =>
nodeRefs.push(nodeRef)
);
const nodeIds: string[] = this.nodeRefToPersistentId(nodeRefs, true);
this.sceneNodeToProductLookupService
.lookupProductCodes(nodeIds)
.pipe(first())
.subscribe((productCodes: string[]) => {
this.selectedProductCodesChange.emit(productCodes);
});
}
} | the_stack |
import { remove, createElement } from '@syncfusion/ej2-base';
import { Chart } from '../../../src/chart/chart';
import { StepAreaSeries } from '../../../src/chart/series/step-area-series';
import { Legend } from '../../../src/chart/legend/legend';
import { ChartSeriesType, ChartRangePadding } from '../../../src/chart/utils/enum';
import { ValueType } from '../../../src/chart/utils/enum';
import '../../../node_modules/es6-promise/dist/es6-promise';
import { Category } from '../../../src/chart/axis/category-axis';
import { DateTime } from '../../../src/chart/axis/date-time-axis';
import { Logarithmic } from '../../../src/chart/axis/logarithmic-axis';
import { DataLabel } from '../../../src/chart/series/data-label';
import { unbindResizeEvents } from '../base/data.spec';
import { tooltipData1,negativeDataPoint, categoryData,datetimeData,tooltipData2, rotateData1, rotateData2 } from '../base/data.spec';
import { MouseEvents } from '../base/events.spec';
import { DataEditing } from '../../../src/chart/user-interaction/data-editing';
import { Tooltip } from '../../../src/chart/user-interaction/tooltip';
import { Crosshair } from '../../../src/chart/user-interaction/crosshair';
import { Selection } from '../../../src/chart/user-interaction/selection';
import { Series, Points } from '../../../src/chart/series/chart-series';
import { Zoom } from '../../../src/chart/user-interaction/zooming';
import { Axis } from '../../../src/chart/axis/axis';
import { EmitType } from '@syncfusion/ej2-base';
import { ILoadedEventArgs } from '../../../src/chart/model/chart-interface';
import {profile , inMB, getMemoryProfile} from '../../common.spec';
import {IAnimationCompleteEventArgs } from '../../../src/chart/model/chart-interface';
Chart.Inject(StepAreaSeries, Category, DataEditing, Legend, DateTime, Tooltip, Logarithmic, DataLabel, Legend, Crosshair);
let data: any = tooltipData1;
let data2:any=tooltipData2;
let negativPoint: any = negativeDataPoint;
let datetime: any = datetimeData;
let trigger: MouseEvents = new MouseEvents();
export interface Arg {
chart: Chart;
}
describe('Chart Control', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
let elem: HTMLElement;
describe('Chart Steparea series', () => {
let chartObj: Chart;
let svg: HTMLElement;
let marker: HTMLElement;
let targetElement: HTMLElement;
let datalabel: HTMLElement;
let loaded: EmitType<ILoadedEventArgs>;
beforeAll(() => {
elem = createElement('div', { id: 'container' });
document.body.appendChild(elem);
chartObj = new Chart(
{
primaryXAxis: { title: 'PrimaryXAxis' },
primaryYAxis: { title: 'PrimaryYAxis', rangePadding: 'Normal' },
series: [{
dataSource: data, xName: 'x', yName: 'y', animation: { enable: false }, type: 'StepArea',
name: 'ChartSeriesNameGold', fill: 'skyblue', marker:{visible: true,dataLabel:{visible:false}}
},
], width: '800',
title: 'Chart TS Title', legendSettings: { visible: false, },
});
chartObj.appendTo('#container');
});
afterAll((): void => {
elem.remove();
chartObj.destroy();
});
it('Checking with fill', (done: Function) => {
loaded = (args: Object): void => {
let svg: HTMLElement = document.getElementById('container_Series_0');
expect(svg.getAttribute('fill') === 'skyblue').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Showing default data label', (done: Function) => {
loaded = (args: Object): void => {
let element = document.getElementById('container_Series_0_Point_2_Text_0');
expect(document.getElementById('containerShapeGroup0').childNodes.length == 0).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.dataLabel.visible = true;
chartObj.refresh();
});
it('Checking dataLabel positions Bottom', (done: Function) => {
loaded = (args: Object): void => {
let element = document.getElementById('container_Series_0_Point_2_Text_0');
expect(document.getElementById('containerShapeGroup0').childNodes.length == 0).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.dataLabel.position = 'Bottom';
chartObj.refresh();
});
it('Checking dataLabel positions Middle', (done: Function) => {
loaded = (args: Object): void => {
let element = document.getElementById('container_Series_0_Point_2_Text_0');
expect(document.getElementById('containerShapeGroup0').childNodes.length == 0).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.dataLabel.position = 'Middle';
chartObj.refresh();
});
it('Checking dataLabel positions Top', (done: Function) => {
loaded = (args: Object): void => {
let element = document.getElementById('container_Series_0_Point_2_Text_0');
expect(document.getElementById('containerShapeGroup0').childNodes.length == 0).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.dataLabel.position = 'Top';
chartObj.refresh();
});
it('Checking dataLabel positions Auto', (done: Function) => {
loaded = (args: Object): void => {
let element = document.getElementById('container_Series_0_Point_2_Text_0');
expect(document.getElementById('containerShapeGroup0').childNodes.length == 0).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.dataLabel.position = 'Auto';
chartObj.refresh();
});
it('Checking dataLabel positions Outer', (done: Function) => {
loaded = (args: Object): void => {
let element = document.getElementById('container_Series_0_Point_2_Text_0');
expect(document.getElementById('containerShapeGroup0').childNodes.length == 0).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.dataLabel.position = 'Outer';
chartObj.refresh();
});
it('Checking dataLabel Alignment Far', (done: Function) => {
loaded = (args: Object): void => {
let element = document.getElementById('container_Series_0_Point_2_Text_0');
expect(document.getElementById('containerShapeGroup0').childNodes.length == 0).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.dataLabel.alignment = 'Far';
chartObj.refresh();
});
it('Checking dataLabel positions Near', (done: Function) => {
loaded = (args: Object): void => {
let element = document.getElementById('container_Series_0_Point_2_Text_0');
expect(document.getElementById('containerShapeGroup0').childNodes.length == 0).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.dataLabel.alignment = 'Near';
chartObj.refresh();
});
it('with marker size without marker visibility', (done: Function) => {
loaded = (args: Object): void => {
let marker: HTMLElement = document.getElementById('container_Series_0_Point_3_Symbol');
expect(marker == null).toBe(true); done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.visible = false;
chartObj.series[0].marker.width = 10;
chartObj.series[0].marker.height = 10;
chartObj.series[0].marker.dataLabel.visible = true;
chartObj.refresh();
});
it('Checking with empty data Points', (done: Function) => {
loaded = (args: Object): void => {
svg = document.getElementById('container_Series_0_Point_3_Symbol');
expect(svg == null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].dataSource[3].y= null;
chartObj.series[0].marker.visible = true;
chartObj.refresh();
});
it('Checking with negative points', (done: Function) => {
loaded = (args: Arg): void => {
svg = document.getElementById('container1_AxisLabel_4');
let series: Series = <Series>args.chart.series[0];
expect(parseFloat(svg.getAttribute('y')) < series.points[1].symbolLocations[0].y).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].dataSource = negativeDataPoint;
chartObj.series[0].marker.visible = true;
chartObj.tooltip.enable=true;
chartObj.refresh();
});
it('Checking with negative points tooltip', (done: Function) => {
loaded = (args: Arg): void => {
let target: HTMLElement = document.getElementById('container_Series_0_Point_1_Symbol');
let series: Series = <Series>chartObj.series[0];
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
let y: number = series.points[1].regions[0].y + parseFloat(chartArea.getAttribute('y')) + elem.offsetTop;
let x: number = series.points[1].regions[0].x + parseFloat(chartArea.getAttribute('x')) + elem.offsetLeft;
trigger.mousemovetEvent(target, Math.ceil(x), Math.ceil(y));
let tooltip: HTMLElement = document.getElementById('container_tooltip');
expect(tooltip != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].dataSource = negativeDataPoint;
chartObj.tooltip.enable=true;
chartObj.refresh();
});
it('Checking with single Points', (done: Function) => {
loaded = (args: Object): void => {
svg = document.getElementById('container_Series_0_Point_0_Symbol');
expect(svg != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].dataSource = null;
chartObj.series[0].dataSource = [{ x: 1, y: 10 }];
chartObj.refresh(); unbindResizeEvents(chartObj);
});
it('Legend Shape type', (done: Function) => {
loaded = (args: Object): void => {
let legendShape: Element = document.getElementById('container_chart_legend_shape_0');
expect(legendShape.tagName).toEqual('path');
expect(legendShape.getAttribute('d') !== null).toBe(true);
done();
};
chartObj.animationComplete = null;
chartObj.loaded = loaded;
chartObj.series[0].type = 'StepArea';
chartObj.legendSettings = { visible: true };
chartObj.refresh();
});
it('checking with marker shape diamond', (done: Function) => {
loaded = (args: Object): void => {
marker = document.getElementById('container_Series_0_Point_0_Symbol');
expect(marker.getAttribute('fill') === 'black').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.shape = 'Diamond';
chartObj.series[0].marker.fill ='black';
chartObj.refresh();
});
it('Checking with marker shape Circle', (done: Function) => {
loaded = (args: Object): void => {
marker = document.getElementById('container_Series_0_Point_0_Symbol');
expect(marker.getAttribute('fill') === 'black').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.shape = 'Circle';
chartObj.series[0].marker.fill = 'black';
chartObj.series[0].dataSource = data;
chartObj.refresh();
});
it('checking with marker shape HorizontalLine', (done: Function) => {
loaded = (args: Object): void => {
marker = document.getElementById('container_Series_0_Point_0_Symbol');
expect(marker.getAttribute('fill') === 'black').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.shape = 'HorizontalLine';
chartObj.refresh();
});
it('checking with marker shape InvertedTriangle', (done: Function) => {
loaded = (args: Object): void => {
marker = document.getElementById('container_Series_0_Point_0_Symbol');
expect(marker.getAttribute('fill') === 'black').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.shape = 'InvertedTriangle';
chartObj.refresh();
});
it('checking with marker shape Pentagon', (done: Function) => {
loaded = (args: Object): void => {
marker = document.getElementById('container_Series_0_Point_0_Symbol');
expect(marker.getAttribute('fill') === 'black').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.shape = 'Pentagon';
chartObj.refresh();
});
it('checking with marker shape Triangle', (done: Function) => {
loaded = (args: Object): void => {
marker = document.getElementById('container_Series_0_Point_0_Symbol');
expect(marker.getAttribute('fill') === 'black').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.shape = 'Triangle';
chartObj.refresh();
});
it('checking with marker shape rectangle', (done: Function) => {
loaded = (args: Object): void => {
marker = document.getElementById('container_Series_0_Point_0_Symbol');
expect(marker.getAttribute('fill') === 'black').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.shape = 'Rectangle';
chartObj.refresh();
});
it('Checking with marker visible false', (done: Function) => {
loaded = (args: Object): void => {
datalabel = document.getElementById('container_Series_0_Point_0_Symbol');
expect(datalabel === null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.visible = false;
chartObj.refresh();
});
it('Checking with multiple series', (done: Function) => {
loaded = (args: Object): void => {
svg = document.getElementById('container_Series_0');
expect(svg.getAttribute('fill') === 'red').toBe(true);
svg = document.getElementById('container_Series_1');
expect(svg.getAttribute('fill') === 'rgba(135,206,235,1)').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series = [{ dataSource: data, xName: 'x', yName: 'y', name: 'Gold', fill: 'red', type: 'StepArea', animation: { enable: false } },
{ dataSource: data2, xName: 'x', name: 'silver', yName: 'y', fill: 'rgba(135,206,235,1)', type: 'StepArea', animation: { enable: false } },
{ dataSource: data, xName: 'x', name: 'diamond', yName: 'y', fill: 'blue', type: 'StepArea', animation: { enable: false } }];
chartObj.series[0].marker.visible = true;
chartObj.series[1].marker.visible = true;
chartObj.series[2].marker.visible = true;
chartObj.series[0].animation.enable=false;
chartObj.series[1].animation.enable=false;
chartObj.series[2].animation.enable=false;
// chartObj.primaryXAxis.valueType = ValueType.DateTime;
chartObj.refresh(); unbindResizeEvents(chartObj);
});
it('Checking with category axis', (done: Function) => {
loaded = (args: Object): void => {
marker = document.getElementById('container_Series_0_Point_0_Symbol');
expect(marker != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.primaryXAxis.valueType = 'Category';
chartObj.series[0].dataSource = categoryData;
chartObj.series[0].marker.visible = true;
chartObj.refresh();
});
it('Checking with category axis BetweenTicks', (done: Function) => {
loaded = (args: Object): void => {
let axisLabel: Element = document.getElementById('container0_AxisLabel_0');
expect(axisLabel.textContent == 'USA').toBe(true);
let axisStart = document.getElementById('containerAxisLine_0');
expect(parseInt(axisLabel.getAttribute('x')) > parseInt(axisStart.getAttribute('d').split(' ')[1])).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.primaryXAxis.valueType = 'Category';
chartObj.primaryXAxis.labelPlacement = 'BetweenTicks'
chartObj.series[0].dataSource = categoryData;
chartObj.refresh();
});
it('Checking with category axis OnTicks', (done: Function) => {
loaded = (args: Object): void => {
let axisLabel: Element = document.getElementById('container0_AxisLabel_0');
expect(axisLabel.textContent == 'USA').toBe(true);
let axisStart: Element = document.getElementById('containerAxisLine_0');
expect(parseInt(axisLabel.getAttribute('x')) < parseInt(axisStart.getAttribute('d').split(' ')[1])).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.primaryXAxis.valueType = 'Category';
chartObj.primaryXAxis.labelPlacement = 'OnTicks'
chartObj.series[0].dataSource = categoryData;
chartObj.refresh();
});
it('checking with dateTime', (done: Function) => {
loaded = (args: Object): void => {
let axislabel: HTMLElement = document.getElementById('container0_AxisLabel_3');
expect(axislabel.textContent === '2003').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].dataSource = datetime;
chartObj.series[1].dataSource = datetime;
chartObj.series[2].dataSource = datetime;
chartObj.primaryXAxis.valueType = 'DateTime';
chartObj.refresh();
});
it('checking with tooltip', (done: Function) => {
loaded = (args: Object): void => {
let target: HTMLElement = document.getElementById('container_Series_0_Point_1_Symbol');
let series: Series = <Series>chartObj.series[0];
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
let y: number = series.points[1].regions[0].y + parseFloat(chartArea.getAttribute('y')) + elem.offsetTop;
let x: number = series.points[1].regions[0].x + parseFloat(chartArea.getAttribute('x')) + elem.offsetLeft;
trigger.mousemovetEvent(target, Math.ceil(x), Math.ceil(y));
let tooltip: HTMLElement = document.getElementById('container_tooltip');
expect(tooltip != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.tooltip.enable = true;
chartObj.refresh();
});
it('checking with trackball', (done: Function) => {
loaded = (args: Object): void => {
let target: HTMLElement = document.getElementById('container_Series_0_Point_1_Symbol');
let series: Series = <Series>chartObj.series[0];
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
let y: number = series.points[1].regions[0].y + parseFloat(chartArea.getAttribute('y')) + elem.offsetTop;
let x: number = series.points[1].regions[0].x + parseFloat(chartArea.getAttribute('x')) + elem.offsetLeft;
trigger.mousemovetEvent(target, Math.ceil(x), Math.ceil(y));
let tooltip: HTMLElement = document.getElementById('container_tooltip');
expect(tooltip != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.tooltip.shared = true;
chartObj.refresh();
});
it('checking with cross hair', (done: Function) => {
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
let series: Series = <Series>chartObj.series[0];
let y: number = series.points[2].regions[0].y + parseFloat(chartArea.getAttribute('y')) + elem.offsetTop;
let x: number = series.points[2].regions[0].x + series.points[2].regions[0].width / 2 +
parseFloat(chartArea.getAttribute('x')) + elem.offsetLeft;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('container_svg').childNodes[4];
let element1: HTMLElement;
expect(crosshair.childNodes.length == 3).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[0];
expect(element1.getAttribute('d').indexOf(chartArea.getAttribute('x')) > 0).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[1];
expect(element1.getAttribute('d').indexOf(chartArea.getAttribute('y')) > 0).toBe(true);
expect(crosshair.childNodes[2].childNodes.length == 4).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[0];
expect(element1.getAttribute('d') != '').toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[2];
expect(element1.getAttribute('d') != '').toBe(true);
done();
}
chartObj.loaded = loaded;
chartObj.crosshair.enable = true;
chartObj.series[0].animation.enable = false;
chartObj.primaryXAxis.crosshairTooltip.enable = true;
chartObj.primaryYAxis.crosshairTooltip.enable = true;
chartObj.refresh();
});
it('checking with log axis with dataTime axis', (done: Function) => {
loaded = (args: Object): void => {
let axisLabelLast: Element = document.getElementById('container1_AxisLabel_3');
expect(axisLabelLast.textContent == '10000').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.primaryXAxis.valueType = 'DateTime';
chartObj.primaryYAxis.valueType = 'Logarithmic';
chartObj.series = [
{
type: 'StepArea', name: 'ProductX', xName: 'x', yName:'y',
dataSource: [
{ x: new Date(1995, 0, 1), y: 80 }, { x: new Date(1996, 0, 1), y: 200 },
{ x: new Date(1997, 0, 1), y: 400 }, { x: new Date(1998, 0, 1), y: 600 },
{ x: new Date(1999, 0, 1), y: 700 }, { x: new Date(2000, 0, 1), y: 1400 },
{ x: new Date(2001, 0, 1), y: 2000 }, { x: new Date(2002, 0, 1), y: 4000 },
{ x: new Date(2003, 0, 1), y: 6000 }, { x: new Date(2004, 0, 1), y: 8000 },
{ x: new Date(2005, 0, 1), y: 10000 }]
}];
chartObj.series[0].animation.enable = false;
chartObj.refresh();
});
it('Checking animation', (done: Function) => {
let animate: EmitType<IAnimationCompleteEventArgs> = (args: series1): void => {
let point : Element = <Element>document.getElementById('container_ChartSeriesClipRect_' + args.series.index).childNodes[0];
expect(point.getAttribute('width') === document.getElementById('container_ChartAreaBorder').getAttribute('width')).toBe(true);
done();
};
chartObj.series[0].animation.enable = true;
chartObj.animationComplete = animate;
chartObj.refresh();
});
});
describe('Step Area Series Inversed axis', () => {
let chart: Chart;
let loaded: EmitType<ILoadedEventArgs>;
let element: HTMLElement;
let dataLabelY;
let pointY;
element = createElement('div', { id: 'container' });
beforeAll(() => {
document.body.appendChild(element);
chart = new Chart(
{
primaryXAxis: { title: 'PrimaryXAxis' },
primaryYAxis: { title: 'PrimaryYAxis', isInversed: true },
series: [{
animation: { enable: false },
name: 'Series1', dataSource: data, xName: 'x', yName: 'y', size: 'size',
type: 'StepArea', marker: { visible: false, dataLabel: { visible: true, fill: 'violet' } }
}],
width: '800',
title: 'Chart TS Title', loaded: loaded,
legendSettings: { visible: false }
});
chart.appendTo('#container');
});
afterAll((): void => {
chart.destroy();
element.remove();
});
it('With Label position Top', (done: Function) => {
loaded = (args: Object): void => {
dataLabelY = +document.getElementById('container_Series_0_Point_2_TextShape_0').getAttribute('y');
pointY = (<Points>(<Series>chart.series[0]).points[2]).symbolLocations[0].y;
expect(dataLabelY > pointY).toBe(true);
dataLabelY = +document.getElementById('container_Series_0_Point_6_TextShape_0').getAttribute('y');
pointY = (<Points>(<Series>chart.series[0]).points[6]).symbolLocations[0].y;
expect(dataLabelY > pointY).toBe(true);
done();
};
chart.loaded = loaded;
chart.series[0].marker.dataLabel.position = 'Top';
chart.series[0].marker.dataLabel.alignment = 'Center';
chart.refresh();
});
it('With Label position Bottom', (done: Function) => {
loaded = (args: Object): void => {
dataLabelY = +document.getElementById('container_Series_0_Point_2_TextShape_0').getAttribute('y');
pointY = (<Points>(<Series>chart.series[0]).points[2]).symbolLocations[0].y;
expect(dataLabelY < pointY).toBe(true);
dataLabelY = +document.getElementById('container_Series_0_Point_6_TextShape_0').getAttribute('y');
pointY = (<Points>(<Series>chart.series[0]).points[6]).symbolLocations[0].y;
expect(dataLabelY < pointY).toBe(true);
done();
};
chart.loaded = loaded;
chart.series[0].marker.dataLabel.position = 'Bottom';
chart.refresh();
});
it('With Label position Middle', (done: Function) => {
loaded = (args: Object): void => {
let labelY: number = +document.getElementById('container_Series_0_Point_1_TextShape_0').getAttribute('y');
let labelHeight: number = +document.getElementById('container_Series_0_Point_1_TextShape_0').getAttribute('height');
let point: Points = (<Points>(<Series>chart.series[0]).points[1]);
expect(labelY + labelHeight / 2).toEqual(point.regions[0].y + point.regions[0].height / 2);
done();
};
chart.loaded = loaded;
chart.series[0].marker.dataLabel.position = 'Middle';
chart.refresh();
});
});
describe('checking rotated step area chart', () => {
let chart: Chart;
let loaded: EmitType<ILoadedEventArgs>;
let element: HTMLElement = createElement('div', { id: 'container' });
let dataLabel: HTMLElement;
let point: Points;
let trigger: MouseEvents = new MouseEvents();
let x: number;
let y: number;
let tooltip: HTMLElement;
let chartArea: HTMLElement;
let series: Series;
beforeAll(() => {
document.body.appendChild(element);
chart = new Chart({
primaryXAxis: { title: 'primaryXAxis', valueType: 'DateTime' },
primaryYAxis: { title: 'PrimaryYAxis'},
series: [
{ type: 'StepLine', name: 'series1', dataSource: rotateData1, xName: 'x', yName: 'y', animation: { enable: false },
marker: { visible: true}},
{ type: 'StepLine', name: 'series2', dataSource: rotateData2, xName: 'x', yName: 'y', animation: { enable: false },
marker: { visible: true}}
],
title: 'rotated stepline Chart'
});
chart.appendTo('#container');
});
afterAll((): void => {
chart.destroy();
element.remove();
});
it('checking without rotated', (done: Function) => {
loaded = (args: Object): void => {
let axis: Axis = <Axis>chart.primaryXAxis;
expect(axis.orientation).toEqual('Horizontal');
axis = <Axis>chart.primaryYAxis;
expect(axis.orientation).toEqual('Vertical');
done();
};
chart.loaded = loaded;
chart.refresh();
});
it('checking with rotated', (done: Function) => {
loaded = (args: Object): void => {
let axis: Axis = <Axis>chart.primaryYAxis;
expect(axis.orientation).toEqual('Horizontal');
axis = <Axis>chart.primaryXAxis;
expect(axis.orientation).toEqual('Vertical');
done();
};
chart.loaded = loaded;
chart.isTransposed = true;
chart.refresh();
});
it('checking with datalabel Auto position', (done: Function) => {
loaded = (args: Object): void => {
dataLabel = document.getElementById('container_Series_0_Point_2_Text_0');
point = (<Points>(<Series>chart.series[0]).points[2]);
expect(+(dataLabel.getAttribute('y')) < point.symbolLocations[0].y).toBe(true);
done();
};
chart.loaded = loaded;
chart.series[0].marker.dataLabel.visible = true;
chart.refresh();
});
it('checking with datalabel Top position', (done: Function) => {
loaded = (args: Object): void => {
dataLabel = document.getElementById('container_Series_0_Point_2_Text_0');
point = (<Points>(<Series>chart.series[0]).points[2]);
expect(+(dataLabel.getAttribute('y')) < point.symbolLocations[0].y).toBe(true);
done();
};
chart.loaded = loaded;
chart.series[0].marker.dataLabel.position = 'Top';
chart.refresh();
});
it('checking with datalabel Middle position', (done: Function) => {
loaded = (args: Object): void => {
dataLabel = document.getElementById('container_Series_0_Point_2_Text_0');
point = (<Points>(<Series>chart.series[0]).points[2]);
expect(+(dataLabel.getAttribute('y')) > (point.symbolLocations[0].y - point.regions[0].height / 2)).toBe(true);
done();
};
chart.loaded = loaded;
chart.series[0].marker.dataLabel.position = 'Middle';
chart.refresh();
});
it('checking with datalabel bottom position', (done: Function) => {
loaded = (args: Object): void => {
dataLabel = document.getElementById('container_Series_0_Point_2_Text_0');
point = (<Points>(<Series>chart.series[0]).points[2]);
expect(+(dataLabel.getAttribute('y')) > point.symbolLocations[0].y).toBe(true);
done();
};
chart.loaded = loaded;
chart.series[0].marker.dataLabel.position = 'Bottom';
chart.refresh();
});
it('checking with tooltip positive values', (done: Function) => {
loaded = (args: Object): void => {
//positive y yValues
dataLabel = document.getElementById('container_Series_0_Point_2_Symbol');
series = <Series>chart.series[0];
chartArea = document.getElementById('container_ChartAreaBorder');
y = series.points[2].regions[0].y + parseFloat(chartArea.getAttribute('y')) + element.offsetTop;
x = series.points[2].regions[0].x + parseFloat(chartArea.getAttribute('x')) + element.offsetLeft;
trigger.mousemovetEvent(dataLabel, Math.ceil(x), Math.ceil(y));
tooltip = document.getElementById('container_tooltip');
expect(tooltip != null).toBe(true);
expect(parseFloat(tooltip.style.left) > series.points[2].regions[0].y + parseFloat(chartArea.getAttribute('y')));
done();
};
chart.loaded = loaded;
chart.tooltip.enable = true;
chart.refresh();
});
it('checking with track ball', (done: Function) => {
loaded = (args: Object): void => {
dataLabel = document.getElementById('container_Series_0_Point_1_Symbol');
y = series.points[1].regions[0].y + parseFloat(chartArea.getAttribute('y')) + element.offsetTop;
x = series.points[1].regions[0].x + parseFloat(chartArea.getAttribute('x')) + element.offsetLeft;
trigger.mousemovetEvent(dataLabel, Math.ceil(x), Math.ceil(y));
tooltip = document.getElementById('container_tooltip');
expect(tooltip != null).toBe(true);
expect(parseFloat(tooltip.style.top) > series.points[1].regions[0].y + parseFloat(chartArea.getAttribute('y')));
done();
};
chart.loaded = loaded;
chart.tooltip.shared = true;
chart.refresh();
});
it('checking with animation', (done: Function) => {
loaded = (args: Object): void => {
done();
};
chart.loaded = loaded;
chart.series[0].animation.enable = true;
chart.series[1].animation.enable = true;
chart.refresh();
});
});
/**
* Cheacking point drag and drop with step area series
*/
describe('Step area series with drag and drop support', () => {
let chartObj: Chart; let x: number; let y: number;
let loaded: EmitType<ILoadedEventArgs>;
let trigger: MouseEvents = new MouseEvents();
let element1: HTMLElement = createElement('div', { id: 'container' });
beforeAll(() => {
document.body.appendChild(element1);
chartObj = new Chart(
{
primaryXAxis: {
valueType: 'DateTime',
labelFormat: 'y',
intervalType: 'Years',
edgeLabelPlacement: 'Shift',
majorGridLines: { width: 0 }
},
//Initializing Primary Y Axis
primaryYAxis:
{
labelFormat: '{value}%',
rangePadding: 'None',
minimum: 0,
maximum: 100,
interval: 20,
lineStyle: { width: 0 },
majorTickLines: { width: 0 },
minorTickLines: { width: 0 }
},
chartArea: {
border: {
width: 0
}
},
//Initializing Chart Series
series: [
{
type: 'StepArea',
dataSource: [
{ x: new Date(2005, 0, 1), y: 21 }, { x: new Date(2006, 0, 1), y: 24 },
{ x: new Date(2007, 0, 1), y: 36 }, { x: new Date(2008, 0, 1), y: 38 },
{ x: new Date(2009, 0, 1), y: 54 }, { x: new Date(2010, 0, 1), y: 57 },
{ x: new Date(2011, 0, 1), y: 70 }
],
animation: { enable: false },
xName: 'x', width: 2, marker: {
visible: true,
width: 20,
height: 20
},
yName: 'y', name: 'Germany', dragSettings: { enable: true }
}
],
//Initializing Chart title
title: 'Inflation - Consumer Price',
//Initializing User Interaction Tooltip
tooltip: {
enable: true
},
});
chartObj.appendTo('#container');
});
afterAll((): void => {
chartObj.destroy();
element1.remove();
});
it('Step area series drag and drop with marker true', (done: Function) => {
loaded = (): void => {
let target: HTMLElement = document.getElementById('container_Series_0_Point_3_Symbol');
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(target.getAttribute('cy')) + parseFloat(chartArea.getAttribute('y')) + element1.offsetTop;
x = parseFloat(target.getAttribute('cx')) + parseFloat(chartArea.getAttribute('x')) + element1.offsetLeft;
trigger.mousemovetEvent(target, Math.ceil(x), Math.ceil(y));
trigger.draganddropEvent(element1, Math.ceil(x), Math.ceil(y), Math.ceil(x), Math.ceil(y) - 208);
let yValue: number = chartObj.visibleSeries[0].points[3].yValue;
expect(yValue == 100 || yValue == 99.12).toBe(true);
chartObj.loaded = null;
done();
};
chartObj.loaded = loaded;
chartObj.refresh();
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
});
export interface series1 {
series: Series;
} | the_stack |
import type { CharSet } from "refa"
import { CharBase } from "refa"
import type { MatchingDirection, ReadonlyFlags } from "regexp-ast-analysis"
import {
isPotentiallyZeroLength,
getFirstCharAfter,
Chars,
getLengthRange,
getMatchingDirection,
hasSomeDescendant,
isEmptyBackreference,
toCharSet,
} from "regexp-ast-analysis"
import type { Alternative, Element, Node, Pattern } from "regexpp/ast"
import { getLongestPrefix } from "./regexp-ast/alternative-prefix"
/**
* This extends the {@link MatchingDirection} type to allow unknown matching
* directions.
*
* This is useful when the matching direction of an element/alternative cannot
* be known with 100% certainty.
*/
export type OptionalMatchingDirection = MatchingDirection | "unknown"
export interface CanReorderOptions {
/**
* The matching direction of the alternatives.
*
* The correctness of {@link canReorder} depends on this direction being
* correct.
*
* If the matching direction cannot be known, supply `"unknown"`.
* `"unknown"` is guaranteed to always create a correct result regardless
* of matching direction.
*
* This value defaults to the result of {@link getMatchingDirection} for
* any of the given alternatives.
*/
matchingDirection?: OptionalMatchingDirection
ignoreCapturingGroups?: boolean
}
/**
* Returns whether the given alternatives can all be reordered.
*
* However, there are restriction how alternatives can be reordered. Let T be
* the set of the given alternatives and let U be the set of alternatives that
* are **not** given and have the same parent as the given alternatives.
*
* If T is empty or U is empty, then the given alternatives can be reordered
* freely without any restrictions. Otherwise, the following restrictions apply:
*
* 1. All alternatives in U must remain in the same position relative to each
* other.
* 2. Let L and R be the lest most and right most alternatives in T. All
* alternatives left of L must stay to the left of L and all alternatives
* right of R must stay to the right of R.
*
* Example: `/0|1|2|A|3|4|B|C|5|6/`
*
* If given the alternatives `A`, `B`, `C`, then `true` will be returned. The
* following are valid reorderings:
*
* - `/0|1|2|A|3|4|B|C|5|6/` (unchanged)
* - `/0|1|2|3|A|4|B|C|5|6/`
* - `/0|1|2|3|4|A|B|C|5|6/`
* - `/0|1|2|A|B|3|4|C|5|6/`
* - `/0|1|2|A|B|C|3|4|5|6/`
*
* The following are invalid reorderings:
*
* - `/0|1|2|A|4|3|B|C|5|6/` (restriction 1)
* - `/A|0|1|2|3|4|B|C|5|6/` (restriction 2)
* - `/0|1|2|A|3|4|C|5|6|B/` (restriction 2)
*/
export function canReorder(
alternatives: Iterable<Alternative>,
flags: ReadonlyFlags,
options: CanReorderOptions = {},
): boolean {
const { ignoreCapturingGroups = false, matchingDirection } = options
const target = asSet(alternatives)
if (target.size < 2) {
// we can trivially reorder 0 or 1 alternatives
return true
}
const slice = getAlternativesSlice(target)
const dir = matchingDirection ?? getMatchingDirection(slice[0])
const eqClasses =
dir === "unknown"
? getDirectionIndependedDeterminismEqClasses(slice, flags)
: getDeterminismEqClasses(slice, dir, flags)
if (
!ignoreCapturingGroups &&
!canReorderCapturingGroups(target, slice, eqClasses)
) {
return false
}
// from this point onward, we don't have to worry about capturing groups
// anymore
// we only have to prove that we can reorder alternatives within each
// equivalence class.
return eqClasses.every((eq) => {
if (eq.length < 2) {
return true
}
if (eq.every((a) => !target.has(a))) {
// This equivalence class contains only non-target alternatives.
// As by the guarantees provided by this function, these
// alternatives are not required to be reorderable.
return true
}
return (
canReorderBasedOnLength(eq) ||
canReorderBasedOnConsumedChars(eq, flags)
)
})
}
/**
* Returns whether the capturing groups in the slice alternative can be
* reordered.
*/
function canReorderCapturingGroups(
target: ReadonlySet<Alternative>,
slice: readonly Alternative[],
eqClasses: readonly (readonly Alternative[])[],
): boolean {
// Reordering and capturing groups:
// Reordering doesn't play well with capturing groups because changing
// the order of two capturing groups is a change that can be observed
// by the user and might break the regex. So we have to avoid changing
// the relative order of two alternatives with capturing groups.
//
// Since target alternatives can be reordered, there must be at most one
// target alternative containing capturing groups. If one target
// alternative contains capturing groups, no other alternative in the
// slice is allowed to contain capturing groups.
const containsCG = cachedFn(containsCapturingGroup)
let targetCG = 0
let nonTargetCG = 0
for (const a of slice) {
if (containsCG(a)) {
if (target.has(a)) {
targetCG++
} else {
nonTargetCG++
}
}
}
if (targetCG > 1 || (targetCG === 1 && nonTargetCG !== 0)) {
return false
}
if (nonTargetCG !== 0) {
// A equivalence class containing a capturing group must not contain a
// target alternative.
//
// Here is an example where this doesn't work: `/^(?:a|(b)|b)$/` with
// the targets `a` and `b`. Since `/^(?:a|(b)|b)$/` !=
// `/^(?:a|b|(b))$/`, we cannot reorder the target alternatives.
return eqClasses.every((eq) => {
return (
// no capturing groups
!eq.some(containsCapturingGroup) ||
// or no target alternatives
eq.every((a) => !target.has(a))
)
})
} else if (targetCG !== 0) {
// The target alternative with the capturing group must be in its own
// equivalence class.
return eqClasses.every((eq) => {
return eq.length < 2 || !eq.some(containsCapturingGroup)
})
}
return true
}
/**
* This splits the set of alternative into disjoint non-empty equivalence
* classes based on the characters consumed. The equivalence classes can be
* reordered freely but elements within an equivalence class have to be proven
* to be reorderable.
*
* The idea of determinism is that we can reorder alternatives freely if the
* regex engine doesn't have a choice as to which alternative to take.
*
* E.g. we can freely reorder the alternatives `food|butter|bread` because the
* alternative are not a prefix of each other and do not overlap.
*
* @param alternatives This is assumed to be a set of alternatives where all
* alternatives have the same parent. It must be possible to iterate of the
* collection multiple times.
*
* Ideally, the backing data structure of this parameter is `Set` but other
* collection types are also possible.
*/
export function getDeterminismEqClasses(
alternatives: Iterable<Alternative>,
dir: OptionalMatchingDirection,
flags: ReadonlyFlags,
): readonly (readonly Alternative[])[] {
if (dir === "unknown") {
return getDirectionIndependedDeterminismEqClasses(alternatives, flags)
}
return getDirectionalDeterminismEqClasses(alternatives, dir, flags)
}
/**
* This will return equivalence classes independent of the matching direction
* of the given alternatives.
*/
function getDirectionIndependedDeterminismEqClasses(
alternatives: Iterable<Alternative>,
flags: ReadonlyFlags,
): readonly (readonly Alternative[])[] {
const ltr = getDirectionalDeterminismEqClasses(alternatives, "ltr", flags)
const rtl = getDirectionalDeterminismEqClasses(alternatives, "rtl", flags)
const disjoint = mergeOverlappingSets([...ltr, ...rtl], (s) => s)
const result: (readonly Alternative[])[] = []
for (const sets of disjoint) {
const eq = new Set<Alternative>()
for (const s of sets) {
s.forEach((a) => eq.add(a))
}
result.push([...eq])
}
return result
}
/**
* This splits the set of alternative into disjoint non-empty equivalence
* classes based on the characters consumed. The equivalence classes can be
* reordered freely but elements within an equivalence class have to be proven
* to be reorderable.
*
* The idea of determinism is that we can reorder alternatives freely if the
* regex engine doesn't have a choice as to which alternative to take.
*
* E.g. we can freely reorder the alternatives `food|butter|bread` because the
* alternative are not a prefix of each other and do not overlap.
*/
function getDirectionalDeterminismEqClasses(
alternatives: Iterable<Alternative>,
dir: MatchingDirection,
flags: ReadonlyFlags,
): readonly (readonly Alternative[])[] {
// Step 1:
// We map each alternative to an array of CharSets. Each array represents a
// concatenation that we are sure of. E.g. the alternative `abc*de` will
// get the array `a, b, [cd]`, and `abc` will get `a, b, c`.
const getPrefixCharSets = cachedFn<Alternative, readonly CharSet[]>((a) => {
let prefix = getLongestPrefix(a, dir, flags)
// We optimize a little here.
// All trailing all-characters sets can be removed without affecting
// the result of the equivalence classes.
let all = 0
for (let i = prefix.length - 1; i >= 0; i--) {
if (prefix[i].isAll) {
all++
} else {
break
}
}
if (all > 0) {
prefix = prefix.slice(0, prefix.length - all)
}
return prefix
})
// Step 2:
// Remap the prefix CharSets to use base sets instead. The following
// operations will scale linearly with the number of characters. By using
// base sets instead of the raw CharSets, we can drastically reduce the
// number "logical" characters. It's the same trick refa uses for its DFA
// operations (creation, minimization).
const allCharSets = new Set<CharSet>()
for (const a of alternatives) {
getPrefixCharSets(a).forEach((cs) => allCharSets.add(cs))
}
const base = new CharBase(allCharSets)
interface Prefix {
readonly characters: readonly (readonly number[])[]
readonly alternative: Alternative
}
const prefixes: Prefix[] = []
for (const a of alternatives) {
prefixes.push({
characters: getPrefixCharSets(a).map((cs) => base.split(cs)),
alternative: a,
})
}
// Step 3:
// Create equivalence classes from the prefixes. In the first iteration, we
// will only look at the first character and create equivalence classes
// based on that. Then we will try to further sub-divide the equivalence
// classes based on the second character of the prefixes. This sub-division
// process will continue until one prefix in the a equivalence class runs
// out of characters.
/** Subdivide */
function subdivide(
eqClass: readonly Prefix[],
index: number,
): (readonly Prefix[])[] {
if (eqClass.length < 2) {
return [eqClass]
}
for (const prefix of eqClass) {
if (index >= prefix.characters.length) {
// ran out of characters
return [eqClass]
}
}
const disjointSets = mergeOverlappingSets(
eqClass,
(p) => p.characters[index],
)
const result: (readonly Prefix[])[] = []
for (const set of disjointSets) {
result.push(...subdivide(set, index + 1))
}
return result
}
return subdivide(prefixes, 0).map((eq) => eq.map((p) => p.alternative))
}
class SetEquivalence {
private readonly indexes: number[]
public readonly count: number
public constructor(count: number) {
this.count = count
this.indexes = []
for (let i = 0; i < count; i++) {
this.indexes.push(i)
}
}
public makeEqual(a: number, b: number): void {
// This works using the following idea:
// 1. If the eq set of a and b is the same, then we can stop.
// 2. If indexes[a] < indexes[b], then we want to make
// indexes[b] := indexes[a]. However, this means that we lose the
// information about the indexes[b]! So we will store
// oldB := indexes[b], then indexes[b] := indexes[a], and then
// make oldB == a.
// 3. If indexes[a] > indexes[b], similar to 2.
let aValue = this.indexes[a]
let bValue = this.indexes[b]
while (aValue !== bValue) {
if (aValue < bValue) {
this.indexes[b] = aValue
// eslint-disable-next-line no-param-reassign -- x
b = bValue
bValue = this.indexes[b]
} else {
this.indexes[a] = bValue
// eslint-disable-next-line no-param-reassign -- x
a = aValue
aValue = this.indexes[a]
}
}
}
/**
* This returns:
*
* 1. `eqSet.count`: How many different equivalence classes there are.
* 2. `eqSet.indexes`: A map (array) from each element (index) to the index
* of its equivalence class.
*
* All equivalence class indexes `eqSet.indexes[i]` are guaranteed to
* be <= `eqSet.count`.
*/
public getEquivalenceSets(): { count: number; indexes: number[] } {
let counter = 0
for (let i = 0; i < this.count; i++) {
if (i === this.indexes[i]) {
this.indexes[i] = counter++
} else {
this.indexes[i] = this.indexes[this.indexes[i]]
}
}
return {
count: counter,
indexes: this.indexes,
}
}
}
/**
* Given a set of sets (`S`), this will merge all overlapping sets until all
* sets are disjoint.
*
* This assumes that all sets contain at least one element.
*
* This function will not merge the given sets itself. Instead, it will
* return an iterable of sets (`Set<S>`) of sets (`S`) to merge. Each set (`S`)
* is guaranteed to be returned exactly once.
*
* Note: Instead of actual JS `Set` instances, the implementation will treat
* `readonly S[]` instances as sets. This makes the whole implementation a lot
* more efficient.
*/
function mergeOverlappingSets<S, E>(
sets: readonly S[],
getElements: (set: S) => Iterable<E>,
): (readonly S[])[] {
if (sets.length < 2) {
return [sets]
}
const eq = new SetEquivalence(sets.length)
const elementMap = new Map<E, number>()
for (let i = 0; i < sets.length; i++) {
const s = sets[i]
for (const e of getElements(s)) {
const elementSet = elementMap.get(e)
if (elementSet === undefined) {
// It's the first time we see this element.
elementMap.set(e, i)
} else {
// We've seen this element before in another set.
// Make the 2 sets equal.
eq.makeEqual(i, elementSet)
}
}
}
const eqSets = eq.getEquivalenceSets()
const result: S[][] = []
for (let i = 0; i < eqSets.count; i++) {
result.push([])
}
for (let i = 0; i < sets.length; i++) {
result[eqSets.indexes[i]].push(sets[i])
}
return result
}
/**
* Returns whether alternatives can be reordered because they all have the same
* length.
*
* No matter which alternative the regex engine picks, we will always end up in
* the same place after.
*/
function canReorderBasedOnLength(slice: readonly Alternative[]): boolean {
const lengthRange = getLengthRange(slice)
return Boolean(lengthRange && lengthRange.min === lengthRange.max)
}
/**
* Returns whether alternatives can be reordered because the characters
* consumed.
*
* If the given alternatives are preceded and followed by characters not
* consumed by the alternatives, then the order order of the alternatives
* doesn't matter.
*/
function canReorderBasedOnConsumedChars(
slice: readonly Alternative[],
flags: ReadonlyFlags,
): boolean {
// we assume that at least one character is consumed in each alternative
if (slice.some(isPotentiallyZeroLength)) {
return false
}
const parent = slice[0].parent
if (parent.type === "Pattern" || parent.type === "Assertion") {
return false
}
const consumedChars = Chars.empty(flags).union(
...slice.map((a) => getConsumedChars(a, flags)),
)
return (
getFirstCharAfter(parent, "rtl", flags).char.isDisjointWith(
consumedChars,
) &&
getFirstCharAfter(parent, "ltr", flags).char.isDisjointWith(
consumedChars,
)
)
}
/**
* Returns the smallest slice of alternatives that contains all given
* alternatives.
*/
function getAlternativesSlice(set: ReadonlySet<Alternative>): Alternative[] {
if (set.size <= 1) {
return [...set]
}
let first
for (const item of set) {
first = item
break
}
if (!first) {
throw new Error()
}
const parentAlternatives = first.parent.alternatives
let min = set.size
let max = 0
for (let i = 0; i < parentAlternatives.length; i++) {
const a = parentAlternatives[i]
if (set.has(a)) {
min = Math.min(min, i)
max = Math.max(max, i)
}
}
return parentAlternatives.slice(min, max + 1)
}
/**
* Returns a readonly set containing all elements of the given iterable.
*/
function asSet<T>(iter: Iterable<T>): ReadonlySet<T> {
if (iter instanceof Set) {
return iter
}
return new Set(iter)
}
/**
* Returns the union of all characters that can possibly be consumed by the
* given element.
*/
function getConsumedChars(
element: Element | Pattern | Alternative,
flags: ReadonlyFlags,
): CharSet {
const sets: CharSet[] = []
// we misuse hasSomeDescendant to iterate all relevant elements
hasSomeDescendant(
element,
(d) => {
if (
d.type === "Character" ||
d.type === "CharacterClass" ||
d.type === "CharacterSet"
) {
sets.push(toCharSet(d, flags))
} else if (d.type === "Backreference" && !isEmptyBackreference(d)) {
sets.push(getConsumedChars(d.resolved, flags))
}
// always continue to the next element
return false
},
// don't go into assertions
(d) => d.type !== "Assertion" && d.type !== "CharacterClass",
)
return Chars.empty(flags).union(...sets)
}
/** Returns whether the given node contains a capturing group. */
function containsCapturingGroup(node: Node): boolean {
return hasSomeDescendant(node, (d) => d.type === "CapturingGroup")
}
interface CachedFn<S, T> {
(value: S): T
readonly cache: Map<S, T>
}
/**
* Create a new cached function.
*/
function cachedFn<S, T>(fn: (value: S) => T): CachedFn<S, T> {
/** */
function wrapper(value: S): T {
let cached = wrapper.cache.get(value)
if (cached === undefined) {
cached = fn(value)
wrapper.cache.set(value, cached)
}
return cached
}
wrapper.cache = new Map<S, T>()
return wrapper
} | the_stack |
import App from "../app";
import {pubsub} from "../helpers/subscriptionManager";
import * as Classes from "../classes";
import uuid from "uuid";
import {resolvers} from "../data";
// Simulator
App.on("createSimulator", ({id = uuid.v4(), name, template, flightId}) => {
const simulator = new Classes.Simulator({
id,
name,
template,
});
if (flightId) {
const flight = App.flights.find(f => f.id === flightId);
flight.addSimulator(simulator);
}
App.simulators.push(simulator);
// Initialize the simulator.
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("removeSimulator", ({simulatorId}) => {
App.simulators = App.simulators.filter(s => s.id !== simulatorId);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("renameSimulator", ({simulatorId, name}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
simulator.rename(name);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("changeSimulatorLayout", ({simulatorId, layout}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
if (simulator) {
simulator.setLayout(layout);
}
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("changeSimulatorCaps", ({simulatorId, caps}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
if (simulator) {
simulator.caps = caps;
}
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("changeSimulatorAlertLevel", ({simulatorId, alertLevel}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
if (simulator && alertLevel !== simulator.alertlevel) {
simulator.setAlertLevel(alertLevel);
pubsub.publish("notify", {
id: uuid.v4(),
simulatorId: simulator.id,
type: "Alert Condition",
station: "Core",
title: `Alert Level ${alertLevel}`,
body: "",
color: "info",
});
App.handleEvent(
{
simulatorId: simulator.id,
title: `Alert Level ${alertLevel}`,
component: "AlertConditionCore",
body: null,
color: "info",
},
"addCoreFeed",
);
// Records Notification
App.handleEvent(
{
simulatorId: simulator.id,
contents: `${alertLevel}`,
category: "Alert Condition",
},
"recordsCreate",
);
}
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("changeSimulatorExocomps", ({simulatorId, exocomps}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
if (simulator) {
simulator.exocomps = exocomps;
}
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("changeSimulatorBridgeCrew", ({simulatorId, crew}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
if (simulator) {
simulator.bridgeCrew(crew);
}
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("changeSimulatorExtraPeople", ({simulatorId, crew}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
if (simulator) {
simulator.extraPeople(crew);
}
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("changeSimulatorRadiation", ({simulatorId, radiation}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
if (simulator) {
simulator.radiation(radiation);
}
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setSimulatorTimelineStep", ({simulatorId, timelineId, step}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
if (simulator) {
simulator.setTimelineStep(step, timelineId);
}
pubsub.publish("simulatorsUpdate", App.simulators);
if (timelineId) {
pubsub.publish("auxTimelinesUpdate", simulator);
}
});
App.on("addSimulatorDamageStep", ({simulatorId, step}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
sim.addDamageStep(step);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("updateSimulatorDamageStep", ({simulatorId, step}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
sim.updateDamageStep(step);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("removeSimulatorDamageStep", ({simulatorId, step}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
sim.removeDamageStep(step);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("addSimulatorDamageTask", ({simulatorId, task}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
sim.addDamageTask(task);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("updateSimulatorDamageTask", ({simulatorId, task}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
sim.updateDamageTask(task);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("removeSimulatorDamageTask", ({simulatorId, taskId}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
sim.removeDamageTask(taskId);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setSimulatorMission", ({simulatorId, missionId, stepId}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
simulator.mission = missionId;
const mission = App.missions.find(s => s.id === missionId);
const stepIndex = mission?.timeline.findIndex(s => s.id === stepId);
simulator.setTimelineStep(stepIndex > 0 ? stepIndex : 0);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on(
"setSimulatorMissionConfig",
({simulatorId, missionId, stationSetId, actionId, args}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
simulator.setMissionConfig(missionId, stationSetId, actionId, args);
pubsub.publish("simulatorsUpdate", App.simulators);
},
);
App.on("updateSimulatorPanels", ({simulatorId, panels}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
simulator.updatePanels(panels);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("updateSimulatorCommandLines", ({simulatorId, commandLines}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
simulator.updateCommandLines(commandLines);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("updateSimulatorTriggers", ({simulatorId, triggers}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
simulator.updateTriggers(triggers);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("updateSimulatorInterfaces", ({simulatorId, interfaces}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
simulator.updateInterfaces(interfaces);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setSimulatorTriggersPaused", ({simulatorId, paused}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
simulator.setTriggersPaused(paused);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setStepDamage", ({simulatorId, stepDamage}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
simulator.stepDamage = stepDamage;
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setVerifyDamage", ({simulatorId, verifyStep}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
simulator.verifyStep = verifyStep;
pubsub.publish("simulatorsUpdate", App.simulators);
});
const allowedMacros = [
"updateViewscreenComponent",
"setViewscreenToAuto",
"showViewscreenTactical",
"autoAdvance",
];
App.on("triggerMacros", ({simulatorId, macros}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
const flight = App.flights.find(f => f.simulators.indexOf(simulatorId) > -1);
const context = {simulator, flight};
// Compile the simulator-specific args based on station set
const actions = Object.values(simulator.missionConfigs)
.map(m => {
return m[simulator.stationSet];
})
.reduce((acc, next) => ({...acc, ...next}), {});
macros.forEach(
({id, stepId = id, event, args, delay = 0, noCancelOnReset}) => {
const simArgs = actions[stepId] || {};
if (stepId) {
simulator.executeTimelineStep(stepId);
}
const timeout = setTimeout(() => {
const parsedArgs = typeof args === "string" ? JSON.parse(args) : args;
App.handleEvent(
{
...parsedArgs,
...simArgs,
simulatorId,
},
event,
context,
);
}, delay);
if (!noCancelOnReset) flight.timeouts.push(timeout);
},
);
});
App.on("autoAdvance", ({simulatorId, prev}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
const {mission, currentTimelineStep, executedTimelineSteps} = sim;
const missionObj = App.missions.find(m => m.id === mission);
if (!missionObj) return;
if (prev && currentTimelineStep - 2 < 0) return;
const timelineStep =
missionObj.timeline[currentTimelineStep - (prev ? 2 : 0)];
if (!timelineStep) return;
const macros = timelineStep.timelineItems.filter(t => {
if (executedTimelineSteps.indexOf(t.id) === -1) return true;
if (allowedMacros.indexOf(t.event) > -1) return true;
if (executedTimelineSteps.indexOf(t.id) > -1) return false;
return true;
});
macros.forEach(({id}) => {
sim.executeTimelineStep(id);
});
App.handleEvent({simulatorId, macros}, "triggerMacros");
sim.setTimelineStep(currentTimelineStep + (prev ? -1 : 1));
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setBridgeMessaging", ({id, messaging}) => {
const sim = App.simulators.find(s => s.id === id);
sim.bridgeOfficerMessaging = messaging;
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setSimulatorAssets", ({id, assets}) => {
const sim = App.simulators.find(s => s.id === id);
sim.setAssets(assets);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setSimulatorSoundEffects", ({id, soundEffects}) => {
const sim = App.simulators.find(s => s.id === id);
sim.setSoundEffects(soundEffects);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("updateSimulatorAmbiance", ({id, ambiance, cb}) => {
const sim = App.simulators.find(s => s.id === id);
sim.updateAmbiance(ambiance);
pubsub.publish("simulatorsUpdate", App.simulators);
cb && cb();
});
App.on("addSimulatorAmbiance", ({id, name, cb}) => {
const sim = App.simulators.find(s => s.id === id);
sim.addAmbiance({name});
pubsub.publish("simulatorsUpdate", App.simulators);
cb && cb();
});
App.on("removeSimulatorAmbiance", ({id, ambianceId, cb}) => {
const sim = App.simulators.find(s => s.id === id);
sim.removeAmbiance(ambianceId);
pubsub.publish("simulatorsUpdate", App.simulators);
cb && cb();
});
App.on(
"addSimulatorStationCard",
({simulatorId, station, cardName, cardComponent, cb}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
const stat = sim.stations.find(s => s.name === station);
stat.addCard({
name: cardName,
component: cardComponent,
});
pubsub.publish("simulatorsUpdate", App.simulators);
cb && cb();
},
);
App.on("removeSimulatorStationCard", ({simulatorId, station, cardName}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
const stat = sim.stations.find(s => s.name === station);
stat.removeCard(cardName);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on(
"editSimulatorStationCard",
({simulatorId, station, cardName, newCardName, cardComponent}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
const stat = sim.stations.find(s => s.name === station);
stat.updateCard(cardName, {
name: newCardName,
component: cardComponent,
});
pubsub.publish("simulatorsUpdate", App.simulators);
},
);
App.on(
"setSimulatorStationMessageGroup",
({simulatorId, station, group, state}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
const stat = sim.stations.find(s => s.name === station);
stat.setMessageGroup(group, state);
pubsub.publish("simulatorsUpdate", App.simulators);
},
);
App.on("setSimulatorStationLogin", ({simulatorId, station, login}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
const stat = sim.stations.find(s => s.name === station);
stat.setLogin(login);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setSimulatorStationLayout", ({simulatorId, station, layout, cb}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
const stat = sim.stations.find(s => s.name === station);
stat.setLayout(layout);
pubsub.publish("simulatorsUpdate", App.simulators);
cb();
});
App.on("setSimulatorStationExecutive", ({simulatorId, station, exec}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
const stat = sim.stations.find(s => s.name === station);
stat.setExec(exec);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setSimulatorStationWidget", ({simulatorId, station, widget, state}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
const stat = sim.stations.find(s => s.name === station);
stat.setWidgets(widget, state);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setAlertConditionLock", ({simulatorId, lock}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
sim.setAlertLevelLock(lock);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setSimulatorHasPrinter", ({simulatorId, hasPrinter}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
sim.setHasPrinter(hasPrinter);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setSimulatorHasLegs", ({simulatorId, hasLegs}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
sim.setHasLegs(hasLegs);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("setSimulatorSpaceEdventuresId", ({simulatorId, spaceEdventuresId}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
sim.setSpaceEdventuresId(spaceEdventuresId);
pubsub.publish("simulatorsUpdate", App.simulators);
});
const cardTimeouts = {};
App.on("hideSimulatorCard", ({simulatorId, cardName, delay}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
if (!sim) return;
sim.hideCard(cardName);
if (!isNaN(parseInt(delay, 10))) {
cardTimeouts[`${simulatorId}-${cardName}`] = setTimeout(() => {
sim.unhideCard(cardName);
pubsub.publish("simulatorsUpdate", App.simulators);
delete cardTimeouts[`${simulatorId}-${cardName}`];
}, parseInt(delay, 10));
}
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("unhideSimulatorCard", ({simulatorId, cardName}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
if (!sim) return sim;
sim.unhideCard(cardName);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("toggleSimulatorCardHidden", ({simulatorId, cardName, toggle}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
if (!sim) return sim;
clearTimeout(cardTimeouts[`${simulatorId}-${cardName}`]);
delete cardTimeouts[`${simulatorId}-${cardName}`];
if (toggle) {
sim.hideCard(cardName);
} else {
sim.unhideCard(cardName);
}
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("flipSimulator", ({simulatorId, flip}) => {
const sim = App.simulators.find(s => s.id === simulatorId);
if (!sim) return sim;
sim.flip(flip);
pubsub.publish("simulatorsUpdate", App.simulators);
});
App.on("stationAssignCard", ({simulatorId, assignedToStation, cardName}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
const card = simulator.stations
.reduce((acc, next) => acc.concat(next.cards), [])
.find(c => c.name === cardName);
// Remove it so it isn't double-assigned
simulator.removeStationAssignedCard(cardName);
simulator.addStationAssignedCard(assignedToStation, card);
pubsub.publish("simulatorsUpdate", App.simulators);
pubsub.publish("clientChanged", App.clients);
});
App.on("stationUnassignCard", ({simulatorId, cardName}) => {
const simulator = App.simulators.find(s => s.id === simulatorId);
simulator.removeStationAssignedCard(cardName);
pubsub.publish("simulatorsUpdate", App.simulators);
pubsub.publish("clientChanged", App.clients);
}); | the_stack |
import {HomeAssistant} from "custom-card-helpers/dist";
import {Current, Forecast, IconsConfig, Sea} from "./types";
import { html } from "lit-element";
import {getUnit, getWeatherIcon,numFormat, pad} from "./ha-cwc-utils";
const _renderSeaTemperature = (hass: HomeAssistant, hours,
air_temperatures: [string, any][],
water_temperatures: [string, any][]) => {
return html`
<div class="day">
${hours.map(hour => {
let air_temperatures_name = air_temperatures[hour.toString()][1],
air_temperatures_sensor = hass.states[air_temperatures_name] ;
let water_temperatures_name = water_temperatures[hour.toString()][1],
water_temperatures_sensor = hass.states[water_temperatures_name] ;
let air_temperature = numFormat( air_temperatures_sensor.state, 0 ),
air_temperature_unit = air_temperatures_sensor.attributes.unit_of_measurement ;
let water_temperature = numFormat( water_temperatures_sensor.state, 0 ),
water_temperature_unit = water_temperatures_sensor.attributes.unit_of_measurement ;
return html`
<div class="highTemp">
<div class="list-group-content">
<div class="inline-block">${water_temperature} - ${air_temperature} ${water_temperature_unit}</div>
</div>
</div>
` ;
})}
</div>
`;
} ;
const _renderSeaWind = (hass: HomeAssistant, hours,
wind_directions: [string, any][],
wind_speeds: [string, any][]) => {
return html`
<div class="day">
${hours.map(hour => {
let wind_dir_name = wind_directions[hour.toString()][1],
wind_dir_sensor = hass.states[wind_dir_name] ;
let wind_speed_name = wind_speeds[hour.toString()][1],
wind_speed_sensor = hass.states[wind_speed_name] ;
let degree = parseFloat( wind_dir_sensor.state ) + "deg"; // , cssclass = (degree % 10==0) ? degree : degree-degree%5 +5 ;
let wind_speed = numFormat( wind_speed_sensor.state, 0),
wind_speed_unit = wind_speed_sensor.attributes.unit_of_measurement ;
return html`
<div class="highTemp">
<div class="list-group-content">
<div class="inline-block">${wind_speed} ${wind_speed_unit}</div>
<span class="svg-icon svg-wind-icon svg-wind-icon-dark" style="transform: rotate(${degree});
-ms-transform: rotate(${degree}); -webkit-transform: rotate(${degree});"></span>
</div>
</div>
` ;
})}
</div>
`;
} ;
const _renderSeaSwell_old = (hass: HomeAssistant, hours,
swell_directions: [string, any][],
swell_heights: [string, any][],
swell_periods: [string, any][]) => {
return html`
<div class="day">
${hours.map(hour => {
let swell_dir_name = swell_directions[hour.toString()][1],
well_dir_sensor = hass.states[swell_dir_name] ;
let swell_height_name = swell_heights[hour.toString()][1],
swell_height_sensor = hass.states[swell_height_name] ;
let swell_periods_name = swell_periods[hour.toString()][1],
swell_periods_sensor = hass.states[swell_periods_name] ;
let degree = parseFloat( well_dir_sensor.state ) + "deg" ; // , cssclass = (degree % 10==0) ? degree : degree-degree%5 +5 ;
let height = numFormat( swell_height_sensor.state ),
height_unit = swell_height_sensor.attributes.unit_of_measurement ;
let period = numFormat( swell_periods_sensor.state, 0),
period_unit = swell_periods_sensor.attributes.unit_of_measurement ;
return html`
<div class="highTemp">
<div class="list-group-content">
<div class="inline-block">
${(new Date(well_dir_sensor.attributes.observation_time)).getHours()}:00 - ${height}${height_unit} / ${period}${period_unit}</div>
<span class="svg-icon svg-wind-icon svg-wind-icon-dark" style="transform: rotate(${degree});
-ms-transform: rotate(${degree}); -webkit-transform: rotate(${degree});"></span>
</div>
</div>
` ;
})}
</div>
`;
} ;
const _renderSeaSwell = (hass: HomeAssistant, hours,
swell_directions: [string, any][],
swell_heights: [string, any][],
swell_periods: [string, any][],
wind_directions: [string, any][],
wind_speeds: [string, any][]) => {
return html`
<div class="day">
${hours.map(hour => {
let swell_dir_name = swell_directions[hour.toString()][1],
swell_dir_sensor = hass.states[swell_dir_name] ;
let swell_height_name = swell_heights[hour.toString()][1],
swell_height_sensor = hass.states[swell_height_name] ;
let swell_periods_name = swell_periods[hour.toString()][1],
swell_periods_sensor = hass.states[swell_periods_name] ;
let wind_dir_name = wind_directions[hour.toString()][1],
wind_dir_sensor = hass.states[wind_dir_name] ;
let wind_speed_name = wind_speeds[hour.toString()][1],
wind_speed_sensor = hass.states[wind_speed_name] ;
let swell_degree = parseFloat( swell_dir_sensor.state ) + "deg" ; // , cssclass = (degree % 10==0) ? degree : degree-degree%5 +5 ;
let height = numFormat( swell_height_sensor.state ),
height_unit = swell_height_sensor.attributes.unit_of_measurement ;
let period = numFormat( swell_periods_sensor.state, 0),
period_unit = swell_periods_sensor.attributes.unit_of_measurement ;
let wind_degree = parseFloat( wind_dir_sensor.state ) + "deg"; // , cssclass = (degree % 10==0) ? degree : degree-degree%5 +5 ;
let wind_speed = numFormat( wind_speed_sensor.state, 0),
wind_speed_unit = wind_speed_sensor.attributes.unit_of_measurement ;
return html`
<div class="highTemp">
<div class="list-group-content">
<div class="inline-block">
${(new Date(swell_dir_sensor.attributes.observation_time)).getHours()}:00
${height}${height_unit} / ${period}${period_unit}
</div>
<span class="svg-icon svg-swell-icon svg-swell-icon-dark" style="transform: rotate(${swell_degree});
-ms-transform: rotate(${swell_degree}); -webkit-transform: rotate(${swell_degree});"></span>
</div>
<div class="inline-block">
${wind_speed} ${wind_speed_unit}
</div>
<span class="svg-icon svg-wind-icon svg-wind-icon-dark" style="transform: rotate(${wind_degree});
-ms-transform: rotate(${wind_degree}); -webkit-transform: rotate(${wind_degree});"></span>
</div>
</div>
` ;
})}
</div>
`;
} ;
// @ts-ignore
export const renderSeaForecast = (hass: HomeAssistant, seaCfg: Sea, iconsConfig: IconsConfig, lang: string, border: boolean) => {
let swell_directions: [string, any][] = seaCfg.swell_direction
? Object.entries(seaCfg.swell_direction) : undefined ;
let swell_heights: [string, any][] = seaCfg.swell_height
? Object.entries(seaCfg.swell_height) : undefined ;
let swell_periods: [string, any][] = seaCfg.swell_period
? Object.entries(seaCfg.swell_period) : undefined ;
let wind_directions: [string, any][] = seaCfg.wind_direction
? Object.entries(seaCfg.wind_direction) : undefined ;
let wind_speeds: [string, any][] = seaCfg.wind_speed
? Object.entries(seaCfg.wind_speed) : undefined ;
let air_temperatures: [string, any][] = seaCfg.air_temperature
? Object.entries(seaCfg.air_temperature) : undefined ;
let water_temperatures: [string, any][] = seaCfg.water_temperature
? Object.entries(seaCfg.water_temperature) : undefined ;
let maxHours = Math.max(swell_directions ? swell_directions.length : 0,
swell_heights ? swell_heights.length : 0, swell_periods ? swell_periods.length : 0);
let startHour = 0;
let hours = maxHours > 0 ?
Array(maxHours - startHour).fill(1, 0, maxHours - startHour).map(() => startHour++)
: Array();
return html`
<div class="forecast clear ${border ? "spacer" : ""}">
<div class="day">
<div class="highTemp">
<table class="synoptic">
<thead>
<tr>
<th>Time</th><th>Swell</th><th>Wind</th><th>Temperature</th>
</tr>
</thead>
<tbody>
${hours.map(hour => {
let swell_dir_name = swell_directions[hour.toString()][1],
swell_dir_sensor = hass.states[swell_dir_name];
let swell_height_name = swell_heights[hour.toString()][1],
swell_height_sensor = hass.states[swell_height_name];
let swell_periods_name = swell_periods[hour.toString()][1],
swell_periods_sensor = hass.states[swell_periods_name];
let wind_dir_name = wind_directions[hour.toString()][1],
wind_dir_sensor = hass.states[wind_dir_name];
let wind_speed_name = wind_speeds[hour.toString()][1],
wind_speed_sensor = hass.states[wind_speed_name];
let air_temperatures_name = air_temperatures[hour.toString()][1],
air_temperatures_sensor = hass.states[air_temperatures_name] ;
let water_temperatures_name = water_temperatures[hour.toString()][1],
water_temperatures_sensor = hass.states[water_temperatures_name] ;
let swell_degree = parseFloat(swell_dir_sensor.state) + "deg"; // , cssclass = (degree % 10==0) ? degree : degree-degree%5 +5 ;
let height = numFormat(swell_height_sensor.state),
height_unit = swell_height_sensor.attributes.unit_of_measurement;
let period = numFormat(swell_periods_sensor.state, 0),
period_unit = swell_periods_sensor.attributes.unit_of_measurement;
let wind_degree = parseFloat(wind_dir_sensor.state) + "deg"; // , cssclass = (degree % 10==0) ? degree : degree-degree%5 +5 ;
let wind_speed = numFormat(wind_speed_sensor.state, 0),
wind_speed_unit = wind_speed_sensor.attributes.unit_of_measurement;
let air_temperature = numFormat( air_temperatures_sensor.state, 0 ),
air_temperature_unit = air_temperatures_sensor.attributes.unit_of_measurement ;
let water_temperature = numFormat( water_temperatures_sensor.state, 1 ),
water_temperature_unit = water_temperatures_sensor.attributes.unit_of_measurement ;
return html`
<tr>
<td>${pad((new Date(swell_dir_sensor.attributes.observation_time)).getHours(), 2)}:00</td>
<td>${height}${height_unit} / ${period}${period_unit}
<span class="svg-icon svg-swell-icon svg-swell-icon-dark" style="transform: rotate(${swell_degree});
-ms-transform: rotate(${swell_degree}); -webkit-transform: rotate(${swell_degree});"></span>
</td>
<td>${wind_speed} ${wind_speed_unit}
<span class="svg-icon svg-wind-icon svg-wind-icon-light" style="transform: rotate(${wind_degree});
-ms-transform: rotate(${wind_degree}); -webkit-transform: rotate(${wind_degree});"></span>
</td>
<td>${water_temperature} - ${air_temperature} ${water_temperature_unit}</td>
</tr>
`;
})}
</tbody>
</table>
</div>
</div>
</div>
`;
} ; | the_stack |
import { Query } from '../../src/query';
import { Source } from '../../src/source';
import { buildTransform } from '../../src/transform';
import { RequestOptions } from '../../src/request';
import {
pullable,
isPullable,
Pullable
} from '../../src/source-interfaces/pullable';
import { ResponseHints } from '../../src/response';
import {
FindRecords,
RecordResponse,
RecordOperation,
RecordQueryExpression,
RecordQueryBuilder,
RecordData,
UpdateRecordOperation
} from '../support/record-data';
const { module, test } = QUnit;
module('@pullable', function (hooks) {
interface MySource
extends Source,
Pullable<
RecordData,
RecordResponse,
RecordOperation,
RecordQueryExpression,
RecordQueryBuilder,
RequestOptions
> {}
@pullable
class MySource extends Source {}
let source: MySource;
hooks.beforeEach(function () {
source = new MySource();
});
test('isPullable - tests for the application of the @pullable decorator', function (assert) {
assert.ok(isPullable(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
@pullable
class Vanilla {}
},
Error(
'Assertion failed: Pullable interface can only be applied to a Source'
),
'assertion raised'
);
});
test('#pull should resolve as a failure when _pull fails', async function (assert) {
assert.expect(2);
source._pull = async function () {
return Promise.reject(':(');
};
try {
await source.pull({ op: 'findRecords', type: 'planet' });
} catch (error) {
assert.ok(true, 'pull promise resolved as a failure');
assert.equal(error, ':(', 'failure');
}
});
test('#pull should trigger `pull` event after a successful action in which `_pull` returns an array of transforms', async function (assert) {
assert.expect(9);
let order = 0;
let qe = { op: 'findRecords', type: 'planet' } as FindRecords;
const fullResponse = {
transforms: [
buildTransform<RecordOperation>({
op: 'updateRecord',
record: { type: 'planet', id: '1' }
}),
buildTransform<RecordOperation>({
op: 'updateRecord',
record: { type: 'planet', id: '2' }
})
]
};
source._pull = async function (query) {
assert.equal(++order, 1, 'action performed after willPull');
assert.strictEqual(query.expressions, qe, 'query object matches');
return fullResponse;
};
let transformCount = 0;
source.on('transform', (transform) => {
assert.strictEqual(
transform,
fullResponse.transforms[transformCount++],
'transform matches'
);
return Promise.resolve();
});
source.on('pull', (query, result) => {
assert.equal(
++order,
2,
'pull triggered after action performed successfully'
);
assert.strictEqual(query.expressions, qe, 'query matches');
assert.strictEqual(result, fullResponse, 'result matches');
});
let result = await source.pull<UpdateRecordOperation>(qe);
assert.equal(++order, 3, 'promise resolved last');
assert.strictEqual(result, fullResponse.transforms, 'success!');
});
test('#pull should resolve all promises returned from `beforePull` before calling `_pull`', async function (assert) {
assert.expect(12);
let order = 0;
let qe = { op: 'findRecords', type: 'planet' } as FindRecords;
const fullResponse = {
transforms: [
buildTransform<RecordOperation>({
op: 'updateRecord',
record: { type: 'planet', id: '1' }
}),
buildTransform<RecordOperation>({
op: 'updateRecord',
record: { type: 'planet', id: '2' }
})
]
};
source.on('beforePull', () => {
assert.equal(++order, 1, 'beforePull triggered first');
return Promise.resolve();
});
source.on('beforePull', () => {
assert.equal(++order, 2, 'beforePull triggered second');
return undefined;
});
source.on('beforePull', () => {
assert.equal(++order, 3, 'beforePull triggered third');
return Promise.resolve();
});
source._pull = async function (query) {
assert.equal(++order, 4, 'action performed after willPull');
assert.strictEqual(query.expressions, qe, 'query object matches');
return fullResponse;
};
let transformCount = 0;
source.on('transform', (transform) => {
assert.strictEqual(
transform,
fullResponse.transforms[transformCount++],
'transform matches'
);
return Promise.resolve();
});
source.on('pull', (query, result) => {
assert.equal(
++order,
5,
'pull triggered after action performed successfully'
);
assert.strictEqual(query.expressions, qe, 'query matches');
assert.strictEqual(result, fullResponse, 'result matches');
});
let result = await source.pull(qe);
assert.equal(++order, 6, 'promise resolved last');
assert.strictEqual(result, fullResponse.transforms, 'success!');
});
test('#pull should resolve all promises returned from `beforePull` and fail if any fail', async function (assert) {
assert.expect(7);
let order = 0;
let qe = { op: 'findRecords', type: 'planet' } as FindRecords;
const fullResponse = {
transforms: []
};
source.on('beforePull', () => {
assert.equal(++order, 1, 'beforePull triggered third');
return Promise.resolve();
});
source.on('beforePull', () => {
assert.equal(++order, 2, 'beforePull triggered third');
return Promise.reject(':(');
});
source._pull = async function (query) {
assert.ok(false, '_pull should not be invoked');
return fullResponse;
};
source.on('pull', () => {
assert.ok(false, 'pull should not be triggered');
});
source.on('pullFail', (query, error) => {
assert.equal(
++order,
3,
'pullFail triggered after an unsuccessful beforePull'
);
assert.strictEqual(query.expressions, qe, 'query matches');
assert.equal(error, ':(', 'error matches');
});
try {
await source.pull(qe);
} catch (error) {
assert.equal(++order, 4, 'promise resolved last');
assert.equal(error, ':(', 'failure');
}
});
test('#pull should trigger `pullFail` event after an unsuccessful pull', async function (assert) {
assert.expect(7);
let order = 0;
let qe = { op: 'findRecords', type: 'planet' } as FindRecords;
source._pull = function (query) {
assert.equal(++order, 1, 'action performed after willPull');
assert.strictEqual(query.expressions, qe, 'query object matches');
return Promise.reject(':(');
};
source.on('pull', () => {
assert.ok(false, 'pull should not be triggered');
});
source.on('pullFail', (query, error) => {
assert.equal(++order, 2, 'pullFail triggered after an unsuccessful pull');
assert.strictEqual(query.expressions, qe, 'query matches');
assert.equal(error, ':(', 'error matches');
});
try {
await source.pull(qe);
} catch (error) {
assert.equal(++order, 3, 'promise resolved last');
assert.equal(error, ':(', 'failure');
}
});
test('#pull should pass a common `hints` object to all `beforePull` events and forward it to `_pull`', async function (assert) {
assert.expect(11);
let order = 0;
let qe = { op: 'findRecords', type: 'planet' } as FindRecords;
let h: ResponseHints<RecordData, RecordResponse>;
const fullResponse = {
transforms: [
buildTransform<RecordOperation>({
op: 'updateRecord',
record: { type: 'planet', id: '1' }
}),
buildTransform<RecordOperation>({
op: 'updateRecord',
record: { type: 'planet', id: '2' }
})
]
};
source.on(
'beforePull',
async function (
query: Query<RecordQueryExpression>,
hints: ResponseHints<RecordData, RecordResponse>
) {
assert.equal(++order, 1, 'beforePull triggered first');
assert.deepEqual(
hints,
{},
'beforePull is passed empty `hints` object'
);
h = hints;
hints.data = [
{ type: 'planet', id: 'venus' },
{ type: 'planet', id: 'mars' }
];
}
);
source.on(
'beforePull',
async function (
query: Query<RecordQueryExpression>,
hints: ResponseHints<RecordData, RecordResponse>
) {
assert.equal(++order, 2, 'beforePull triggered second');
assert.strictEqual(
hints,
h,
'beforePull is passed same hints instance'
);
}
);
source.on(
'beforePull',
async function (
query: Query<RecordQueryExpression>,
hints: ResponseHints<RecordData, RecordResponse>
) {
assert.equal(++order, 3, 'beforePull triggered third');
assert.strictEqual(
hints,
h,
'beforePull is passed same hints instance'
);
}
);
source._pull = async function (
query: Query<RecordQueryExpression>,
hints?: ResponseHints<RecordData, RecordResponse>
) {
assert.equal(
++order,
4,
'_query invoked after all `beforeQuery` handlers'
);
assert.strictEqual(hints, h, '_query is passed same hints instance');
return { data: hints?.data, transforms: fullResponse.transforms };
};
source.on('pull', async function () {
assert.equal(
++order,
5,
'pull triggered after action performed successfully'
);
});
let result = await source.pull(qe);
assert.equal(++order, 6, 'promise resolved last');
assert.deepEqual(result, fullResponse.transforms, 'success!');
});
test('#pull can return a full response, with `transforms` nested in a response object', async function (assert) {
assert.expect(7);
let order = 0;
let qe = { op: 'findRecords', type: 'planet' } as FindRecords;
const fullResponse = {
transforms: [
buildTransform<RecordOperation>({
op: 'updateRecord',
record: { type: 'planet', id: '1' }
}),
buildTransform<RecordOperation>({
op: 'updateRecord',
record: { type: 'planet', id: '2' }
})
]
};
source._pull = async function (query) {
assert.equal(++order, 1, 'action performed after beforeQuery');
assert.strictEqual(query.expressions, qe, 'query object matches');
return fullResponse;
};
source.on('pull', (query, result) => {
assert.equal(
++order,
2,
'pull triggered after action performed successfully'
);
assert.strictEqual(query.expressions, qe, 'query matches');
assert.deepEqual(result, fullResponse, 'result matches');
});
let result = await source.pull(qe, { fullResponse: true });
assert.equal(++order, 3, 'promise resolved last');
assert.deepEqual(result, fullResponse, 'success!');
});
test('#pull can return a full response, with `transforms`, `details`, and `sources` nested in a response object', async function (assert) {
assert.expect(9);
let order = 0;
let qe = { op: 'findRecords', type: 'planet' } as FindRecords;
const result1 = [
{
type: 'planet',
id: 'p1'
}
];
const details1 = {
data: result1,
links: {
self: 'https://example.com/api/planets'
}
};
const transforms1 = [
buildTransform<RecordOperation>({
op: 'updateRecord',
record: { type: 'planet', id: '1' }
}),
buildTransform<RecordOperation>({
op: 'updateRecord',
record: { type: 'planet', id: '2' }
})
];
const expectedResult = {
transforms: transforms1,
details: details1,
// source-specific responses are based on beforePull responses
sources: {
remote: { details: details1 }
}
};
source.on('beforePull', async (query) => {
assert.equal(++order, 1, 'beforePull triggered first');
assert.strictEqual(query.expressions, qe, 'beforePull: query matches');
return ['remote', { details: details1 }];
});
source._pull = async function (query) {
assert.equal(++order, 2, 'action performed after beforeQuery');
assert.strictEqual(query.expressions, qe, '_pull: query matches');
return {
transforms: transforms1,
details: details1
};
};
source.on('pull', (query, result) => {
assert.equal(
++order,
3,
'pull triggered after action performed successfully'
);
assert.strictEqual(query.expressions, qe, 'pull: query matches');
assert.deepEqual(result, expectedResult, 'pull: result matches');
});
const result = await source.pull(qe, {
fullResponse: true
});
assert.equal(++order, 4, 'request resolved last');
assert.deepEqual(result, expectedResult, 'success!');
});
}); | the_stack |
import path from 'path'
import { ExtensionActiveType, ExtensionService, MenuDetail, ExtensionAccessor } from './ExtensionService'
import { MessagePipeline } from './MessageTransfer'
import { Resource, StorageAccessor } from '@/../public/Resource'
import { ResourcePath } from './common/ResourcePath'
import { Result } from './common/Result'
import { config } from '@/../public/CivetConfig'
import { APIFactory } from './ExtensionAPI'
import { isFileExist, getExtensionPath} from '@/../public/Utility'
import { CivetDatabase } from './Kernel'
import { PropertyType } from '../public/ExtensionHostType'
import { ExtensionInstallManager, ExtensionDescriptor } from './ExtensionInstallManager'
import { logger } from '@/../public/Logger'
import fs from 'fs'
import { injectable, showErrorInfo } from './Singleton'
import { IPCRendererResponse, IPCNormalMessage } from '@/../public/IPCMessage'
class ExtensionCommandAccessor implements ExtensionAccessor {
#commands: Set<string>;
#overview: string;
constructor(overview: string) {
this.#overview = overview
this.#commands = new Set<string>()
}
visit(service: ExtensionService) {
this.menu(service)
}
result() {
return this.#commands
}
private menu(service: ExtensionService) {
const m = service.menus
const items: MenuDetail[] = m[this.#overview]
if (items) {
for (let item of items) {
this.#commands.add(item.command)
}
}
}
}
class ExtensionMenuAccessor implements ExtensionAccessor {
#menus: MenuDetail[] = [];
#context: string;
constructor(context: string) {
this.#context = context
}
visit(service: ExtensionService) {
const m = service.menus
const items: MenuDetail[] = m[this.#context]
if (items) {
this.#menus = this.#menus.concat(items)
}
}
result(){
return this.#menus
}
}
class MenuCommand {
group: string;
command: string;
name: string;
id: string;
}
class ExtensionAllMenuAccessor implements ExtensionAccessor {
#menus: any[] = [];
visit(service: ExtensionService) {
const m = service.menus
for (let context in m) {
const items: MenuDetail[] = m[context]
console.info('context:', context, items)
for (let item of items) {
this.#menus.push({
id: context,
name: item.name,
group: item.group,
command: item.command
})
}
}
}
result() { return this.#menus }
}
@injectable
export class ExtensionManager {
private _pipeline: MessagePipeline;
// aviable extension of this
private _extensionsOfConfig: string[] = [];
private _extensions: ExtensionService[] = []; //
private _activableExtensions: Map<string, ExtensionService[]> = new Map<string, ExtensionService[]>(); // contentType, service
private _viewServices: Map<string, ExtensionService> = new Map<string, ExtensionService>();
private _installManager: ExtensionInstallManager|null = null;
constructor(pipeline: MessagePipeline) {
this._pipeline = pipeline
const dbname = config.getCurrentDB()
const resource = config.getResourceByName(dbname!)
this._extensionsOfConfig = (!resource || resource['extensions'] === undefined) ? [] : resource['extensions']
let extensionPath = getExtensionPath()
console.info('extension path:', extensionPath)
if (!fs.existsSync(extensionPath)) return
let exts = fs.readdirSync(extensionPath)
// remove files
for (let idx = exts.length - 1; idx >= 0; --idx) {
// console.info(exts[idx])
if (fs.statSync(extensionPath + '/' + exts[idx]).isDirectory() && this._isExtension(exts[idx])) continue
exts.splice(idx, 1)
}
// console.info('-------', exts)
this._initServices(extensionPath, exts, pipeline)
this._buildGraph()
// console.info('graph:', this._actives)
// npm extension
this._initExternalExtension()
this._initFrontEndEvent(pipeline)
// this._installRouter()
}
private _isExtension(name: string) {
if (name === 'node_modules' || name === '.DS_Store') return false
return true
}
private _initServices(root: string, extensionsName: string[], pipeline: MessagePipeline) {
if (this._extensionsOfConfig.length === 0) {
this._initRestService(root, extensionsName, pipeline)
} else {
let visited = {}
for (let name of this._extensionsOfConfig) {
if (this._initService(root, name, pipeline)) {
visited[name] = name
}
}
// clean service that is not in the config
for (let idx = this._extensions.length; idx >= 0; ++idx) {
let name = this._extensions[idx].name
console.info('key', name)
if (visited[name] === undefined) {
this._extensions.splice(idx)
}
}
}
}
private _initRestService(root: string, extensionsName: string[], pipeline: MessagePipeline) {
for (let name of extensionsName) {
this._initService(root, name, pipeline)
}
}
/**
* return true if create new service, else return false
*/
private _initService(root: string, extensionName: string, pipeline: MessagePipeline): boolean {
let service = this._getService(extensionName)
try {
if (!service) {
const packPath = root + '/' + extensionName
service = new ExtensionService(packPath, pipeline)
this._extensions.push(service)
console.info('extension name:', extensionName)
return true
}
} catch (err) {
console.error(`init extension ${extensionName} fail: ${err}`)
}
return false
}
private _buildGraph() {
this._activableExtensions.clear()
console.info('service:', this._extensions)
let extServs: ExtensionService[] = this._extensions
console.info('service:', extServs)
// build dependent service
for (let idx = 0, len = extServs.length; idx < len; ++idx) {
let service = extServs[idx]
if (!service.dependency) continue
for (let pos = 0; pos < len; ++pos) {
if (service.dependency === extServs[pos].name) {
extServs[pos].addDependency(service)
break
}
}
}
// check if loop circle exist
// build empty dependent service
for (let idx = extServs.length - 1; idx >= 0; --idx) {
let service = extServs[idx]
console.info('service:', service)
if (!service.dependency) {
this._initContentTypeExtension(service)
this._initViewExtension(service)
this._initStorageExtension(service)
}
}
}
private _getService(name: string) {
for (let service of this._extensions) {
if (service.name === name) return service
}
return null
}
private _initFrontEndEvent(pipeline: MessagePipeline) {
pipeline.regist(IPCNormalMessage.INSTALL_EXTENSION, this.install, this)
pipeline.regist(IPCNormalMessage.UNINSTALL_EXTENSION, this.uninstall, this)
pipeline.regist(IPCNormalMessage.UPDATE_EXTENSION, this.update, this)
pipeline.regist(IPCNormalMessage.LIST_EXTENSION, this.installedList, this)
pipeline.regist(IPCNormalMessage.GET_OVERVIEW_MENUS, this.replyMenus, this)
pipeline.regist(IPCNormalMessage.POST_COMMAND, this.onRecieveCommand, this)
}
private _initInstaller(extensionPath: string) {
if (this._installManager === null) {
this._installManager = new ExtensionInstallManager(extensionPath)
}
}
_initExternalExtension() {
const extPath = getExtensionPath()
const extConfig = extPath + '/package.json'
if (isFileExist(extConfig)) {
const pkg = fs.readFileSync(extConfig)
const exts = pkg['dependencies']
console.info('external extension:', exts)
// for (let ext of exts) {
// }
}
}
install(msgid: number, extinfo: any) {
const extPath = getExtensionPath()
this._initInstaller(extPath)
const result = this._installManager!.install(extinfo.name, extinfo.version)
if (result) {
// load extension
const root = getExtensionPath()
this._initService(root, extinfo.name, this._pipeline)
}
return {type: IPCRendererResponse.install, data: result}
}
uninstall(msgid: number, extname: string) {
const extPath = getExtensionPath()
this._initInstaller(extPath)
const result = this._installManager!.uninstall(extname)
return {type: IPCRendererResponse.uninstall, data: result}
}
update(msgid: number, extname: string) {
const extPath = getExtensionPath()
this._initInstaller(extPath)
this._installManager!.update(extname)
// let extPackPath = this._extensionPath + '/' + extname + '/package.json'
// if (!isFileExist(extPackPath)) return
}
installedList(msgid: number): any {
const extPath = getExtensionPath()
this._initInstaller(extPath)
const list = this._installManager!.installList()
return {type: IPCRendererResponse.getExtensions, data: list}
}
enable(msgid: number, extname: string) {
}
disable(msgid: number, extname: string) {}
accessMenu(menuAccessor: ExtensionAccessor) {
this._extensions.forEach((service: ExtensionService) => {
menuAccessor.visit(service)
})
const menus = menuAccessor.result()
return {type: IPCRendererResponse.getOverviewMenus, data: menus}
}
replyMenus(msgid: number, context: string|undefined) {
if (context) {
let menuAccessor: ExtensionMenuAccessor = new ExtensionMenuAccessor(context);
return this.accessMenu(menuAccessor)
}
let menuAccessor: ExtensionAllMenuAccessor = new ExtensionAllMenuAccessor()
return this.accessMenu(menuAccessor)
}
replyAllCommand(msgid: number) {
let cmdAccessor: ExtensionCommandAccessor = new ExtensionCommandAccessor(config.defaultView)
this._extensions.forEach((service: ExtensionService) => {
cmdAccessor.visit(service)
})
return {type: IPCRendererResponse.getActiveCmd, data: Array.from(cmdAccessor.result())}
}
onRecieveCommand(msgid: number, data: any) {
const command = data.command
const target = data.target
const args = data.args
this.onExecuteCommand(target, command, args)
}
private _initContentTypeExtension(service: ExtensionService) {
let activeType = service.activeType()
if (!activeType) return
for (let active of activeType) {
active = active.toLowerCase()
let events = this._activableExtensions.get(active)
if (!events) {
events = []
}
events.push(service)
this._activableExtensions.set(active, events)
}
}
private _initViewExtension(service: ExtensionService) {
let activeType = service.viewType()
if (!activeType) return
this._viewServices.set(service.name, service)
}
private _initStorageExtension(service: ExtensionService) { }
// enable resource's extensions
switchResourceDB(dbname: string) {
const resource = config.getResourceByName(dbname)
if (!resource) {}
// this._extensionsOfConfig = resource['extensions']
}
getExtensionsByType(extensionType: ExtensionActiveType): ExtensionService[] {
let extensions: ExtensionService[] = []
for (let idx = 0, len = this._extensions.length; idx < len; ++idx) {
const extension = this._extensions[idx]
if (extension.hasType(extensionType)) {
extensions.push(extension)
}
}
return extensions
}
async read(uri: ResourcePath): Promise<Result<Resource, string>> {
const f = path.parse(uri.local())
const extname = f.ext.substr(1).toLowerCase()
const extensions = this._activableExtensions.get(extname)
if (!extensions || extensions.length === 0) {
const msg = `No extensions can read ${extname} file`
showErrorInfo({msg: msg})
return Result.failure(msg)
}
let resource: Resource = APIFactory.createResource(this._pipeline);
resource.filename = f.base
resource.path = uri.local()
if (uri.remote()) {
resource.remote = uri.remote()
}
resource.filetype = extname
resource.putProperty({ name: 'type', value: extname, type: PropertyType.String, query: true, store: true })
resource.putProperty({ name: 'filename', value: f.base, type: PropertyType.String, query: true, store: true })
resource.putProperty({ name: 'path', value: uri.local(), type: PropertyType.String, query: false, store: true })
for (const extension of extensions) {
await extension.run('read', uri.local(), resource)
// this._pipeline.post(ReplyType.WORKER_UPDATE_RESOURCES, [resource.toJson()])
}
console.info('add files:', resource)
const accessor = new StorageAccessor()
const store = resource.toJson(accessor)
CivetDatabase.addFiles([store])
CivetDatabase.addMeta([resource.id], { name: 'thumbnail', value: resource.getPropertyValue('thumbnail'), type: 'bin' })
CivetDatabase.addMeta([resource.id], { name: 'color', value: resource.getPropertyValue('color'), type: 'color', query: true })
return Result.success(resource)
}
async onExecuteCommand(id: string, command: string, ...args: any) {
console.info(`Execute command ${command} on ${id}, params is ${args}`)
const extensions = this._activableExtensions[id]
if (!extensions || extensions.length === 0) {
const msg = `No extensions can read ${id} file`
showErrorInfo({msg: msg})
return Result.failure(msg)
}
const [kind, cmd] = command.split(':')
if (kind === 'ext') {
for (const extension of extensions) {
await extension.run(cmd, args)
}
} else {
console.error('unknow command', command)
}
return Result.success(true)
}
} | the_stack |
import * as fs from 'fs';
import { flags, FlagsConfig, SfdxCommand } from '@salesforce/command';
import { AuthInfo, Connection, Logger } from '@salesforce/core';
import { OutputFlags } from '@oclif/parser';
import * as ConfigApi from '../../../../lib/core/configApi';
import consts = require('../../../../lib/core/constants');
import pkgUtils = require('../../../../lib/package/packageUtils');
// Import i18n messages
import Messages = require('../../../../lib/messages');
const messages = Messages();
export class PackageVersionDisplayAncestryCommand extends SfdxCommand {
public static readonly description = messages.getMessage('cliDescription', [], 'package_displayancestry');
public static readonly longDescription = messages.getMessage('cliDescriptionLong', [], 'package_displayancestry');
public static readonly help = messages.getMessage('help', [], 'package_displayancestry');
public static readonly showProgress = false;
public static readonly varargs = false;
public static readonly orgType = consts.DEFAULT_DEV_HUB_USERNAME;
public static readonly requiresDevhubUsername = true;
// The first chunk of the query is what makes them unique, and the unit tests rely on these, so making them const
// and public will allow for normalization
public static readonly SELECT_ALL_ROOTS = 'SELECT SubscriberPackageVersionId FROM Package2Version';
public static readonly SELECT_ROOT_INFO =
'SELECT MajorVersion, MinorVersion, PatchVersion, BuildNumber FROM Package2Version';
public static readonly SELECT_CHILD_INFO =
'SELECT SubscriberPackageVersionId, MajorVersion, MinorVersion, PatchVersion, BuildNumber FROM Package2Version';
public static readonly SELECT_PARENT_INFO =
'SELECT AncestorId, MajorVersion, MinorVersion, PatchVersion, BuildNumber FROM Package2Version';
public static readonly SELECT_PACKAGE_CONTAINER_OPTIONS = 'SELECT ContainerOptions FROM Package2';
public static readonly SELECT_PACKAGE_VERSION_CONTAINER_OPTIONS =
'SELECT Package2ContainerOptions FROM SubscriberPackageVersion';
// Add this to query calls to only show released package versions in the output
public releasedOnlyFilter = ' AND IsReleased = true';
// Parse flags
public static readonly flagsConfig: FlagsConfig = {
// --json is configured automatically
package: flags.string({
char: 'p',
description: messages.getMessage('package', [], 'package_displayancestry'),
longDescription: messages.getMessage('packageLong', [], 'package_displayancestry'),
required: true,
}),
dotcode: flags.boolean({
description: messages.getMessage('dotcode', [], 'package_displayancestry'),
longDescription: messages.getMessage('dotcodeLong', [], 'package_displayancestry'),
}),
verbose: flags.builtin({
description: messages.getMessage('verbose', [], 'package_displayancestry'),
longDescription: messages.getMessage('verboseLong', [], 'package_displayancestry'),
}),
};
public async run(): Promise<unknown> {
const org = this.org || this.hubOrg;
const username: string = org.getUsername();
return await this._findAncestry(username, this.flags);
}
/**
* Finds the ancestry of the given package.
* <p>This was separated out from the run() method so that unit testing could actually be done. This is admittedly a bit of a hack, but I think every other command does it too?
* // TODO: Maybe some CLI whiz could make this not be needed
* </p>
*
* @param username - username of the org
* @param flags - the flags passed in
* @private
*/
// eslint-disable-next-line @typescript-eslint/no-shadow
protected async _findAncestry(username: string, flags: OutputFlags<any>) {
this.logger = await Logger.child(this.constructor.name);
this.logger.debug('Ancestry started with args %s', flags);
this.flags = flags; // Needed incase we're running from a unit test.
const connection = await Connection.create({
authInfo: await AuthInfo.create({ username }),
});
// Connection.create() defaults to the latest API version, but the user can override it with this flag.
if (flags.apiversion != undefined) {
connection.setApiVersion(flags.apiversion);
}
let dotcodeOutput = 'strict graph G {\n';
let unicodeOutput = '';
const forest: TreeNode[] = [];
const packageId: string = flags.package;
const roots: string[] = [];
// Get the roots based on what packageId is.
switch (packageId.substr(0, 3)) {
// If this an 0Ho, we need to get all the roots of this package
case '0Ho':
// Validate, and then fetch
try {
pkgUtils.validateId(pkgUtils.BY_LABEL.PACKAGE_ID, packageId);
} catch (err) {
throw new Error(messages.getMessage('invalidId', packageId, 'package_displayancestry'));
}
// Check to see if the package is an unlocked package
// if so, throw and error since ancestry only applies to managed packages
const query =
PackageVersionDisplayAncestryCommand.SELECT_PACKAGE_CONTAINER_OPTIONS + ` WHERE Id = '${packageId}'`;
const packageTypeResults: Array<{
ContainerOptions?: string;
}> = await this.executeQuery(connection, query);
if (packageTypeResults && packageTypeResults.length === 0) {
throw new Error(messages.getMessage('invalidId', packageId, 'package_displayancestry'));
} else if (
packageTypeResults &&
packageTypeResults.length === 1 &&
packageTypeResults[0]['ContainerOptions'] !== 'Managed'
) {
throw new Error(messages.getMessage('unlockedPackageError', [], 'package_displayancestry'));
}
const normalQuery =
PackageVersionDisplayAncestryCommand.SELECT_ALL_ROOTS +
` WHERE AncestorId = NULL AND Package2Id = '${packageId}' ${this.releasedOnlyFilter}`;
const results: Array<{
SubscriberPackageVersionId?: string;
}> = await this.executeQuery(connection, normalQuery);
// The package exists, but there are no versions for the provided package
if (results.length == 0) {
throw new Error(messages.getMessage('noVersionsError', [], 'package_displayancestry'));
}
results.forEach((row) => roots.push(row.SubscriberPackageVersionId));
break;
// If this is an 04t, we were already given our root id, and we also want to go up
case '04t':
// Validate id
try {
pkgUtils.validateId(pkgUtils.BY_LABEL.SUBSCRIBER_PACKAGE_VERSION_ID, packageId);
} catch (err) {
throw new Error(messages.getMessage('invalidId', packageId, 'package_displayancestry'));
}
// Check to see if the package version is part of an unlocked package
// if so, throw and error since ancestry only applies to managed packages
const versionQuery =
PackageVersionDisplayAncestryCommand.SELECT_PACKAGE_VERSION_CONTAINER_OPTIONS + ` WHERE Id = '${packageId}'`;
const packageVersionTypeResults: Array<{
ContainerOptions?: string;
}> = await this.executeQuery(connection, versionQuery);
if (
packageVersionTypeResults &&
packageVersionTypeResults.length === 1 &&
packageVersionTypeResults[0]['Package2ContainerOptions'] !== 'Managed'
) {
throw new Error(messages.getMessage('unlockedPackageError', [], 'package_displayancestry'));
}
// since this is a package version, we don't want to filter on only released package versions
this.releasedOnlyFilter = '';
roots.push(packageId);
unicodeOutput += (await this.ancestorsFromLeaf(flags.package, connection)) + '\n\n';
break;
// Else, this is likely an alias. So attempt to find the package information from the alias.
default:
let id;
const workspaceConfigFilename = new ConfigApi.Config().getWorkspaceConfigFilename();
try {
const parseConfigFile = JSON.parse(fs.readFileSync(workspaceConfigFilename, 'utf8'));
id = parseConfigFile.packageAliases[packageId];
} catch (err) {
throw new Error(messages.getMessage('parseError', [], 'package_displayancestry'));
}
if (id === undefined) {
throw new Error(messages.getMessage('invalidAlias', packageId, 'package_displayancestry'));
}
this.debug(`Matched ${packageId} to ${id}`);
// If we have the alias, re-run this function with the new ID, so that it can hit the two cases above
flags.package = id;
return this._findAncestry(username, flags);
}
// For every root node, build the tree below it.
for (const rootId of roots) {
const { root, dotOutput } = await this.exploreTreeFromRoot(connection, rootId);
forest.push(root);
dotcodeOutput += dotOutput;
}
dotcodeOutput += '}\n';
// Determine proper output based on flags
if (!flags.json) {
if (flags.dotcode) {
this.ux.log(dotcodeOutput);
return dotcodeOutput;
} else {
unicodeOutput += this.createUnicodeTreeOutput(forest);
this.ux.log(unicodeOutput);
return unicodeOutput;
}
} else {
if (flags.dotcode) {
// if they ask for *both* dotcode *and* json, give them the compiled string.
return dotcodeOutput;
} else {
return forest;
}
}
}
/**
* Builds the bottom-up view from a leaf.
*
* @param nodeId - the 04t of this node
* @param connection - the connection object
*/
private async ancestorsFromLeaf(nodeId: string, connection: Connection): Promise<string> {
let output = '';
// Start with the node, and shoot up
while (nodeId != null) {
const query = `${PackageVersionDisplayAncestryCommand.SELECT_PARENT_INFO} WHERE SubscriberPackageVersionId = '${nodeId}' ${this.releasedOnlyFilter}`;
const results: Array<{
MajorVersion?: string;
MinorVersion?: string;
PatchVersion?: string;
AncestorId?: string;
BuildNumber?: string;
}> = await this.executeQuery(connection, query);
if (results.length == 0) {
throw new Error(messages.getMessage('versionNotFound', nodeId, 'package_displayancestry'));
}
// @ts-ignore - ignoring this error, since results is guaranteed at runtime to have Major/Minor/etc, but TS doesn't know this at compile time.
const node = new TreeNode({ ...results[0], depthCounter: 0, SubscriberPackageVersionId: nodeId });
output += `${PackageVersionDisplayAncestryCommand.buildVersionOutput(node)} -> `;
nodeId = results[0].AncestorId;
}
// remove the last " -> " from the output string
output = output.substr(0, output.length - 4);
output += ' (root)';
return output;
}
/**
* Makes this tree from starting root this is so that we can be given a package Id and then create the forest of versions
*
* @param connection
* @param rootId the subscriber package version id for this root version.
*/
private async exploreTreeFromRoot(connection, rootId: string): Promise<{ root: TreeNode; dotOutput: string }> {
// Before we do anything, we need *all* the package information for this node, and they just gave us the ID
const query =
PackageVersionDisplayAncestryCommand.SELECT_ROOT_INFO +
` WHERE SubscriberPackageVersionId = '${rootId}' ${this.releasedOnlyFilter}`;
const results: Array<{
MajorVersion?: string;
MinorVersion?: string;
PatchVersion?: string;
BuildNumber?: string;
}> = await this.executeQuery(connection, query);
const rootInfo = new PackageInformation(
rootId,
results[0].MajorVersion,
results[0].MinorVersion,
results[0].PatchVersion,
results[0].BuildNumber
);
// Setup our BFS
const visitedSet = new Set<string>(); // If this is *always* a tree, not needed. But if there's somehow a cycle (a dev screwed something up, maybe?), this will prevent an infinite loop.
// eslint-disable-next-line no-array-constructor
const dfsStack = new Array<TreeNode>();
const root = new TreeNode(rootInfo);
dfsStack.push(root);
// Traverse!
let dotOutput = PackageVersionDisplayAncestryCommand.buildDotNode(root);
while (dfsStack.length > 0) {
const currentNode = dfsStack.pop(); // DFS
// Skip already visited elements
if (visitedSet.has(currentNode.data.SubscriberPackageVersionId)) {
continue;
}
visitedSet.add(currentNode.data.SubscriberPackageVersionId);
// Find all children, ordered from smallest -> largest
// eslint-disable-next-line @typescript-eslint/no-shadow
const query =
PackageVersionDisplayAncestryCommand.SELECT_CHILD_INFO +
` WHERE AncestorId = '${currentNode.data.SubscriberPackageVersionId}' ${this.releasedOnlyFilter}
ORDER BY MajorVersion ASC, MinorVersion ASC, PatchVersion ASC`;
// eslint-disable-next-line @typescript-eslint/no-shadow
const results: Array<{
SubscriberPackageVersionId?: string;
MajorVersion?: string;
MinorVersion?: string;
PatchVersion?: string;
BuildNumber?: string;
}> = await this.executeQuery(connection, query);
// We want to print in-order, but add to our stack in reverse-order so that we both print *and* visit nodes
// left -> right, as the dfaStack will visit right -> left if we don't do this.
const reversalStack: TreeNode[] = [];
// eslint-disable-next-line no-loop-func
results.forEach((row) => {
const childPackageInfo = new PackageInformation(
row.SubscriberPackageVersionId,
row.MajorVersion,
row.MinorVersion,
row.PatchVersion,
row.BuildNumber,
currentNode.data.depthCounter + 1
);
const childNode = new TreeNode(childPackageInfo);
currentNode.addChild(childNode);
reversalStack.push(childNode);
dotOutput += PackageVersionDisplayAncestryCommand.buildDotNode(childNode);
dotOutput += PackageVersionDisplayAncestryCommand.buildDotEdge(currentNode, childNode);
});
// Important to reverse, so that we visit the children left -> right, not right -> left.
reversalStack.reverse().forEach((child) => dfsStack.push(child));
}
return { root, dotOutput };
}
/**
* Creates the fancy NPM-LS unicode tree output
* Idea from: https://github.com/substack/node-archy
*
* @param forest
*/
private createUnicodeTreeOutput(forest: TreeNode[]): string {
let result = '';
// DFS from each root
for (const root of forest) {
result += this.unicodeOutputTraversal(root, null, '');
}
return result;
}
/**
* Builds the unicode output of this tree.
* <p>
* Root is handled differently, to make it look better / stand out as the root.
* This complicates the code flow somewhat.
* </p>
*
* @param node - current node
* @param parent - the parent of the current node
* @param prefix - the current prefix, so that we 'indent' far enough
*/
private unicodeOutputTraversal(node: TreeNode, parent: TreeNode, prefix: string): string {
let newPrefix = prefix;
let result = '';
// Root is special, just a line with no up-arrow part.
if (parent === null) {
newPrefix = '─';
} else {
// If we're the last child, use └ instead of ├
if (parent.children.indexOf(node) == parent.children.length - 1) {
newPrefix += '└─';
} else {
newPrefix += '├─';
}
}
// If we have children, add a ┬, else it's just a ─
if (node.children.length > 0) {
newPrefix += '┬ ';
} else {
newPrefix += '─ ';
}
// This line is whatever the prefix is, followed by the number
result += newPrefix + `${PackageVersionDisplayAncestryCommand.buildVersionOutput(node)}`;
// Add 04t to output if verbose mode
if (this.flags.verbose) {
result += ` (${node.data.SubscriberPackageVersionId})`;
}
result += '\n';
// If we have children, indent a level and go in
if (node.children.length != 0) {
// Root is special (a single space)
if (parent === null) {
prefix += ' ';
}
// if we're the last child, no vertical lines, just spaces
else if (parent.children[parent.children.length - 1] === node) {
prefix += ' ';
}
// lastly is everyone else (the majority of the cases).
else {
prefix += '│ ';
}
for (const child of node.children) {
result += this.unicodeOutputTraversal(child, node, prefix);
}
}
return result;
}
/**
* Builds a node line in DOT, of the form nodeID [label="MAJOR.MINOR.PATCH"]
*
* @param currentNode
*/
private static buildDotNode(currentNode: TreeNode): string {
return `\t node${
currentNode.data.SubscriberPackageVersionId
} [label="${PackageVersionDisplayAncestryCommand.buildVersionOutput(currentNode)}"]\n`;
}
/**
* Builds an edge line in DOT, of the form fromNode -- toNode
*
* @param fromNode
* @param toNode
*/
private static buildDotEdge(fromNode: TreeNode, toNode: TreeNode): string {
return `\t node${fromNode.data.SubscriberPackageVersionId} -- node${toNode.data.SubscriberPackageVersionId}\n`;
}
/**
* Runs a single query, and returns a promise with the results
*
* @param connection
* @param query
*/
private executeQuery(connection: Connection, query: string): Promise<Array<{}>> {
return connection.tooling
.autoFetchQuery(query)
.then((queryResult) => {
const records: Array<{ attributes?: {} }> = queryResult.records;
const results: Array<{}> = []; // Array of objects.
this.logger.debug('Query results: ');
this.logger.debug(records);
// Halt here if we have nothing to return
if (!records || records.length <= 0) {
return results;
}
records.forEach((record) => {
// This seems like a hack, but TypeScript is cool so we use it. Since we (usually) want
// almost *everything* from this record, rather than specifying everything we *do* want,
// instead specify only the things we do *NOT* want, and use `propertiesWeWant`
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { attributes, ...propertiesWeWant } = record;
results.push(propertiesWeWant);
});
this.logger.debug('Parsed results: ');
this.logger.debug(results);
return results;
})
.catch(() => {
throw new Error(messages.getMessage('invalidId', '', 'package_displayancestry'));
});
}
/**
* Building {Major}.{Minor}.{Patch}.{BuildNumber} is done in many places, so centralize.
*
* @param node
*/
private static buildVersionOutput(node: TreeNode): string {
return `${node.data.MajorVersion}.${node.data.MinorVersion}.${node.data.PatchVersion}.${node.data.BuildNumber}`;
}
}
/**
* A treenode used to create the package version history for the JSON output.
*/
export class TreeNode {
data: PackageInformation;
children: TreeNode[];
constructor(data: PackageInformation) {
this.data = data;
this.children = [];
}
/**
* Adds a child to this node
*
* @param child
*/
addChild(child: TreeNode): void {
this.children.push(child);
}
}
/**
* This is the 'data' part of TreeNode, a collection of useful version information.
*/
class PackageInformation {
SubscriberPackageVersionId: string;
MajorVersion: string;
MinorVersion: string;
PatchVersion: string;
BuildNumber: string;
depthCounter: number;
constructor(
SubscriberPackageVersionId: string,
MajorVersion: string,
MinorVersion: string,
PatchVersion: string,
BuildNumber: string,
depthCounter = 0
) {
this.SubscriberPackageVersionId = SubscriberPackageVersionId;
this.MajorVersion = MajorVersion;
this.MinorVersion = MinorVersion;
this.PatchVersion = PatchVersion;
this.BuildNumber = BuildNumber;
this.depthCounter = depthCounter;
}
} | the_stack |
import { ChartAxisData } from '../../..';
import { select } from 'd3-selection';
import { scaleBand, scaleLinear, scaleTime } from 'd3-scale';
import { format } from 'd3-format';
import { axisTop } from 'd3-axis';
import { curveLinear } from 'd3-shape';
import { chartAxis } from '../../../dist/d2b.cjs.js';
import { annotationBadge } from 'd3-svg-annotation';
const axis = chartAxis();
// The axis chart data creation type checked with the ChartAxisData interface.
const datum: ChartAxisData = {
// sets: (required) [{generators: array, graphs: array}]
// Array of graph sets to be rendered.
sets: [
{
// This set is an example of stacked bars:
// yType: (optional) either 'y' or 'y2'
// The y axis in which the graphs will be associated with. 'y' is the left side vertical axis, and 'y2' is the right side virtical axis.
// default: 'y'
yType: 'y2',
// xType: (optional) either 'x' or 'x2'
// The x axis in which the graphs will be associated with. 'x' is the left side vertical axis, and 'x2' is the right side virtical axis.
// default: 'x'
xType: 'x2',
// generators: (required) array
// The svg generators use to render the graphs.
generators: [
// Generators can either be in the form of a preconfigured d2b svg generator:
// (e.g. one of svgBar, svgLine, svgArea, svgScatter, svgBubblePack, svgBoxPlot)
// d2b.svgBar().stackBy(true),
// Or the generators can be described by an object:
{
// type: (type OR types required) one of 'line', 'bar', 'area', 'scatter', 'boxPlot', 'bubblePack'
// The generator type.
type: 'scatter',
// types: (type OR types required) array of strings with the following possible options 'line', 'bar', 'area', 'scatter', 'boxPlot', 'bubblePack'
// The generator types.
// types: ['scatter', 'line', 'area'],
// stack: (optional) boolean
// Only used for bar, area, line, and scatter generators.
// default: null (if null will defer to the set's stack property)
// stack: true,
// padding: (optional) number between 0 and 1
// Only used for bar generator. Describes the padding "between" bar groups.
// default: 0.5
padding: 0.2,
// groupPadding: (optional) number between 0 and 0.5
// Only used for bar generator. Describes the padding "within" bar groups.
// default: 0
groupPadding: 0.05,
// curve: curveLinear,
// stackOffset: (optional) one of d3.stackOffsetExpand, d3.stackOffsetDiverging, d3.stackOffsetNone, d3.stackOffsetSilhouette, d3.stackOffsetWiggle
// Only used for area, line, and scatter generators.
// default: d3.stackOffsetNone
// stackOffset: d3.stackOffsetExpand,
// stackOrder: (optional) one of d3.stackOrderAppearance, d3.stackOrderAscending, d3.stackOrderDescending, d3.stackOrderInsideOut, d3.stackOrderNone, d3.stackOrderReverse
// Only used for area, line, and scatter generators.
// default: d3.stackOrderNone
// stackOrder: d3.stackOrderAscending,
// orient: (optional) one of 'horizontal' or 'vertical'
// Only used for bar and boxPlot generators.
// default: 'vertical'
// orient: 'horizontal',
// curve: (optional) one of d3 curves: https://github.com/d3/d3-shape#curves
// Only used for area and line generators.
// default: d3.curveLinear
// curve: d3.curveBasis,
// align: (optional) 'y0' or 'y1'
// Only used for scatter and line generators. If stacking is enabled, this specifies if the line or points will be aligned at the y0 or y1 position of the data stack.
// default: 'y1'
// align: 'y0',
// size: (optional) number
// Only used for scatter and bubblePack generators. Specifies the area size of the points. In regards to the bubblePack generator, the size will be a multiplier of the computed bubble size.
// default: 25 (scatter) 100 (bubblePack)
// size: (d) => d.y * 20,
// tendancy: (optional) One of d2b.mean, d2b.median, d2b.mode, d2b.midpoint
// Only used for bubblePack generator. Specifies how the size of the parent bubbles are computed relative to their leaf nodes.
// default: d2b.mean
// tendancy: d2b.median,
// valueFormat: (optional) function (d)
// Only used for boxPlot generator. Specifies the box plot values (maximum, upperQuartile, median, lowerQuartile, minimum) should be formated.
// default: d3.format(',')
// valueFormat: d3.format('%'),
// centered: (optional) boolean
// Only used for bar generator. Forces bars to be centered instead of being aligned according to their group siblings.
// default: false
// centered: true,
// width: (optional) number
// Only used for boxPlot generator. Sets the box plot pixel width.
// default: 20
// width: 30,
// symbol: (optional) One of https://github.com/d3/d3-shape#symbols or https://docs.d2bjs.org/shape/symbols.html
// Only used for scatter and bubblePack generators. Defines the point symbol type.
// default: d3.symbolCircle
// symbol: d3.symbolSquare,
}
],
// graphs: (required) [{label: string, ...}]
// Array of graphs to be rendered with the set generators.
graphs: [
{
// label: (required) string
// The graph label.
label: 'bar 1',
// tooltip: (optional) null, string, or function (d, graph)
// The graph value tooltip accessor (returns html). If undefined the tooltip will fallback to the charts tooltip.row config. If null tooltips will be disabled for this graph.
// default: undefined
// tooltip: (d, graph) => `<b>${graph.label}</b>: ${d.y}`,
// hidden: (optional) boolean
// Initially hides this graph. This value will be modified internally when interacting with the chart legend.
// default: false
// hidden: true,
// color: (optional) string
// The graph color. If undefined, the color will fall back to the chart's graphColor accessor.
// default: undefined
color: 'red',
stack: 1,
// symbol: (optional) One of https://github.com/d3/d3-shape#symbols or https://docs.d2bjs.org/shape/symbols.html
// The graph symbol. If undefined, the symbol will fall back to the generator's symbol.
// default: undefined
// symbol: d3.symbolStar,
// group: (required) string
// The graph group, should match the group's label. This is useful to group graphs together on the legend
// group: 'Bar Group',
// values: (required) array
// The graph values.
values: [
{x: 1, y: 25},
{x: 2, y: 38},
{x: 3, y: 24},
{x: 4, y: 60},
{x: 5, y: 22}
]
},
{
label: 'bar 2',
stack: 1,
values: [
{x: 3, y: 45},
{x: 5, y: 31},
]
},
{
label: 'bar 3',
values: [
{x: 2, y: 25},
{x: 3, y: 15},
{x: 4, y: 35},
{x: 5, y: 25},
{x: 6, y: 18},
]
}
]
},
{
// area graphs
generators: [{
types: ['area', 'line', 'scatter']
}],
graphs: [
{
label: 'area 1',
// hidden: true,
values: [
{x: 1, y: 25,
annotations: [{
// type: d3.annotationBadge,
subject: {
text: 'A'
}
}]
},
{x: 2, y: 38},
{x: 3, y: 24},
{x: 4, y: 60},
{x: 5, y: 22}
]
},
{
label: 'area 2',
// hidden: true,
values: [
{x: 3, y: 45},
{x: 5, y: 31},
]
}
]
},
{
// box plot graphs
generators: [{
types: ['boxPlot']
}],
graphs: [
{
label: 'box plot 1',
group: 'Box Group',
values: [
// Example value format for boxPlot generator
{
// x: (required for vertical boxPlots) number (or string for band scales)
// x-value
x: 1,
// y: (required for horizontal boxPlots) number (or string for band scales)
// y-value
y: 1,
// maximum: (required) number
// maximum-value
maximum: 10,
// minimum: (required) number
// minimum-value
minimum: 1,
// upperQuartile: (required) number
// upper-quartile-value
upperQuartile: 7.5,
// lowerQuartile: (required) number
// lower-quartile-value
lowerQuartile: 2.8,
// median: (required) number
// median-value
median: 5.4,
// outliers: (required) [number]
// Array of outliers-values
outliers: [0.5, 12, 13.3],
// width: (optional) number
// The pixel width for this value's box-plot. If undefined will fall back to the boxPlot generator's width attribute.
// default: undefined
width: 50
},
{x: 2, maximum: 12, minimum: 3, upperQuartile: 9, lowerQuartile: 5.8, median: 7},
{x: 3, maximum: 15, minimum: 4.5, upperQuartile: 12.8, lowerQuartile: 6.2, median: 7.3}
]
},
{
label: 'box-plot 2',
group: 'Box Group',
values: [
{x: 4, maximum: 6, minimum: 0, upperQuartile: 5, lowerQuartile: 1.4, median: 3.8},
{x: 5, maximum: 8.2, minimum: 1.2, upperQuartile: 7, lowerQuartile: 2.8, median: 5.5, outliers: [1, 11.1, 14.5]},
{x: 6, maximum: 12.8, minimum: 4.2, upperQuartile: 11, lowerQuartile: 4.8, median: 6.4}
]
}
]
},
{
// bubble pack graphs
generators: [{
type: 'bubblePack'
}],
graphs: [
{
label: 'bubble pack 1',
values: [
// Example value format for bubblePack generator
{
size:100,
// label: (required) string
// Unique label for this bubble.
label: 'one',
annotation: {
dy: -50,
dx: 70,
// location: 'y',
type: annotationBadge,
note: {
title: 'Important Point',
label: 'This point represents something important that happened.',
wrap: 150
},
subject: {
radius: 20,
radiusPadding: 5,
},
connector: {
end : "arrow"
}
},
// annotations:[{
// location: 'y',
// // dy: -30,
// type: annotationCalloutCircle,
// // note: {
// // title: 'Peak',
// // label: 'Here is the peak of one of the area charts'
// // },
// // connector: {
// // end: "dot"
// // },
// subject: {
// radius: 15,
// text: 'peak'
// }
// }],
// children: (required if bubble has children) array
// Children of this bubble.
children: [
{
label: 'one-one',
// size: (required if bubble is a leaf node) number
// Size of this bubble.
size: 5,
// x: (required if bubble is a leaf node) number
// x-value
x: 7,
// y: (required if bubble is a leaf node) number
// y-value
y: 25
}
]
},
{
expanded: true,
// symbol: d3.symbolDiamond,
label: 'two',
children: [
{
label: 'two-one',
size: 5,
x: 3,
y: 15
},
{
label: 'two-two',
children: [
{
label: 'two-two-one',
size: 2,
x: 6,
y: 8
},
{
label: 'two-two-two',
size: 17,
x: 8,
y: 21
}
]
}
]
}
]
}
]
}
],
// groups: (optional) [{label: string}]
// Array of graph groups.
groups: [
{
// label: (required) string
// The graph label.
label: 'Box Group',
// color: (optional) string
// The group color. If undefined, the color will fall back to the chart's groupColor accessor.
// default: undefined
color: 'purple'
}
],
// // Event hook for d2b charts. Will be fired whenever the chart is rendered either externally or internally.
// // Note: Transitions may still occur after this lifecycle hook fires.
// // updated (datum) {
// // console.log(datum) // event will be passed the chart datum
// // console.log(this) // context will be chart container DOM element
// // },
// // size: (optional) {height: number, width: number}
// // The pixel size of the chart.
// // default: width and height will size according to the container size if not provided
// size: {
// height: 400
// },
// chartPadding: (optional) number or { top: number, left: number, right: number, bottom: number }
// The inner chart padding (excluding the legend)
// default: 10
// padding: (optional) number or { top: number, left: number, right: number, bottom: number }
// The outer chart padding (including the legend)
// default: 10
// planePadding: (optional) number or { top: number, left: number, right: number, bottom: number }
// The chart's plane padding. If set to null the padding will be computed automatically based on the axis label and tick sizes.
// default: null
// planeMargin: (optional) number or { top: number, left: number, right: number, bottom: number }
// The chart's plane margin. This is useful if additional space is required for axis labels or ticks.
// default: 0
// duration: (optional) number
// The duration of internal chart transitions in miliseconds.
// default: 250
// graphColor: (optional) function (d)
// Color accessor for graphs.
// default: Colors dynamically based on the graph label
// graphColor: function (d) {
// return d3.scaleOrdinal(d3.schemeCategory20)(d.label)
// },
// groupColor: (optional) function (d)
// Color accessor for groups.
// default: Colors dynamically based on the group label
// groupColor: function (d) {
// return d3.scaleOrdinal(d3.schemeCategory20)(d.label)
// },
// legend: (optional)
// legend configuration options
// legend: {
// enabled: (optional) boolean
// Enable or disable the legend
// default: true
// orient: (optional) one of 'left', 'right', 'top', 'bottom'
// Orientation of the legend
// default: 'bottom'
// clickable: (optional) boolean
// Whether the legend will hide / show graphs on click
// default: true
// dblclickable: (optional) boolean
// Whether the legend will hide / show graphs on dblclick
// default: true
// icon: (optional) d3 symbol or font awesome character code
// Legend item icon.
// default: d3.symbolCircle
// },
tooltip: {
// trackX: false,
// trackY: false,
// title,
// row
},
x: {
scale: {
// type: scaleTime()
// type: scaleBand().domain([1, 2])
// forceBounds: {
// min: -10
// }
},
// tickFormat: format('%'),
// axis: axisTop(scaleLinear())
// wrapLength: 1
// tickFormat: () => 'This is a long tick',
wrapLength: 1,
showGrid: false,
tickSize: 20,
label: 'Test Label',
labelOrient: 'inner end',
linearPadding: [-0.5, 0.2],
tickPadding: 20,
ticks: 3,
// tickValues: [1, 2, 3]
}
// (x, y, x2, y2): {
// scale: {
// type,
// domain,
// clamp,
// nice,
// exponent,
// base,
// constant,
// forceBounds: {
// min,
// max
// }
// },
// orient,
// wrapLength,
// tickSize,
// showGrid,
// label,
// labelOrient,
// linearPadding,
// tickPadding,
// ticks,
// tickFormat,
// tickValues,
// axis
// }
};
const chart = select('.chart-axis').datum(datum);
chart.call(axis.advanced); | the_stack |
import { TypedEmitter } from "tiny-typed-emitter";
import { Logger } from "ts-log";
import { HTTPApi } from "./api";
import { CommandName, DeviceCommands, DeviceEvent, DeviceProperties, DeviceType, FloodlightMotionTriggeredDistance, GenericDeviceProperties, ParamType, PropertyName } from "./types";
import { FullDeviceResponse, ResultResponse, StreamResponse } from "./models"
import { ParameterHelper } from "./parameter";
import { DeviceEvents, PropertyValue, PropertyValues, PropertyMetadataAny, IndexedProperty, RawValues, RawValue, PropertyMetadataNumeric, PropertyMetadataBoolean } from "./interfaces";
import { CommandType, ESLAnkerBleConstant } from "../p2p/types";
import { calculateWifiSignalLevel, getAbsoluteFilePath } from "./utils";
import { convertTimestampMs } from "../push/utils";
import { eslTimestamp } from "../p2p/utils";
import { CusPushEvent, DoorbellPushEvent, LockPushEvent, IndoorPushEvent, PushMessage } from "../push";
import { isEmpty } from "../utils";
import { InvalidPropertyError, PropertyNotSupportedError } from "./error";
export abstract class Device extends TypedEmitter<DeviceEvents> {
protected api: HTTPApi;
protected rawDevice: FullDeviceResponse;
protected log: Logger;
protected eventTimeouts = new Map<DeviceEvent, NodeJS.Timeout>();
protected properties: PropertyValues = {};
private rawProperties: RawValues = {};
private ready = false;
constructor(api: HTTPApi, device: FullDeviceResponse) {
super();
this.api = api;
this.rawDevice = device;
this.log = api.getLog();
this.update(this.rawDevice);
this.ready = true;
setImmediate(() => {
this.emit("ready", this);
});
}
public getRawDevice(): FullDeviceResponse {
return this.rawDevice;
}
public update(device: FullDeviceResponse): void {
this.rawDevice = device;
const metadata = this.getPropertiesMetadata();
for (const property of Object.values(metadata)) {
if (this.rawDevice[property.key] !== undefined && typeof property.key === "string") {
let timestamp = 0;
switch (property.key) {
case "cover_path":
if (this.rawDevice.cover_time !== undefined) {
timestamp = convertTimestampMs(this.rawDevice.cover_time);
break;
}
case "main_sw_version":
if (this.rawDevice.main_sw_time !== undefined) {
timestamp = convertTimestampMs(this.rawDevice.main_sw_time);
break;
}
case "sec_sw_version":
if (this.rawDevice.sec_sw_time !== undefined) {
timestamp = convertTimestampMs(this.rawDevice.sec_sw_time);
break;
}
default:
if (this.rawDevice.update_time !== undefined) {
timestamp = convertTimestampMs(this.rawDevice.update_time);
}
break;
}
this.updateProperty(property.name, { value: this.rawDevice[property.key], timestamp: timestamp });
} else if (this.properties[property.name] === undefined && property.default !== undefined && !this.ready) {
this.updateProperty(property.name, { value: property.default, timestamp: 0 });
}
}
this.rawDevice.params.forEach(param => {
this.updateRawProperty(param.param_type, { value: param.param_value, timestamp: convertTimestampMs(param.update_time) });
});
this.log.debug("Normalized Properties", { deviceSN: this.getSerial(), properties: this.properties });
}
protected updateProperty(name: string, value: PropertyValue): boolean {
if (
(this.properties[name] !== undefined
&& (
this.properties[name].value !== value.value
&& this.properties[name].timestamp <= value.timestamp
)
)
|| this.properties[name] === undefined
) {
this.properties[name] = value;
if (!name.startsWith("hidden-")) {
if (this.ready)
this.emit("property changed", this, name, value);
}
return true;
}
return false;
}
public updateRawProperties(values: RawValues): void {
Object.keys(values).forEach(paramtype => {
const param_type = Number.parseInt(paramtype);
this.updateRawProperty(param_type, values[param_type]);
});
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected processCustomParameterChanged(metadata: PropertyMetadataAny, oldValue: PropertyValue, newValue: PropertyValue): void {
if ((metadata.key === ParamType.DETECT_MOTION_SENSITIVE || metadata.key === ParamType.DETECT_MODE) && this.isWiredDoorbell()) {
//TODO: Not perfectly solved, can in certain cases briefly trigger a double event where the last event is the correct one
const rawSensitivity = this.getRawProperty(ParamType.DETECT_MOTION_SENSITIVE);
const rawMode = this.getRawProperty(ParamType.DETECT_MODE);
if (rawSensitivity !== undefined && rawMode !== undefined) {
const sensitivity = Number.parseInt(rawSensitivity.value);
const mode = Number.parseInt(rawMode.value);
if (mode === 3 && sensitivity === 2) {
this.updateProperty(PropertyName.DeviceMotionDetectionSensitivity, { value: 1, timestamp: newValue !== undefined ? newValue.timestamp : 0 });
} else if (mode === 1 && sensitivity === 1) {
this.updateProperty(PropertyName.DeviceMotionDetectionSensitivity, { value: 2, timestamp: newValue !== undefined ? newValue.timestamp : 0 });
} else if (mode === 1 && sensitivity === 2) {
this.updateProperty(PropertyName.DeviceMotionDetectionSensitivity, { value: 3, timestamp: newValue !== undefined ? newValue.timestamp : 0 });
} else if (mode === 1 && sensitivity === 3) {
this.updateProperty(PropertyName.DeviceMotionDetectionSensitivity, { value: 4, timestamp: newValue !== undefined ? newValue.timestamp : 0 });
} else if (mode === 2 && sensitivity === 1) {
this.updateProperty(PropertyName.DeviceMotionDetectionSensitivity, { value: 5, timestamp: newValue !== undefined ? newValue.timestamp : 0 });
}
}
} else if (metadata.name === PropertyName.DeviceWifiRSSI) {
this.updateProperty(PropertyName.DeviceWifiSignalLevel, { value: calculateWifiSignalLevel(this, newValue.value as number), timestamp: newValue !== undefined ? newValue.timestamp : 0 });
}
}
public updateRawProperty(type: number, value: RawValue): boolean {
const parsedValue = ParameterHelper.readValue(type, value.value);
if (
(this.rawProperties[type] !== undefined
&& (
this.rawProperties[type].value !== parsedValue
&& this.rawProperties[type].timestamp <= value.timestamp
)
)
|| this.rawProperties[type] === undefined
) {
this.rawProperties[type] = {
value: parsedValue,
timestamp: value.timestamp
};
if (this.ready)
this.emit("raw property changed", this, type, this.rawProperties[type].value, this.rawProperties[type].timestamp);
const metadata = this.getPropertiesMetadata();
for (const property of Object.values(metadata)) {
if (property.key === type) {
try {
const oldValue = this.properties[property.name];
if (this.updateProperty(property.name, this.convertRawPropertyValue(property, this.rawProperties[type]))) {
this.processCustomParameterChanged(property, oldValue, this.properties[property.name]);
}
} catch (error) {
if (error instanceof PropertyNotSupportedError) {
this.log.debug("Property not supported error", error);
} else {
this.log.error("Property error", error);
}
}
}
}
return true;
} else if (this.rawProperties[type] !== undefined && (
this.rawProperties[type].value === parsedValue
&& this.rawProperties[type].timestamp < value.timestamp)
) {
this.rawProperties[type].timestamp = value.timestamp;
if (this.ready)
this.emit("raw property renewed", this, type, this.rawProperties[type].value, this.rawProperties[type].timestamp);
const metadata = this.getPropertiesMetadata();
for (const property of Object.values(metadata)) {
if (property.key === type && this.properties[property.name] !== undefined) {
this.properties[property.name].timestamp = value.timestamp;
if (this.ready)
this.emit("property changed", this, property.name, this.properties[property.name]);
}
}
}
return false;
}
protected convertRawPropertyValue(property: PropertyMetadataAny, value: RawValue): PropertyValue {
try {
if (property.key === ParamType.PRIVATE_MODE || property.key === ParamType.OPEN_DEVICE || property.key === CommandType.CMD_DEVS_SWITCH) {
if (this.isIndoorCamera() || this.isWiredDoorbell() || this.getDeviceType() === DeviceType.FLOODLIGHT_CAMERA_8422 || this.getDeviceType() === DeviceType.FLOODLIGHT_CAMERA_8424) {
return { value: value !== undefined ? (value.value === "true" ? true : false) : false, timestamp: value !== undefined ? value.timestamp : 0 };
}
return { value: value !== undefined ? (value.value === "0" ? true : false) : false, timestamp: value !== undefined ? value.timestamp : 0 };
} else if (property.key === CommandType.CMD_BAT_DOORBELL_SET_NOTIFICATION_MODE) {
try {
switch (property.name) {
case PropertyName.DeviceNotificationRing:
return { value: value !== undefined ? (Number.parseInt((value.value as any).notification_ring_onoff)) : 0, timestamp: value !== undefined ? value.timestamp : 0 };
case PropertyName.DeviceNotificationMotion:
return { value: value !== undefined ? (Number.parseInt((value.value as any).notification_motion_onoff)) : 0, timestamp: value !== undefined ? value.timestamp : 0 };
case PropertyName.DeviceNotificationType:
return { value: value !== undefined ? (Number.parseInt((value.value as any).notification_style)) : 1, timestamp: value !== undefined ? value.timestamp : 0 };
}
} catch (error) {
this.log.error("Convert CMD_BAT_DOORBELL_SET_NOTIFICATION_MODE Error:", { property: property, value: value, error: error });
return { value: 1, timestamp: 0 };
}
} else if (property.key === ParamType.DOORBELL_NOTIFICATION_OPEN) {
try {
switch (property.name) {
case PropertyName.DeviceNotificationRing:
return { value: value !== undefined ? (Number.parseInt((value.value as any)) === 3 || Number.parseInt((value.value as any)) === 1 ? true : false) : false, timestamp: value !== undefined ? value.timestamp : 0 };
case PropertyName.DeviceNotificationMotion:
return { value: value !== undefined ? (Number.parseInt((value.value as any)) === 3 || Number.parseInt((value.value as any)) === 2 ? true : false) : false, timestamp: value !== undefined ? value.timestamp : 0 };
}
} catch (error) {
this.log.error("Convert DOORBELL_NOTIFICATION_OPEN Error:", { property: property, value: value, error: error });
return { value: false, timestamp: 0 };
}
} else if (property.key === CommandType.CMD_SET_PIRSENSITIVITY) {
try {
if (this.getDeviceType() === DeviceType.CAMERA || this.getDeviceType() === DeviceType.CAMERA_E) {
const convertedValue = ((200 - Number.parseInt(value.value)) / 2) + 1;
return { value: convertedValue, timestamp: value.timestamp };
} else if (this.isCamera2Product()) {
let convertedValue;
switch (Number.parseInt(value.value)) {
case 192:
convertedValue = 1;
break;
case 118:
convertedValue = 2;
break;
case 72:
convertedValue = 3;
break;
case 46:
convertedValue = 4;
break;
case 30:
convertedValue = 5;
break;
case 20:
convertedValue = 6;
break;
case 14:
convertedValue = 7;
break;
default:
convertedValue = 4;
break;
}
return { value: convertedValue, timestamp: value.timestamp };
}
} catch (error) {
this.log.error("Convert CMD_SET_PIRSENSITIVITY Error:", { property: property, value: value, error: error });
return value;
}
} else if (property.type === "number") {
const numericProperty = property as PropertyMetadataNumeric;
try {
return { value: value !== undefined ? Number.parseInt(value.value) : (property.default !== undefined ? numericProperty.default : (numericProperty.min !== undefined ? numericProperty.min : 0)), timestamp: value !== undefined ? value.timestamp : 0 };
} catch (error) {
this.log.warn("PropertyMetadataNumeric Convert Error:", { property: property, value: value, error: error });
return { value: property.default !== undefined ? numericProperty.default : (numericProperty.min !== undefined ? numericProperty.min : 0), timestamp: value !== undefined ? value.timestamp : 0 };
}
} else if (property.type === "boolean") {
const booleanProperty = property as PropertyMetadataBoolean;
try {
return { value: value !== undefined ? (value.value === "1" || value.value.toLowerCase() === "true" ? true : false) : (property.default !== undefined ? booleanProperty.default : false), timestamp: value !== undefined ? value.timestamp : 0 };
} catch (error) {
this.log.warn("PropertyMetadataBoolean Convert Error:", { property: property, value: value, error: error });
return { value: property.default !== undefined ? booleanProperty.default : false, timestamp: value !== undefined ? value.timestamp : 0 };
}
}
} catch (error) {
this.log.error("Convert Error:", { property: property, value: value, error: error });
}
return value;
}
public getPropertyMetadata(name: string): PropertyMetadataAny {
const property = this.getPropertiesMetadata()[name];
if (property !== undefined)
return property;
throw new InvalidPropertyError(`Property ${name} invalid`);
}
public getPropertyValue(name: string): PropertyValue {
return this.properties[name];
}
public getRawProperty(type: number): RawValue {
return this.rawProperties[type];
}
public getRawProperties(): RawValues {
return this.rawProperties;
}
public getProperties(): PropertyValues {
const result: PropertyValues = {};
for (const property of Object.keys(this.properties)) {
if (!property.startsWith("hidden-"))
result[property] = this.properties[property];
}
return result;
}
public getPropertiesMetadata(): IndexedProperty {
const metadata = DeviceProperties[this.getDeviceType()];
if (metadata === undefined)
return GenericDeviceProperties;
return metadata;
}
public hasProperty(name: string): boolean {
return this.getPropertiesMetadata()[name] !== undefined;
}
public getCommands(): Array<CommandName> {
const commands = DeviceCommands[this.getDeviceType()];
if (commands === undefined)
return [];
return commands;
}
public hasCommand(name: CommandName): boolean {
return this.getCommands().includes(name);
}
public processPushNotification(_message: PushMessage, _eventDurationSeconds: number): void {
// Nothing to do
}
public setCustomPropertyValue(name: string, value: PropertyValue): void {
const metadata = this.getPropertyMetadata(name);
if (typeof metadata.key === "string" && metadata.key.startsWith("custom_")) {
this.updateProperty(name, value);
}
}
public destroy(): void {
this.eventTimeouts.forEach((timeout) => {
clearTimeout(timeout);
});
this.eventTimeouts.clear();
}
protected clearEventTimeout(eventType: DeviceEvent): void {
const timeout = this.eventTimeouts.get(eventType);
if (timeout !== undefined) {
clearTimeout(timeout);
this.eventTimeouts.delete(eventType);
}
}
static isCamera(type: number): boolean {
if (type == DeviceType.CAMERA ||
type == DeviceType.CAMERA2 ||
type == DeviceType.CAMERA_E ||
type == DeviceType.CAMERA2C ||
type == DeviceType.INDOOR_CAMERA ||
type == DeviceType.INDOOR_PT_CAMERA ||
type == DeviceType.FLOODLIGHT ||
type == DeviceType.DOORBELL ||
type == DeviceType.BATTERY_DOORBELL ||
type == DeviceType.BATTERY_DOORBELL_2 ||
type == DeviceType.CAMERA2C_PRO ||
type == DeviceType.CAMERA2_PRO ||
type == DeviceType.INDOOR_CAMERA_1080 ||
type == DeviceType.INDOOR_PT_CAMERA_1080 ||
type == DeviceType.SOLO_CAMERA ||
type == DeviceType.SOLO_CAMERA_PRO ||
type == DeviceType.SOLO_CAMERA_SPOTLIGHT_1080 ||
type == DeviceType.SOLO_CAMERA_SPOTLIGHT_2K ||
type == DeviceType.SOLO_CAMERA_SPOTLIGHT_SOLAR ||
type == DeviceType.INDOOR_OUTDOOR_CAMERA_1080P ||
type == DeviceType.INDOOR_OUTDOOR_CAMERA_1080P_NO_LIGHT ||
type == DeviceType.INDOOR_OUTDOOR_CAMERA_2K ||
type == DeviceType.FLOODLIGHT_CAMERA_8422 ||
type == DeviceType.FLOODLIGHT_CAMERA_8423 ||
type == DeviceType.FLOODLIGHT_CAMERA_8424)
return true;
return false;
}
static hasBattery(type: number): boolean {
if (type == DeviceType.CAMERA ||
type == DeviceType.CAMERA2 ||
type == DeviceType.CAMERA_E ||
type == DeviceType.CAMERA2C ||
type == DeviceType.BATTERY_DOORBELL ||
type == DeviceType.BATTERY_DOORBELL_2 ||
type == DeviceType.CAMERA2C_PRO ||
type == DeviceType.CAMERA2_PRO ||
type == DeviceType.SOLO_CAMERA ||
type == DeviceType.SOLO_CAMERA_PRO ||
type == DeviceType.SOLO_CAMERA_SPOTLIGHT_1080 ||
type == DeviceType.SOLO_CAMERA_SPOTLIGHT_2K ||
type == DeviceType.SOLO_CAMERA_SPOTLIGHT_SOLAR)
//TODO: Add other battery devices
return true;
return false;
}
static isStation(type: number): boolean {
if (type == DeviceType.STATION)
return true;
return false;
}
static isSensor(type: number): boolean {
if (type == DeviceType.SENSOR ||
type == DeviceType.MOTION_SENSOR)
return true;
return false;
}
static isKeyPad(type: number): boolean {
return DeviceType.KEYPAD == type;
}
static isDoorbell(type: number): boolean {
if (type == DeviceType.DOORBELL ||
type == DeviceType.BATTERY_DOORBELL ||
type == DeviceType.BATTERY_DOORBELL_2)
return true;
return false;
}
static isWiredDoorbell(type: number): boolean {
if (type == DeviceType.DOORBELL)
return true;
return false;
}
static isIndoorCamera(type: number): boolean {
if (type == DeviceType.INDOOR_CAMERA ||
type == DeviceType.INDOOR_CAMERA_1080 ||
type == DeviceType.INDOOR_PT_CAMERA ||
type == DeviceType.INDOOR_PT_CAMERA_1080 ||
type == DeviceType.INDOOR_OUTDOOR_CAMERA_1080P ||
type == DeviceType.INDOOR_OUTDOOR_CAMERA_1080P_NO_LIGHT ||
type == DeviceType.INDOOR_OUTDOOR_CAMERA_2K)
return true;
return false;
}
static isFloodLight(type: number): boolean {
if (type == DeviceType.FLOODLIGHT ||
type == DeviceType.FLOODLIGHT_CAMERA_8422 ||
type == DeviceType.FLOODLIGHT_CAMERA_8423 ||
type == DeviceType.FLOODLIGHT_CAMERA_8424)
return true;
return false;
}
static isLock(type: number): boolean {
return Device.isLockBasic(type) || Device.isLockAdvanced(type) || Device.isLockBasicNoFinger(type) || Device.isLockAdvancedNoFinger(type);
}
static isLockBasic(type: number): boolean {
return DeviceType.LOCK_BASIC == type;
}
static isLockBasicNoFinger(type: number): boolean {
return DeviceType.LOCK_BASIC_NO_FINGER == type;
}
static isLockAdvanced(type: number): boolean {
return DeviceType.LOCK_ADVANCED == type;
}
static isLockAdvancedNoFinger(type: number): boolean {
return DeviceType.LOCK_ADVANCED_NO_FINGER == type;
}
static isBatteryDoorbell(type: number): boolean {
return DeviceType.BATTERY_DOORBELL == type;
}
static isBatteryDoorbell2(type: number): boolean {
return DeviceType.BATTERY_DOORBELL_2 == type;
}
static isSoloCamera(type: number): boolean {
return DeviceType.SOLO_CAMERA == type;
}
static isSoloCameraPro(type: number): boolean {
return DeviceType.SOLO_CAMERA_PRO == type;
}
static isSoloCameraSpotlight1080(type: number): boolean {
return DeviceType.SOLO_CAMERA_SPOTLIGHT_1080 == type;
}
static isSoloCameraSpotlight2k(type: number): boolean {
return DeviceType.SOLO_CAMERA_SPOTLIGHT_2K == type;
}
static isSoloCameraSpotlightSolar(type: number): boolean {
return DeviceType.SOLO_CAMERA_SPOTLIGHT_SOLAR == type;
}
static isSoloCameras(type: number): boolean {
return Device.isSoloCamera(type) ||
Device.isSoloCameraPro(type) ||
Device.isSoloCameraSpotlight1080(type) ||
Device.isSoloCameraSpotlight2k(type) ||
Device.isSoloCameraSpotlightSolar(type);
}
static isIndoorOutdoorCamera1080p(type: number): boolean {
return DeviceType.INDOOR_OUTDOOR_CAMERA_1080P == type;
}
static isIndoorOutdoorCamera1080pNoLight(type: number): boolean {
return DeviceType.INDOOR_OUTDOOR_CAMERA_1080P_NO_LIGHT == type;
}
static isIndoorOutdoorCamera2k(type: number): boolean {
return DeviceType.INDOOR_OUTDOOR_CAMERA_2K == type;
}
static isCamera2(type: number): boolean {
//T8114
return DeviceType.CAMERA2 == type;
}
static isCamera2C(type: number): boolean {
//T8113
return DeviceType.CAMERA2C == type;
}
static isCamera2Pro(type: number): boolean {
//T8140
return DeviceType.CAMERA2_PRO == type;
}
static isCamera2CPro(type: number): boolean {
//T8142
return DeviceType.CAMERA2C_PRO == type;
}
static isCamera2Product(type: number): boolean {
return Device.isCamera2(type) || Device.isCamera2C(type) || Device.isCamera2Pro(type) || Device.isCamera2CPro(type);
}
static isEntrySensor(type: number): boolean {
//T8900
return DeviceType.SENSOR == type;
}
static isMotionSensor(type: number): boolean {
return DeviceType.MOTION_SENSOR == type;
}
static isIntegratedDeviceBySn(sn: string): boolean {
return sn.startsWith("T8420") ||
sn.startsWith("T820") ||
sn.startsWith("T8410") ||
sn.startsWith("T8400") ||
sn.startsWith("T8401") ||
sn.startsWith("T8411") ||
sn.startsWith("T8130") ||
sn.startsWith("T8131") ||
sn.startsWith("T8422") ||
sn.startsWith("T8423") ||
sn.startsWith("T8424") ||
sn.startsWith("T8440") ||
sn.startsWith("T8441") ||
sn.startsWith("T8442");
}
static isSoloCameraBySn(sn: string): boolean {
return sn.startsWith("T8130") ||
sn.startsWith("T8131") ||
sn.startsWith("T8122") ||
sn.startsWith("T8123") ||
sn.startsWith("T8124");
}
public isCamera(): boolean {
return Device.isCamera(this.rawDevice.device_type);
}
public isFloodLight(): boolean {
return Device.isFloodLight(this.rawDevice.device_type);
}
public isDoorbell(): boolean {
return Device.isDoorbell(this.rawDevice.device_type);
}
public isWiredDoorbell(): boolean {
return Device.isWiredDoorbell(this.rawDevice.device_type);
}
public isLock(): boolean {
return Device.isLock(this.rawDevice.device_type);
}
public isLockBasic(): boolean {
return Device.isLockBasic(this.rawDevice.device_type);
}
public isLockBasicNoFinger(): boolean {
return Device.isLockBasicNoFinger(this.rawDevice.device_type);
}
public isLockAdvanced(): boolean {
return Device.isLockAdvanced(this.rawDevice.device_type);
}
public isLockAdvancedNoFinger(): boolean {
return Device.isLockAdvancedNoFinger(this.rawDevice.device_type);
}
public isBatteryDoorbell(): boolean {
return Device.isBatteryDoorbell(this.rawDevice.device_type);
}
public isBatteryDoorbell2(): boolean {
return Device.isBatteryDoorbell2(this.rawDevice.device_type);
}
public isSoloCamera(): boolean {
return Device.isSoloCamera(this.rawDevice.device_type);
}
public isSoloCameraPro(): boolean {
return Device.isSoloCameraPro(this.rawDevice.device_type);
}
public isSoloCameraSpotlight1080(): boolean {
return Device.isSoloCameraSpotlight1080(this.rawDevice.device_type);
}
public isSoloCameraSpotlight2k(): boolean {
return Device.isSoloCameraSpotlight2k(this.rawDevice.device_type);
}
public isSoloCameraSpotlightSolar(): boolean {
return Device.isSoloCameraSpotlightSolar(this.rawDevice.device_type);
}
public isIndoorOutdoorCamera1080p(): boolean {
return Device.isIndoorOutdoorCamera1080p(this.rawDevice.device_type);
}
public isIndoorOutdoorCamera1080pNoLight(): boolean {
return Device.isIndoorOutdoorCamera1080pNoLight(this.rawDevice.device_type);
}
public isIndoorOutdoorCamera2k(): boolean {
return Device.isIndoorOutdoorCamera2k(this.rawDevice.device_type);
}
public isSoloCameras(): boolean {
return Device.isSoloCameras(this.rawDevice.device_type);
}
public isCamera2(): boolean {
return Device.isCamera2(this.rawDevice.device_type);
}
public isCamera2C(): boolean {
return Device.isCamera2C(this.rawDevice.device_type);
}
public isCamera2Pro(): boolean {
return Device.isCamera2Pro(this.rawDevice.device_type);
}
public isCamera2CPro(): boolean {
return Device.isCamera2CPro(this.rawDevice.device_type);
}
public isCamera2Product(): boolean {
return Device.isCamera2Product(this.rawDevice.device_type);
}
public isEntrySensor(): boolean {
return Device.isEntrySensor(this.rawDevice.device_type);
}
public isKeyPad(): boolean {
return Device.isKeyPad(this.rawDevice.device_type);
}
public isMotionSensor(): boolean {
return Device.isMotionSensor(this.rawDevice.device_type);
}
public isIndoorCamera(): boolean {
return Device.isIndoorCamera(this.rawDevice.device_type);
}
public hasBattery(): boolean {
return Device.hasBattery(this.rawDevice.device_type);
}
public getDeviceKey(): string {
return this.rawDevice.station_sn + this.rawDevice.device_channel;
}
public getDeviceType(): number {
return this.rawDevice.device_type;
}
public getHardwareVersion(): string {
return this.rawDevice.main_hw_version;
}
public getSoftwareVersion(): string {
return this.rawDevice.main_sw_version;
}
public getModel(): string {
return this.rawDevice.device_model;
}
public getName(): string {
return this.rawDevice.device_name;
}
public getSerial(): string {
return this.rawDevice.device_sn;
}
public getStationSerial(): string {
return this.rawDevice.station_sn;
}
public async setParameters(params: { paramType: number; paramValue: any; }[]): Promise<boolean> {
return this.api.setParameters(this.rawDevice.station_sn, this.rawDevice.device_sn, params);
}
public getChannel(): number {
return this.rawDevice.device_channel;
}
public getStateID(state: string, level = 2): string {
switch (level) {
case 0:
return `${this.getStationSerial()}.${this.getStateChannel()}`
case 1:
return `${this.getStationSerial()}.${this.getStateChannel()}.${this.getSerial()}`
default:
if (state)
return `${this.getStationSerial()}.${this.getStateChannel()}.${this.getSerial()}.${state}`
throw new Error("No state value passed.");
}
}
public abstract getStateChannel(): string;
public getWifiRssi(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceWifiRSSI);
}
public getStoragePath(filename: string): string {
return getAbsoluteFilePath(this.rawDevice.device_type, this.rawDevice.device_channel, filename);
}
public isEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceEnabled);
}
}
export class Camera extends Device {
private _isStreaming = false;
constructor(api: HTTPApi, device: FullDeviceResponse) {
super(api, device);
this.properties[PropertyName.DeviceMotionDetected] = { value: false, timestamp: 0 };
this.properties[PropertyName.DevicePersonDetected] = { value: false, timestamp: 0 };
this.properties[PropertyName.DevicePersonName] = { value: "", timestamp: 0 };
}
public getStateChannel(): string {
return "cameras";
}
protected convertRawPropertyValue(property: PropertyMetadataAny, value: RawValue): PropertyValue {
try {
switch (property.key) {
case CommandType.CMD_SET_AUDIO_MUTE_RECORD:
return { value: value !== undefined ? (value.value === "0" ? true : false) : false, timestamp: value !== undefined ? value.timestamp : 0 };
}
} catch (error) {
this.log.error("Convert Error:", { property: property, value: value, error: error });
}
return super.convertRawPropertyValue(property, value);
}
public getLastCameraImageURL(): PropertyValue {
return this.getPropertyValue(PropertyName.DevicePictureUrl);
}
public getMACAddress(): string {
return this.rawDevice.wifi_mac;
}
public async startDetection(): Promise<void> {
// Start camera detection.
await this.setParameters([{ paramType: ParamType.DETECT_SWITCH, paramValue: 1 }]).catch(error => {
this.log.error("Error:", error);
});
}
public async startStream(): Promise<string> {
// Start the camera stream and return the RTSP URL.
try {
const response = await this.api.request("post", "v1/web/equipment/start_stream", {
device_sn: this.rawDevice.device_sn,
station_sn: this.rawDevice.station_sn,
proto: 2
}).catch(error => {
this.log.error("Error:", error);
return error;
});
this.log.debug("Response:", response.data);
if (response.status == 200) {
const result: ResultResponse = response.data;
if (result.code == 0) {
const dataresult: StreamResponse = result.data;
this._isStreaming = true;
this.log.info(`Livestream of camera ${this.rawDevice.device_sn} started`);
return dataresult.url;
} else {
this.log.error("Response code not ok", { code: result.code, msg: result.msg });
}
} else {
this.log.error("Status return code not 200", { status: response.status, statusText: response.statusText });
}
} catch (error) {
this.log.error("Generic Error:", error);
}
return "";
}
public async stopDetection(): Promise<void> {
// Stop camera detection.
await this.setParameters([{ paramType: ParamType.DETECT_SWITCH, paramValue: 0 }])
}
public async stopStream(): Promise<void> {
// Stop the camera stream.
try {
const response = await this.api.request("post", "v1/web/equipment/stop_stream", {
device_sn: this.rawDevice.device_sn,
station_sn: this.rawDevice.station_sn,
proto: 2
}).catch(error => {
this.log.error("Error:", error);
return error;
});
this.log.debug("Response:", response.data);
if (response.status == 200) {
const result: ResultResponse = response.data;
if (result.code == 0) {
this._isStreaming = false;
this.log.info(`Livestream of camera ${this.rawDevice.device_sn} stopped`);
} else {
this.log.error("Response code not ok", { code: result.code, msg: result.msg });
}
} else {
this.log.error("Status return code not 200", { status: response.status, statusText: response.statusText });
}
} catch (error) {
this.log.error("Generic Error:", error);
}
}
public getState(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceState);
}
public isStreaming(): boolean {
return this._isStreaming;
}
public async close(): Promise<void> {
//TODO: Stop other things if implemented such as detection feature
if (this._isStreaming)
await this.stopStream().catch();
}
public getLastChargingDays(): number {
return this.rawDevice.charging_days;
}
public getLastChargingFalseEvents(): number {
return this.rawDevice.charging_missing;
}
public getLastChargingRecordedEvents(): number {
return this.rawDevice.charging_reserve;
}
public getLastChargingTotalEvents(): number {
return this.rawDevice.charing_total;
}
public getBatteryValue(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceBattery);
}
public getBatteryTemperature(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceBatteryTemp);
}
public isMotionDetectionEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceMotionDetection);
}
public isLedEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceStatusLed);
}
public isAutoNightVisionEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceAutoNightvision);
}
public isRTSPStreamEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceRTSPStream);
}
public isAntiTheftDetectionEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceAntitheftDetection);
}
public getWatermark(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceWatermark);
}
public isMotionDetected(): boolean {
return this.getPropertyValue(PropertyName.DeviceMotionDetected).value as boolean;
}
public isPersonDetected(): boolean {
return this.getPropertyValue(PropertyName.DevicePersonDetected).value as boolean;
}
public getDetectedPerson(): string {
return this.getPropertyValue(PropertyName.DevicePersonName).value as string;
}
public processPushNotification(message: PushMessage, eventDurationSeconds: number): void {
super.processPushNotification(message, eventDurationSeconds);
if (message.type !== undefined && message.event_type !== undefined) {
if (message.event_type === CusPushEvent.SECURITY && message.device_sn === this.getSerial()) {
try {
if (message.fetch_id !== undefined) {
// Person or someone identified
this.updateProperty(PropertyName.DevicePersonDetected, { value: true, timestamp: message.event_time });
this.updateProperty(PropertyName.DevicePersonName, { value: !isEmpty(message.person_name) ? message.person_name! : "Unknown", timestamp: message.event_time });
if (!isEmpty(message.pic_url))
this.updateProperty(PropertyName.DevicePictureUrl, { value: message.pic_url, timestamp: message.event_time });
if (message.push_count === 1 || message.push_count === undefined)
this.emit("person detected", this, this.getPropertyValue(PropertyName.DevicePersonDetected).value as boolean, this.getPropertyValue(PropertyName.DevicePersonName).value as string);
this.clearEventTimeout(DeviceEvent.PersonDetected);
this.eventTimeouts.set(DeviceEvent.PersonDetected, setTimeout(async () => {
const timestamp = new Date().getTime();
this.updateProperty(PropertyName.DevicePersonDetected, { value: false, timestamp: timestamp });
this.updateProperty(PropertyName.DevicePersonName, { value: "", timestamp: timestamp });
this.emit("person detected", this, this.getPropertyValue(PropertyName.DevicePersonDetected).value as boolean, this.getPropertyValue(PropertyName.DevicePersonName).value as string);
this.eventTimeouts.delete(DeviceEvent.PersonDetected);
}, eventDurationSeconds * 1000));
} else {
// Motion detected
this.updateProperty(PropertyName.DeviceMotionDetected, { value: true, timestamp: message.event_time });
if (!isEmpty(message.pic_url))
this.updateProperty(PropertyName.DevicePictureUrl, { value: message.pic_url, timestamp: message.event_time });
if (message.push_count === 1 || message.push_count === undefined)
this.emit("motion detected", this, this.getPropertyValue(PropertyName.DeviceMotionDetected).value as boolean);
this.clearEventTimeout(DeviceEvent.MotionDetected);
this.eventTimeouts.set(DeviceEvent.MotionDetected, setTimeout(async () => {
this.updateProperty(PropertyName.DeviceMotionDetected, { value: false, timestamp: new Date().getTime() });
this.emit("motion detected", this, this.getPropertyValue(PropertyName.DeviceMotionDetected).value as boolean);
this.eventTimeouts.delete(DeviceEvent.MotionDetected);
}, eventDurationSeconds * 1000));
}
} catch (error) {
this.log.debug(`CusPushEvent.SECURITY - Device: ${message.device_sn} Error:`, error);
}
}
}
}
}
export class SoloCamera extends Camera {
public isLedEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceStatusLed);
}
public isMotionDetectionEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceMotionDetection);
}
public processPushNotification(message: PushMessage, eventDurationSeconds: number): void {
super.processPushNotification(message, eventDurationSeconds);
if (message.type !== undefined && message.event_type !== undefined) {
if (message.device_sn === this.getSerial()) {
try {
switch (message.event_type) {
case IndoorPushEvent.MOTION_DETECTION:
this.updateProperty(PropertyName.DeviceMotionDetected, { value: true, timestamp: message.event_time });
if (!isEmpty(message.pic_url))
this.updateProperty(PropertyName.DevicePictureUrl, { value: message.pic_url, timestamp: message.event_time });
if (message.push_count === 1 || message.push_count === undefined)
this.emit("motion detected", this, this.getPropertyValue(PropertyName.DeviceMotionDetected).value as boolean);
this.clearEventTimeout(DeviceEvent.MotionDetected);
this.eventTimeouts.set(DeviceEvent.MotionDetected, setTimeout(async () => {
this.updateProperty(PropertyName.DeviceMotionDetected, { value: false, timestamp: new Date().getTime() });
this.emit("motion detected", this, this.getPropertyValue(PropertyName.DeviceMotionDetected).value as boolean);
this.eventTimeouts.delete(DeviceEvent.MotionDetected);
}, eventDurationSeconds * 1000));
break;
case IndoorPushEvent.FACE_DETECTION:
this.updateProperty(PropertyName.DevicePersonDetected, { value: true, timestamp: message.event_time });
this.updateProperty(PropertyName.DevicePersonName, { value: !isEmpty(message.person_name) ? message.person_name! : "Unknown", timestamp: message.event_time });
if (!isEmpty(message.pic_url))
this.updateProperty(PropertyName.DevicePictureUrl, { value: message.pic_url, timestamp: message.event_time });
if (message.push_count === 1 || message.push_count === undefined)
this.emit("person detected", this, this.getPropertyValue(PropertyName.DevicePersonDetected).value as boolean, this.getPropertyValue(PropertyName.DevicePersonName).value as string);
this.clearEventTimeout(DeviceEvent.PersonDetected);
this.eventTimeouts.set(DeviceEvent.PersonDetected, setTimeout(async () => {
const timestamp = new Date().getTime();
this.updateProperty(PropertyName.DevicePersonDetected, { value: false, timestamp: timestamp });
this.updateProperty(PropertyName.DevicePersonName, { value: "", timestamp: timestamp });
this.emit("person detected", this, this.getPropertyValue(PropertyName.DevicePersonDetected).value as boolean, this.getPropertyValue(PropertyName.DevicePersonName).value as string);
this.eventTimeouts.delete(DeviceEvent.PersonDetected);
}, eventDurationSeconds * 1000));
break;
default:
this.log.debug("Unhandled solo camera push event", message);
break;
}
} catch (error) {
this.log.debug(`SoloPushEvent - Device: ${message.device_sn} Error:`, error);
}
}
}
}
}
export class IndoorCamera extends Camera {
constructor(api: HTTPApi, device: FullDeviceResponse) {
super(api, device);
this.properties[PropertyName.DevicePetDetected] = { value: false, timestamp: 0 };
this.properties[PropertyName.DeviceSoundDetected] = { value: false, timestamp: 0 };
this.properties[PropertyName.DeviceCryingDetected] = { value: false, timestamp: 0 };
}
public isLedEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceStatusLed);
}
public isMotionDetectionEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceMotionDetection);
}
public isPetDetectionEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DevicePetDetection);
}
public isSoundDetectionEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceSoundDetection);
}
public isPetDetected(): boolean {
return this.getPropertyValue(PropertyName.DevicePetDetected).value as boolean;
}
public isSoundDetected(): boolean {
return this.getPropertyValue(PropertyName.DeviceSoundDetected).value as boolean;
}
public isCryingDetected(): boolean {
return this.getPropertyValue(PropertyName.DeviceCryingDetected).value as boolean;
}
public processPushNotification(message: PushMessage, eventDurationSeconds: number): void {
super.processPushNotification(message, eventDurationSeconds);
if (message.type !== undefined && message.event_type !== undefined) {
if (message.device_sn === this.getSerial()) {
try {
switch (message.event_type) {
case IndoorPushEvent.MOTION_DETECTION:
this.updateProperty(PropertyName.DeviceMotionDetected, { value: true, timestamp: message.event_time });
if (!isEmpty(message.pic_url))
this.updateProperty(PropertyName.DevicePictureUrl, { value: message.pic_url, timestamp: message.event_time });
if (message.push_count === 1 || message.push_count === undefined)
this.emit("motion detected", this, this.getPropertyValue(PropertyName.DeviceMotionDetected).value as boolean);
this.clearEventTimeout(DeviceEvent.MotionDetected);
this.eventTimeouts.set(DeviceEvent.MotionDetected, setTimeout(async () => {
this.updateProperty(PropertyName.DeviceMotionDetected, { value: false, timestamp: new Date().getTime() });
this.emit("motion detected", this, this.getPropertyValue(PropertyName.DeviceMotionDetected).value as boolean);
this.eventTimeouts.delete(DeviceEvent.MotionDetected);
}, eventDurationSeconds * 1000));
break;
case IndoorPushEvent.FACE_DETECTION:
this.updateProperty(PropertyName.DevicePersonDetected, { value: true, timestamp: message.event_time });
this.updateProperty(PropertyName.DevicePersonName, { value: !isEmpty(message.person_name) ? message.person_name! : "Unknown", timestamp: message.event_time });
if (!isEmpty(message.pic_url))
this.updateProperty(PropertyName.DevicePictureUrl, { value: message.pic_url, timestamp: message.event_time });
if (message.push_count === 1 || message.push_count === undefined)
this.emit("person detected", this, this.getPropertyValue(PropertyName.DevicePersonDetected).value as boolean, this.getPropertyValue(PropertyName.DevicePersonName).value as string);
this.clearEventTimeout(DeviceEvent.PersonDetected);
this.eventTimeouts.set(DeviceEvent.PersonDetected, setTimeout(async () => {
const timestamp = new Date().getTime();
this.updateProperty(PropertyName.DevicePersonDetected, { value: false, timestamp: timestamp });
this.updateProperty(PropertyName.DevicePersonName, { value: "", timestamp: timestamp });
this.emit("person detected", this, this.getPropertyValue(PropertyName.DevicePersonDetected).value as boolean, this.getPropertyValue(PropertyName.DevicePersonName).value as string);
this.eventTimeouts.delete(DeviceEvent.PersonDetected);
}, eventDurationSeconds * 1000));
break;
case IndoorPushEvent.CRYING_DETECTION:
this.updateProperty(PropertyName.DeviceCryingDetected, { value: true, timestamp: message.event_time });
if (message.push_count === 1 || message.push_count === undefined)
this.emit("crying detected", this, this.getPropertyValue(PropertyName.DeviceCryingDetected).value as boolean);
this.clearEventTimeout(DeviceEvent.CryingDetected);
this.eventTimeouts.set(DeviceEvent.CryingDetected, setTimeout(async () => {
this.updateProperty(PropertyName.DeviceCryingDetected, { value: false, timestamp: new Date().getTime() });
this.emit("crying detected", this, this.getPropertyValue(PropertyName.DeviceCryingDetected).value as boolean);
this.eventTimeouts.delete(DeviceEvent.CryingDetected);
}, eventDurationSeconds * 1000));
break;
case IndoorPushEvent.SOUND_DETECTION:
this.updateProperty(PropertyName.DeviceSoundDetected, { value: true, timestamp: message.event_time });
if (message.push_count === 1 || message.push_count === undefined)
this.emit("sound detected", this, this.getPropertyValue(PropertyName.DeviceSoundDetected).value as boolean);
this.clearEventTimeout(DeviceEvent.SoundDetected);
this.eventTimeouts.set(DeviceEvent.SoundDetected, setTimeout(async () => {
this.updateProperty(PropertyName.DeviceSoundDetected, { value: false, timestamp: new Date().getTime() });
this.emit("sound detected", this, this.getPropertyValue(PropertyName.DeviceSoundDetected).value as boolean);
this.eventTimeouts.delete(DeviceEvent.SoundDetected);
}, eventDurationSeconds * 1000));
break;
case IndoorPushEvent.PET_DETECTION:
this.updateProperty(PropertyName.DevicePetDetected, { value: true, timestamp: message.event_time });
if (!isEmpty(message.pic_url))
this.updateProperty(PropertyName.DevicePictureUrl, { value: message.pic_url, timestamp: message.event_time });
if (message.push_count === 1 || message.push_count === undefined)
this.emit("pet detected", this, this.getPropertyValue(PropertyName.DevicePetDetected).value as boolean);
this.clearEventTimeout(DeviceEvent.PetDetected);
this.eventTimeouts.set(DeviceEvent.PetDetected, setTimeout(async () => {
this.updateProperty(PropertyName.DevicePetDetected, { value: false, timestamp: new Date().getTime() });
this.emit("pet detected", this, this.getPropertyValue(PropertyName.DevicePetDetected).value as boolean);
this.eventTimeouts.delete(DeviceEvent.PetDetected);
}, eventDurationSeconds * 1000));
break;
default:
this.log.debug("Unhandled indoor camera push event", message);
break;
}
} catch (error) {
this.log.debug(`IndoorPushEvent - Device: ${message.device_sn} Error:`, error);
}
}
}
}
public destroy(): void {
super.destroy();
}
}
export class DoorbellCamera extends Camera {
constructor(api: HTTPApi, device: FullDeviceResponse) {
super(api, device);
this.properties[PropertyName.DeviceRinging] = { value: false, timestamp: 0 };
}
public isRinging(): boolean {
return this.getPropertyValue(PropertyName.DeviceRinging).value as boolean;
}
public processPushNotification(message: PushMessage, eventDurationSeconds: number): void {
super.processPushNotification(message, eventDurationSeconds);
if (message.type !== undefined && message.event_type !== undefined) {
if (message.device_sn === this.getSerial()) {
try {
switch (message.event_type) {
case DoorbellPushEvent.MOTION_DETECTION:
this.updateProperty(PropertyName.DeviceMotionDetected, { value: true, timestamp: message.event_time });
if (!isEmpty(message.pic_url))
this.updateProperty(PropertyName.DevicePictureUrl, { value: message.pic_url, timestamp: message.event_time });
if (message.push_count === 1 || message.push_count === undefined)
this.emit("motion detected", this, this.getPropertyValue(PropertyName.DeviceMotionDetected).value as boolean);
this.clearEventTimeout(DeviceEvent.MotionDetected);
this.eventTimeouts.set(DeviceEvent.MotionDetected, setTimeout(async () => {
this.updateProperty(PropertyName.DeviceMotionDetected, { value: false, timestamp: new Date().getTime() });
this.emit("motion detected", this, this.getPropertyValue(PropertyName.DeviceMotionDetected).value as boolean);
this.eventTimeouts.delete(DeviceEvent.MotionDetected);
}, eventDurationSeconds * 1000));
break;
case DoorbellPushEvent.FACE_DETECTION:
this.updateProperty(PropertyName.DevicePersonDetected, { value: true, timestamp: message.event_time });
this.updateProperty(PropertyName.DevicePersonName, { value: !isEmpty(message.person_name) ? message.person_name! : "Unknown", timestamp: message.event_time });
if (!isEmpty(message.pic_url))
this.updateProperty(PropertyName.DevicePictureUrl, { value: message.pic_url, timestamp: message.event_time });
if (message.push_count === 1 || message.push_count === undefined)
this.emit("person detected", this, this.getPropertyValue(PropertyName.DevicePersonDetected).value as boolean, this.getPropertyValue(PropertyName.DevicePersonName).value as string);
this.clearEventTimeout(DeviceEvent.PersonDetected);
this.eventTimeouts.set(DeviceEvent.PersonDetected, setTimeout(async () => {
const timestamp = new Date().getTime();
this.updateProperty(PropertyName.DevicePersonDetected, { value: false, timestamp: timestamp });
this.updateProperty(PropertyName.DevicePersonName, { value: "", timestamp: timestamp });
this.eventTimeouts.delete(DeviceEvent.PersonDetected);
}, eventDurationSeconds * 1000));
break;
case DoorbellPushEvent.PRESS_DOORBELL:
this.updateProperty(PropertyName.DeviceRinging, { value: true, timestamp: message.event_time });
if (!isEmpty(message.pic_url))
this.updateProperty(PropertyName.DevicePictureUrl, { value: message.pic_url, timestamp: message.event_time });
if (message.push_count === 1 || message.push_count === undefined)
this.emit("rings", this, this.getPropertyValue(PropertyName.DeviceRinging).value as boolean);
this.clearEventTimeout(DeviceEvent.Ringing);
this.eventTimeouts.set(DeviceEvent.Ringing, setTimeout(async () => {
this.updateProperty(PropertyName.DeviceRinging, { value: false, timestamp: new Date().getTime() });
this.emit("rings", this, this.getPropertyValue(PropertyName.DeviceRinging).value as boolean);
this.eventTimeouts.delete(DeviceEvent.Ringing);
}, eventDurationSeconds * 1000));
break;
default:
this.log.debug("Unhandled doorbell push event", message);
break;
}
} catch (error) {
this.log.debug(`DoorbellPushEvent - Device: ${message.device_sn} Error:`, error);
}
}
}
}
}
export class WiredDoorbellCamera extends DoorbellCamera {
public isLedEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceStatusLed);
}
public isAutoNightVisionEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceAutoNightvision);
}
public isMotionDetectionEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceMotionDetection);
}
}
export class BatteryDoorbellCamera extends DoorbellCamera {
public isLedEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceStatusLed);
}
}
export class FloodlightCamera extends Camera {
public isLedEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceStatusLed);
}
public isMotionDetectionEnabled(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceMotionDetection);
}
protected convertRawPropertyValue(property: PropertyMetadataAny, value: RawValue): PropertyValue {
try {
switch (property.key) {
case CommandType.CMD_DEV_RECORD_AUTOSTOP:
if (this.getDeviceType() === DeviceType.FLOODLIGHT_CAMERA_8423 || this.getDeviceType() === DeviceType.FLOODLIGHT)
return { value: value !== undefined ? (value.value === "0" ? true : false) : false, timestamp: value !== undefined ? value.timestamp : 0 };
break;
case CommandType.CMD_FLOODLIGHT_SET_AUTO_CALIBRATION:
if (this.getDeviceType() === DeviceType.FLOODLIGHT_CAMERA_8423)
return { value: value !== undefined ? (value.value === "0" ? true : false) : false, timestamp: value !== undefined ? value.timestamp : 0 };
break;
case CommandType.CMD_RECORD_AUDIO_SWITCH:
return { value: value !== undefined ? (value.value === "0" ? true : false) : false, timestamp: value !== undefined ? value.timestamp : 0 };
case CommandType.CMD_SET_AUDIO_MUTE_RECORD:
if (this.getDeviceType() === DeviceType.FLOODLIGHT_CAMERA_8423)
return { value: value !== undefined ? (value.value === "1" ? true : false) : false, timestamp: value !== undefined ? value.timestamp : 0 };
return { value: value !== undefined ? (value.value === "0" ? true : false) : false, timestamp: value !== undefined ? value.timestamp : 0 };
case CommandType.CMD_SET_PIRSENSITIVITY:
switch (Number.parseInt(value.value)) {
case FloodlightMotionTriggeredDistance.MIN:
return { value: 1, timestamp: value !== undefined ? value.timestamp : 0 };
case FloodlightMotionTriggeredDistance.LOW:
return { value: 2, timestamp: value !== undefined ? value.timestamp : 0 };
case FloodlightMotionTriggeredDistance.MEDIUM:
return { value: 3, timestamp: value !== undefined ? value.timestamp : 0 };
case FloodlightMotionTriggeredDistance.HIGH:
return { value: 4, timestamp: value !== undefined ? value.timestamp : 0 };
case FloodlightMotionTriggeredDistance.MAX:
return { value: 5, timestamp: value !== undefined ? value.timestamp : 0 };
default:
return { value: 5, timestamp: value !== undefined ? value.timestamp : 0 };
}
}
} catch (error) {
this.log.error("Convert Error:", { property: property, value: value, error: error });
}
return super.convertRawPropertyValue(property, value);
}
}
export class Sensor extends Device {
public getStateChannel(): string {
return "sensors";
}
public getState(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceState);
}
}
export class EntrySensor extends Sensor {
public isSensorOpen(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceSensorOpen);
}
public getSensorChangeTime(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceSensorChangeTime);
}
public isBatteryLow(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceBatteryLow);
}
public processPushNotification(message: PushMessage, eventDurationSeconds: number): void {
super.processPushNotification(message, eventDurationSeconds);
if (message.type !== undefined && message.event_type !== undefined) {
if (message.event_type === CusPushEvent.DOOR_SENSOR && message.device_sn === this.getSerial()) {
try {
if (message.sensor_open !== undefined) {
this.updateRawProperty(CommandType.CMD_ENTRY_SENSOR_STATUS, { value: message.sensor_open ? "1" : "0", timestamp: convertTimestampMs(message.event_time) });
this.emit("open", this, message.sensor_open);
}
} catch (error) {
this.log.debug(`CusPushEvent.DOOR_SENSOR - Device: ${message.device_sn} Error:`, error);
}
}
}
}
}
export class MotionSensor extends Sensor {
public static readonly MOTION_COOLDOWN_MS = 120000;
//TODO: CMD_MOTION_SENSOR_ENABLE_LED = 1607
//TODO: CMD_MOTION_SENSOR_ENTER_USER_TEST_MODE = 1613
//TODO: CMD_MOTION_SENSOR_EXIT_USER_TEST_MODE = 1610
//TODO: CMD_MOTION_SENSOR_SET_CHIRP_TONE = 1611
//TODO: CMD_MOTION_SENSOR_SET_PIR_SENSITIVITY = 1609
//TODO: CMD_MOTION_SENSOR_WORK_MODE = 1612
/*public static isMotionDetected(millis: number): { motion: boolean, cooldown_ms: number} {
const delta = new Date().getUTCMilliseconds() - millis;
if (delta < this.MOTION_COOLDOWN_MS) {
return { motion: true, cooldown_ms: this.MOTION_COOLDOWN_MS - delta};
}
return { motion: false, cooldown_ms: 0};
}
public isMotionDetected(): { motion: boolean, cooldown_ms: number} {
return MotionSensor.isMotionDetected(this.getMotionSensorPIREvent().value);
}*/
constructor(api: HTTPApi, device: FullDeviceResponse) {
super(api, device);
this.properties[PropertyName.DeviceMotionDetected] = { value: false, timestamp: 0 };
}
public isMotionDetected(): boolean {
return this.getPropertyValue(PropertyName.DeviceMotionDetected).value as boolean;
}
public getMotionSensorPIREvent(): PropertyValue {
//TODO: Implement P2P Control Event over active station connection
return this.getPropertyValue(PropertyName.DeviceMotionSensorPIREvent);
}
public isBatteryLow(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceBatteryLow);
}
public processPushNotification(message: PushMessage, eventDurationSeconds: number): void {
super.processPushNotification(message, eventDurationSeconds);
if (message.type !== undefined && message.event_type !== undefined) {
if (message.event_type === CusPushEvent.MOTION_SENSOR_PIR && message.device_sn === this.getSerial()) {
try {
this.updateProperty(PropertyName.DeviceMotionDetected, { value: true, timestamp: message.event_time });
this.emit("motion detected", this, this.getPropertyValue(PropertyName.DeviceMotionDetected).value as boolean);
this.clearEventTimeout(DeviceEvent.MotionDetected);
this.eventTimeouts.set(DeviceEvent.MotionDetected, setTimeout(async () => {
this.updateProperty(PropertyName.DeviceMotionDetected, { value: false, timestamp: new Date().getTime() });
this.emit("motion detected", this, this.getPropertyValue(PropertyName.DeviceMotionDetected).value as boolean);
this.eventTimeouts.delete(DeviceEvent.MotionDetected);
}, eventDurationSeconds * 1000));
} catch (error) {
this.log.debug(`CusPushEvent.MOTION_SENSOR_PIR - Device: ${message.device_sn} Error:`, error);
}
}
}
}
}
export class Lock extends Device {
public getStateChannel(): string {
return "locks";
}
protected processCustomParameterChanged(metadata: PropertyMetadataAny, oldValue: PropertyValue, newValue: PropertyValue): void {
super.processCustomParameterChanged(metadata, oldValue, newValue);
if (metadata.key === CommandType.CMD_DOORLOCK_GET_STATE && oldValue !== undefined && ((oldValue.value === 4 && newValue.value !== 4) || (oldValue.value !== 4 && newValue.value === 4))) {
if (this.updateProperty(PropertyName.DeviceLocked, { value: newValue.value === 4 ? true : false, timestamp: newValue.timestamp}))
this.emit("locked", this as unknown as Lock, newValue.value === 4 ? true : false);
}
}
public getState(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceState);
}
public getBatteryValue(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceBattery);
}
public getWifiRssi(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceWifiRSSI);
}
public isLocked(): PropertyValue {
const param = this.getLockStatus();
return { value: param ? (param.value === 4 ? true : false) : false, timestamp: param ? param.timestamp : 0 };
}
public getLockStatus(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceLockStatus);
}
// public isBatteryLow(): PropertyValue {
// return this.getPropertyValue(PropertyName.DeviceBatteryLow);
// }
public static encodeESLCmdOnOff(short_user_id: number, nickname: string, lock: boolean): Buffer {
const buf1 = Buffer.from([ESLAnkerBleConstant.a, 2]);
const buf2 = Buffer.allocUnsafe(2);
buf2.writeUInt16BE(short_user_id);
const buf3 = Buffer.from([ESLAnkerBleConstant.b, 1, lock === true ? 1 : 0, ESLAnkerBleConstant.c, 4]);
const buf4 = Buffer.from(eslTimestamp());
const buf5 = Buffer.from([ESLAnkerBleConstant.d, nickname.length]);
const buf6 = Buffer.from(nickname);
return Buffer.concat([buf1, buf2, buf3, buf4, buf5, buf6]);
}
public static encodeESLCmdQueryStatus(admin_user_id: string): Buffer {
const buf1 = Buffer.from([ESLAnkerBleConstant.a, admin_user_id.length]);
const buf2 = Buffer.from(admin_user_id);
const buf3 = Buffer.from([ESLAnkerBleConstant.b, 4]);
const buf4 = Buffer.from(eslTimestamp());
return Buffer.concat([buf1, buf2, buf3, buf4]);
}
protected convertRawPropertyValue(property: PropertyMetadataAny, value: RawValue): PropertyValue {
try {
if (property.key === CommandType.CMD_DOORLOCK_GET_STATE) {
switch (value.value) {
case "3":
return { value: false, timestamp: value.timestamp };
case "4":
return { value: true, timestamp: value.timestamp };
}
}
} catch (error) {
this.log.error("Convert Error:", { property: property, value: value, error: error });
}
return super.convertRawPropertyValue(property, value);
}
public processPushNotification(message: PushMessage, eventDurationSeconds: number): void {
super.processPushNotification(message, eventDurationSeconds);
if (message.type !== undefined && message.event_type !== undefined) {
if (message.device_sn === this.getSerial()) {
try {
switch (message.event_type) {
case LockPushEvent.APP_LOCK:
case LockPushEvent.AUTO_LOCK:
case LockPushEvent.FINGER_LOCK:
case LockPushEvent.KEYPAD_LOCK:
case LockPushEvent.MANUAL_LOCK:
case LockPushEvent.PW_LOCK:
this.updateRawProperty(CommandType.CMD_DOORLOCK_GET_STATE, { value: "4", timestamp: convertTimestampMs(message.event_time) });
this.emit("locked", this, this.getPropertyValue(PropertyName.DeviceLocked).value as boolean);
break;
case LockPushEvent.APP_UNLOCK:
case LockPushEvent.AUTO_UNLOCK:
case LockPushEvent.FINGER_UNLOCK:
case LockPushEvent.MANUAL_UNLOCK:
case LockPushEvent.PW_UNLOCK:
this.updateRawProperty(CommandType.CMD_DOORLOCK_GET_STATE, { value: "3", timestamp: convertTimestampMs(message.event_time) });
this.emit("locked", this, this.getPropertyValue(PropertyName.DeviceLocked).value as boolean);
break;
case LockPushEvent.LOCK_MECHANICAL_ANOMALY:
case LockPushEvent.MECHANICAL_ANOMALY:
case LockPushEvent.VIOLENT_DESTRUCTION:
case LockPushEvent.MULTIPLE_ERRORS:
this.updateRawProperty(CommandType.CMD_DOORLOCK_GET_STATE, { value: "5", timestamp: convertTimestampMs(message.event_time) });
break;
// case LockPushEvent.LOW_POWE:
// this.updateRawProperty(CommandType.CMD_SMARTLOCK_QUERY_BATTERY_LEVEL, { value: "10", timestamp: convertTimestampMs(message.event_time) });
// break;
// case LockPushEvent.VERY_LOW_POWE:
// this.updateRawProperty(CommandType.CMD_SMARTLOCK_QUERY_BATTERY_LEVEL, { value: "5", timestamp: convertTimestampMs(message.event_time) });
// break;
default:
this.log.debug("Unhandled lock push event", message);
break;
}
} catch (error) {
this.log.debug(`LockPushEvent - Device: ${message.device_sn} Error:`, error);
}
}
}
}
/*public static decodeCommand(command: number): void {
switch (command) {
case ESLCommand.ON_OFF_LOCK:
case 8:
break;
case ESLCommand.QUERY_STATUS_IN_LOCK:
case 17:
break;
case ESLCommand.NOTIFY:
case 18:
break;
default:
break;
}
}*/
}
export class Keypad extends Device {
//TODO: CMD_KEYPAD_BATTERY_CHARGER_STATE = 1655
//TODO: CMD_KEYPAD_BATTERY_TEMP_STATE = 1654
//TODO: CMD_KEYPAD_GET_PASSWORD = 1657
//TODO: CMD_KEYPAD_GET_PASSWORD_LIST = 1662
//TODO: CMD_KEYPAD_IS_PSW_SET = 1670
//TODO: CMD_KEYPAD_SET_CUSTOM_MAP = 1660
//TODO: CMD_KEYPAD_SET_PASSWORD = 1650
public getStateChannel(): string {
return "keypads";
}
public getState(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceState);
}
public isBatteryLow(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceBatteryLow);
}
public isBatteryCharging(): PropertyValue {
return this.getPropertyValue(PropertyName.DeviceBatteryIsCharging);
}
protected convertRawPropertyValue(property: PropertyMetadataAny, value: RawValue): PropertyValue {
try {
switch(property.key) {
case CommandType.CMD_KEYPAD_BATTERY_CHARGER_STATE:
return { value: value !== undefined ? (value.value === "0" || value.value === "2"? false : true) : false, timestamp: value !== undefined ? value.timestamp : 0 };
}
} catch (error) {
this.log.error("Convert Error:", { property: property, value: value, error: error });
}
return super.convertRawPropertyValue(property, value);
}
}
export class UnknownDevice extends Device {
public getStateChannel(): string {
return "unknown";
}
} | the_stack |
import { barTimestamp } from '~blockml/barrels/bar-timestamp';
import { common } from '~blockml/barrels/common';
import { constants } from '~blockml/barrels/constants';
import { enums } from '~blockml/barrels/enums';
export function processFilter(item: {
filterBricks: string[];
result: common.FieldResultEnum;
// parameters below do not affect validation
weekStart?: common.ProjectWeekStartEnum;
connection?: common.ProjectConnection;
timezone?: string;
proc?: string;
sqlTsSelect?: string;
ors?: string[];
nots?: string[];
ins?: string[];
notIns?: string[];
fractions?: common.Fraction[];
}): { valid: number; brick?: string } {
let {
filterBricks,
result,
weekStart,
connection,
timezone,
proc,
sqlTsSelect,
ors,
nots,
ins,
notIns,
fractions
} = item;
weekStart = common.isDefined(weekStart)
? weekStart
: common.ProjectWeekStartEnum.Monday;
let cn = {
connectionId: 'cn',
type: common.ConnectionTypeEnum.PostgreSQL
};
connection = common.isDefined(connection) ? connection : cn;
timezone = common.isDefined(timezone) ? timezone : common.UTC;
proc = common.isDefined(proc) ? proc : 'proc';
sqlTsSelect = common.isDefined(sqlTsSelect) ? sqlTsSelect : 'sqlTsSelect';
ors = common.isDefined(ors) ? ors : [];
nots = common.isDefined(nots) ? nots : [];
ins = common.isDefined(ins) ? ins : [];
notIns = common.isDefined(notIns) ? notIns : [];
fractions = common.isDefined(fractions) ? fractions : [];
let answerError: { valid: number; brick?: string };
filterBricks.forEach(brick => {
let r;
let num: string;
let value: string;
let value1: string;
let value2: string;
let not: string;
let nullValue: string;
let blank: string;
let condition: string;
if (answerError) {
return;
}
if (result === common.FieldResultEnum.Number) {
// IS EQUAL TO
// IS NOT EQUAL TO
if ((r = common.MyRegex.BRICK_NUMBER_NOT_AND_DIGITS().exec(brick))) {
not = r[1];
let equals = brick.split(',');
let nums: string[] = [];
equals.forEach(equal => {
if (answerError) {
return;
}
let eReg = common.MyRegex.BRICK_NUMBER_EQUAL_TO();
let eR = eReg.exec(equal);
if (eR) {
num = eR[1];
}
if (not && num) {
notIns.push(num);
nums.push(num);
} else if (num) {
ins.push(num);
nums.push(num);
} else if (not) {
nots.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
} else {
ors.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
}
});
let numValues = nums.join(', ');
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.NumberIsNotEqualTo,
numberValues: numValues
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.NumberIsEqualTo,
numberValues: numValues
});
}
// IS GREATER THAN OR EQUAL TO
} else if (
(r = common.MyRegex.BRICK_NUMBER_IS_GREATER_THAN_OR_EQUAL_TO().exec(
brick
))
) {
value = r[1];
ors.push(`${proc} >= ${value}`);
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.NumberIsGreaterThanOrEqualTo,
numberValue1: Number(value)
});
// IS GREATER THAN
} else if (
(r = common.MyRegex.BRICK_NUMBER_IS_GREATER_THAN().exec(brick))
) {
value = r[1];
ors.push(`${proc} > ${value}`);
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.NumberIsGreaterThan,
numberValue1: Number(value)
});
// IS LESS THAN OR EQUAL TO
} else if (
(r = common.MyRegex.BRICK_NUMBER_IS_LESS_THAN_OR_EQUAL_TO().exec(brick))
) {
value = r[1];
ors.push(`${proc} <= ${value}`);
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.NumberIsLessThanOrEqualTo,
numberValue1: Number(value)
});
// IS LESS THAN
} else if ((r = common.MyRegex.BRICK_NUMBER_IS_LESS_THAN().exec(brick))) {
value = r[1];
ors.push(`${proc} < ${value}`);
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.NumberIsLessThan,
numberValue1: Number(value)
});
// IS ANY VALUE
} else if ((r = common.MyRegex.BRICK_IS_ANY_VALUE().exec(brick))) {
ors.push(constants.SQL_TRUE_CONDITION);
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.NumberIsAnyValue
});
} else {
// [,]
// not [,]
if (
(r = common.MyRegex.BRICK_NUMBER_IS_BETWEEN_INCLUSIVE().exec(brick))
) {
not = r[1];
value1 = r[2];
value2 = r[3];
condition = `((${proc} >= ${value1}) AND (${proc} <= ${value2}))`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.NumberIsNotBetween,
numberValue1: Number(value1),
numberValue2: Number(value2),
numberBetweenOption:
common.FractionNumberBetweenOptionEnum.Inclusive
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.NumberIsBetween,
numberValue1: Number(value1),
numberValue2: Number(value2),
numberBetweenOption:
common.FractionNumberBetweenOptionEnum.Inclusive
});
}
// [,)
// not [,)
} else if (
(r = common.MyRegex.BRICK_NUMBER_IS_BETWEEN_LEFT_INCLUSIVE().exec(
brick
))
) {
not = r[1];
value1 = r[2];
value2 = r[3];
condition = `((${proc} >= ${value1}) AND (${proc} < ${value2}))`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.NumberIsNotBetween,
numberValue1: Number(value1),
numberValue2: Number(value2),
numberBetweenOption:
common.FractionNumberBetweenOptionEnum.LeftInclusive
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.NumberIsBetween,
numberValue1: Number(value1),
numberValue2: Number(value2),
numberBetweenOption:
common.FractionNumberBetweenOptionEnum.LeftInclusive
});
}
// (,]
// not (,]
} else if (
(r = common.MyRegex.BRICK_NUMBER_IS_BETWEEN_RIGHT_INCLUSIVE().exec(
brick
))
) {
not = r[1];
value1 = r[2];
value2 = r[3];
condition = `((${proc} > ${value1}) AND (${proc} <= ${value2}))`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.NumberIsNotBetween,
numberValue1: Number(value1),
numberValue2: Number(value2),
numberBetweenOption:
common.FractionNumberBetweenOptionEnum.RightInclusive
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.NumberIsBetween,
numberValue1: Number(value1),
numberValue2: Number(value2),
numberBetweenOption:
common.FractionNumberBetweenOptionEnum.RightInclusive
});
}
// (,)
// not (,)
} else if (
(r = common.MyRegex.BRICK_NUMBER_IS_BETWEEN_EXCLUSIVE().exec(brick))
) {
not = r[1];
value1 = r[2];
value2 = r[3];
condition = `((${proc} > ${value1}) AND (${proc} < ${value2}))`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.NumberIsNotBetween,
numberValue1: Number(value1),
numberValue2: Number(value2),
numberBetweenOption:
common.FractionNumberBetweenOptionEnum.Exclusive
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.NumberIsBetween,
numberValue1: Number(value1),
numberValue2: Number(value2),
numberBetweenOption:
common.FractionNumberBetweenOptionEnum.Exclusive
});
}
// IS NULL
// IS NOT NULL
} else if ((r = common.MyRegex.BRICK_IS_NULL().exec(brick))) {
not = r[1];
nullValue = r[2];
condition = `(${proc} IS NULL)`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.NumberIsNotNull
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.NumberIsNull
});
}
}
// common for else of number
if (not && condition) {
nots.push(`NOT ${condition}`);
} else if (condition) {
ors.push(condition);
} else if (not) {
nots.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
} else {
ors.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
}
}
} else if (result === common.FieldResultEnum.String) {
// IS EQUAL TO
// IS NOT EQUAL TO
if ((r = common.MyRegex.BRICK_STRING_IS_EQUAL_TO().exec(brick))) {
not = r[1];
value = r[2];
condition = `${proc} = '${value}'`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.StringIsNotEqualTo,
stringValue: value
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.StringIsEqualTo,
stringValue: value
});
}
// CONTAINS
// DOES NOT CONTAIN
} else if ((r = common.MyRegex.BRICK_STRING_CONTAINS().exec(brick))) {
not = r[1];
value = r[2];
condition = `${proc} LIKE '%${value}%'`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.StringDoesNotContain,
stringValue: value
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.StringContains,
stringValue: value
});
}
// STARTS WITH
// DOES NOT START WITH
} else if ((r = common.MyRegex.BRICK_STRING_STARTS_WITH().exec(brick))) {
value = r[1];
not = r[2];
condition = `${proc} LIKE '${value}%'`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.StringDoesNotStartWith,
stringValue: value
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.StringStartsWith,
stringValue: value
});
}
// ENDS WITH
// DOES NOT END WITH
} else if ((r = common.MyRegex.BRICK_STRING_ENDS_WITH().exec(brick))) {
not = r[1];
value = r[2];
condition = `${proc} LIKE '%${value}'`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.StringDoesNotEndWith,
stringValue: value
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.StringEndsWith,
stringValue: value
});
}
// IS NULL
// IS NOT NULL
} else if ((r = common.MyRegex.BRICK_IS_NULL().exec(brick))) {
not = r[1];
nullValue = r[2];
condition = `(${proc} IS NULL)`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.StringIsNotNull
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.StringIsNull
});
}
// IS BLANK
// IS NOT BLANK
} else if ((r = common.MyRegex.BRICK_STRING_IS_BLANK().exec(brick))) {
not = r[1];
blank = r[2];
if (connection.type === common.ConnectionTypeEnum.BigQuery) {
condition = `(${proc} IS NULL OR LENGTH(CAST(${proc} AS STRING)) = 0)`;
} else if (connection.type === common.ConnectionTypeEnum.PostgreSQL) {
condition = `(${proc} IS NULL OR LENGTH(CAST(${proc} AS TEXT)) = 0)`;
}
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.StringIsNotBlank
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.StringIsBlank
});
}
// IS ANY VALUE
} else if ((r = common.MyRegex.BRICK_IS_ANY_VALUE().exec(brick))) {
condition = constants.SQL_TRUE_CONDITION;
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.StringIsAnyValue
});
}
// common for string
if (not && condition) {
nots.push(`NOT ${condition}`);
} else if (condition) {
ors.push(condition);
} else if (not) {
nots.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
} else {
ors.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
}
} else if (result === common.FieldResultEnum.Yesno) {
// YESNO YES
if ((r = common.MyRegex.BRICK_YESNO_IS_YES().exec(brick))) {
condition = `${proc} = 'Yes'`;
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.YesnoIs,
yesnoValue: common.FractionYesnoValueEnum.Yes
});
// YESNO NO
} else if ((r = common.MyRegex.BRICK_YESNO_IS_NO().exec(brick))) {
condition = `${proc} = 'No'`;
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.YesnoIs,
yesnoValue: common.FractionYesnoValueEnum.No
});
// IS ANY VALUE
} else if ((r = common.MyRegex.BRICK_IS_ANY_VALUE().exec(brick))) {
condition = constants.SQL_TRUE_CONDITION;
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.YesnoIsAnyValue
});
}
// common for yesno
if (condition) {
ors.push(condition);
} else {
ors.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
}
} else if (result === common.FieldResultEnum.Ts) {
let {
currentTs,
currentMinuteTs,
currentHourTs,
currentDateTs,
currentWeekStartTs,
currentMonthTs,
currentQuarterTs,
currentYearTs
} = barTimestamp.makeTimestampsCurrent({
timezone: timezone,
weekStart: weekStart,
connection: connection
});
let way;
let integerStr: string;
let unit;
let year;
let month;
let day;
let hour;
let minute;
let toYear;
let toMonth;
let toDay;
let toHour;
let toMinute;
let complete;
let when;
let plusCurrent;
let forIntegerStr: string;
let forUnit;
if ((r = common.MyRegex.BRICK_TS_INTERVALS().exec(brick))) {
way = r[1];
integerStr = r[2];
unit = r[3];
year = r[4];
month = r[5];
day = r[6];
hour = r[7];
minute = r[8];
complete = r[9];
when = r[10];
plusCurrent = r[11];
forIntegerStr = r[12];
forUnit = r[13];
let open;
let close;
let one;
let two;
if (year) {
open = barTimestamp.makeTimestampOpenFromDateParts({
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
connection: connection
});
switch (true) {
case way === 'after': {
one = `${sqlTsSelect} >= ${open}`;
two = '';
break;
}
case way === 'before': {
one = `${sqlTsSelect} < ${open}`;
two = '';
break;
}
}
} else {
// OPEN INTERVAL
if (
(way.match(/^last$/) && complete) ||
(way.match(/^before|after$/) && when.match(/^ago$/) && complete)
) {
open = barTimestamp.makeTimestampOpenLastBeforeAfterComplete({
unit: unit,
integer: Number(integerStr),
currentYearTs: currentYearTs,
currentQuarterTs: currentQuarterTs,
currentMonthTs: currentMonthTs,
currentWeekStartTs: currentWeekStartTs,
currentDateTs: currentDateTs,
currentHourTs: currentHourTs,
currentMinuteTs: currentMinuteTs,
connection: connection
});
} else if (
way.match(/^last$/) ||
(way.match(/^before|after$/) && when.match(/^ago$/))
) {
open = barTimestamp.makeTimestampOpenLastBeforeAfter({
unit: unit,
integer: Number(integerStr),
currentTs: currentTs,
connection: connection
});
} else if (
way.match(/^before|after$/) &&
when.match(/^in\s+future$/) &&
complete
) {
open = barTimestamp.makeTimestampOpenBeforeAfterInFutureComplete({
unit: unit,
integer: Number(integerStr),
currentYearTs: currentYearTs,
currentQuarterTs: currentQuarterTs,
currentMonthTs: currentMonthTs,
currentWeekStartTs: currentWeekStartTs,
currentDateTs: currentDateTs,
currentHourTs: currentHourTs,
currentMinuteTs: currentMinuteTs,
connection: connection
});
} else if (
way.match(/^before|after$/) &&
when.match(/^in\s+future$/)
) {
open = barTimestamp.makeTimestampOpenBeforeAfterInFuture({
unit: unit,
integer: Number(integerStr),
currentTs: currentTs,
connection: connection
});
}
// CLOSE INTERVAL
if (way.match(/^last$/) && complete && plusCurrent) {
close = barTimestamp.makeTimestampCloseLastCompletePlusCurrent({
unit: unit,
currentYearTs: currentYearTs,
currentQuarterTs: currentQuarterTs,
currentMonthTs: currentMonthTs,
currentWeekStartTs: currentWeekStartTs,
currentDateTs: currentDateTs,
currentHourTs: currentHourTs,
currentMinuteTs: currentMinuteTs,
connection: connection
});
} else if (way.match(/^last$/) && complete) {
close =
unit === enums.FractionUnitEnum.Minutes
? currentMinuteTs
: unit === enums.FractionUnitEnum.Hours
? currentHourTs
: unit === enums.FractionUnitEnum.Days
? currentDateTs
: unit === enums.FractionUnitEnum.Weeks
? currentWeekStartTs
: unit === enums.FractionUnitEnum.Months
? currentMonthTs
: unit === enums.FractionUnitEnum.Quarters
? currentQuarterTs
: unit === enums.FractionUnitEnum.Years
? currentYearTs
: undefined;
} else if (way.match(/^last$/)) {
close = currentTs;
}
}
if (way.match(/^before|after$/) && forUnit) {
let sIntegerStr = way.match(/^after$/)
? `${forIntegerStr}`
: `-${forIntegerStr}`;
close = barTimestamp.makeTimestampCloseBeforeAfterForUnit({
open: open,
forUnit: forUnit,
sInteger: Number(sIntegerStr),
connection: connection
});
}
if (way.match(/^last|after$/)) {
one = `${sqlTsSelect} >= ${open}`;
} else if (way.match(/^before$/)) {
one = `${sqlTsSelect} < ${open}`;
}
if (way.match(/^last$/)) {
two = ` AND ${sqlTsSelect} < ${close}`;
} else if (way.match(/^after$/) && forUnit) {
two = ` AND ${sqlTsSelect} < ${close}`;
} else if (way.match(/^before$/) && forUnit) {
two = ` AND ${sqlTsSelect} >= ${close}`;
} else if (way.match(/^before|after$/)) {
two = '';
}
ors.push(`(${one}` + `${two})`);
if (way.match(/^last$/)) {
let tsLastCompleteOption =
complete && plusCurrent
? common.FractionTsLastCompleteOptionEnum.CompletePlusCurrent
: complete
? common.FractionTsLastCompleteOptionEnum.Complete
: common.FractionTsLastCompleteOptionEnum.Incomplete;
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.TsIsInLast,
tsLastValue: Number(integerStr),
tsLastUnit: <any>unit,
tsLastCompleteOption: tsLastCompleteOption
});
} else if (way.match(/^before$/) && year) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.TsIsBeforeDate,
tsDateYear: Number(year),
tsDateMonth: Number(month),
tsDateDay: Number(day),
tsDateHour: Number(hour),
tsDateMinute: Number(minute),
tsForOption: forUnit
? common.FractionTsForOptionEnum.For
: common.FractionTsForOptionEnum.ForInfinity,
tsForValue: Number(forIntegerStr),
tsForUnit: <any>forUnit
});
} else if (way.match(/^before$/)) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.TsIsBeforeRelative,
tsRelativeValue: Number(integerStr),
tsRelativeUnit: <any>unit,
tsRelativeCompleteOption: complete
? common.FractionTsRelativeCompleteOptionEnum.Complete
: common.FractionTsRelativeCompleteOptionEnum.Incomplete,
tsRelativeWhenOption: when.match(/^ago$/)
? common.FractionTsRelativeWhenOptionEnum.Ago
: when.match(/^in\s+future$/)
? common.FractionTsRelativeWhenOptionEnum.InFuture
: undefined,
tsForOption: forUnit
? common.FractionTsForOptionEnum.For
: common.FractionTsForOptionEnum.ForInfinity,
tsForValue: Number(forIntegerStr),
tsForUnit: <any>forUnit
});
} else if (way.match(/^after$/) && year) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.TsIsAfterDate,
tsDateYear: Number(year),
tsDateMonth: Number(month),
tsDateDay: Number(day),
tsDateHour: Number(hour),
tsDateMinute: Number(minute),
tsForOption: forUnit
? common.FractionTsForOptionEnum.For
: common.FractionTsForOptionEnum.ForInfinity,
tsForValue: Number(forIntegerStr),
tsForUnit: <any>forUnit
});
} else if (way.match(/^after$/)) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.TsIsAfterRelative,
tsRelativeValue: Number(integerStr),
tsRelativeUnit: <any>unit,
tsRelativeCompleteOption: complete
? common.FractionTsRelativeCompleteOptionEnum.Complete
: common.FractionTsRelativeCompleteOptionEnum.Incomplete,
tsRelativeWhenOption: when.match(/^ago$/)
? common.FractionTsRelativeWhenOptionEnum.Ago
: when.match(/^in\s+future$/)
? common.FractionTsRelativeWhenOptionEnum.InFuture
: undefined,
tsForOption: forUnit
? common.FractionTsForOptionEnum.For
: common.FractionTsForOptionEnum.ForInfinity,
tsForValue: Number(forIntegerStr),
tsForUnit: <any>forUnit
});
}
// IS
// BETWEEN
// on (year)/(month)/(day) (hour):(minute) [to (year)/(month)/(day) (hour):(minute)]
} else if ((r = common.MyRegex.BRICK_TS_IS_BETWEEN_ON().exec(brick))) {
year = r[1];
month = r[2];
day = r[3];
hour = r[4];
minute = r[5];
toYear = r[6];
toMonth = r[7];
toDay = r[8];
toHour = r[9];
toMinute = r[10];
let open;
let close;
open = barTimestamp.makeTimestampOpenFromDateParts({
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
connection: connection
});
if (common.isUndefined(toYear)) {
close = barTimestamp.makeTimestampCloseBetween({
open: open,
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
connection: connection
});
} else {
// to
close = barTimestamp.makeTimestampCloseBetweenTo({
toYear: toYear,
toMonth: toMonth,
toDay: toDay,
toHour: toHour,
toMinute: toMinute,
connection: connection
});
}
ors.push(`(${sqlTsSelect} >= ${open} AND ${sqlTsSelect} < ${close})`);
if (toYear) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.TsIsInRange,
tsDateYear: Number(year),
tsDateMonth: Number(month),
tsDateDay: Number(day),
tsDateHour: Number(hour),
tsDateMinute: Number(minute),
tsDateToYear: Number(toYear),
tsDateToMonth: Number(toMonth),
tsDateToDay: Number(toDay),
tsDateToHour: Number(toHour),
tsDateToMinute: Number(toMinute)
});
} else if (minute) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.TsIsOnMinute,
tsDateYear: Number(year),
tsDateMonth: Number(month),
tsDateDay: Number(day),
tsDateHour: Number(hour),
tsDateMinute: Number(minute)
});
} else if (hour) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.TsIsOnHour,
tsDateYear: Number(year),
tsDateMonth: Number(month),
tsDateDay: Number(day),
tsDateHour: Number(hour)
});
} else if (day) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.TsIsOnDay,
tsDateYear: Number(year),
tsDateMonth: Number(month),
tsDateDay: Number(day)
});
} else if (month) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.TsIsOnMonth,
tsDateYear: Number(year),
tsDateMonth: Number(month)
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.TsIsOnYear,
tsDateYear: Number(year)
});
}
// IS NULL
// IS NOT NULL
} else if ((r = common.MyRegex.BRICK_IS_NULL().exec(brick))) {
not = r[1];
nullValue = r[2];
condition = `(${sqlTsSelect} IS NULL)`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.TsIsNotNull
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.TsIsNull
});
}
if (not && condition) {
nots.push(`NOT ${condition}`);
} else if (condition) {
ors.push(condition);
}
// IS ANY VALUE
} else if ((r = common.MyRegex.BRICK_IS_ANY_VALUE().exec(brick))) {
ors.push(constants.SQL_TRUE_CONDITION);
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.TsIsAnyValue
});
if (not && condition) {
nots.push(`NOT ${condition}`);
} else if (condition) {
ors.push(condition);
}
} else {
ors.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
}
} else if (result === common.FieldResultEnum.DayOfWeek) {
// IS
// IS NOT
if ((r = common.MyRegex.BRICK_DAY_OF_WEEK_IS().exec(brick))) {
not = r[1];
value = r[2];
condition = `UPPER(${proc}) = UPPER('${value}')`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.DayOfWeekIsNot,
dayOfWeekValue: <any>value
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.DayOfWeekIs,
dayOfWeekValue: <any>value
});
}
// IS NULL
// IS NOT NULL
} else if ((r = common.MyRegex.BRICK_IS_NULL().exec(brick))) {
not = r[1];
nullValue = r[2];
condition = `(${proc} IS NULL)`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.DayOfWeekIsNotNull
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.DayOfWeekIsNull
});
}
// IS ANY VALUE
} else if ((r = common.MyRegex.BRICK_IS_ANY_VALUE().exec(brick))) {
condition = constants.SQL_TRUE_CONDITION;
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.DayOfWeekIsAnyValue
});
}
// common for DayOfWeek
if (not && condition) {
nots.push(`NOT ${condition}`);
} else if (condition) {
ors.push(condition);
} else if (not) {
nots.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
} else {
ors.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
}
} else if (result === common.FieldResultEnum.DayOfWeekIndex) {
if ((r = common.MyRegex.BRICK_DAY_OF_WEEK_INDEX_IS_EQUAL().exec(brick))) {
not = r[1];
let equals = brick.split(',');
let dayOfWeekIndexValues: string[] = [];
equals.forEach(equal => {
if (answerError) {
return;
}
let eReg = common.MyRegex.BRICK_DAY_OF_WEEK_INDEX_EQUAL_TO();
let eR = eReg.exec(equal);
if (eR) {
num = eR[1];
}
if (not && num) {
notIns.push(num);
dayOfWeekIndexValues.push(num);
} else if (num) {
ins.push(num);
dayOfWeekIndexValues.push(num);
} else if (not) {
nots.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
} else {
ors.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
}
});
let dayOfWeekIndexValuesString = dayOfWeekIndexValues.join(', ');
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.DayOfWeekIndexIsNotEqualTo,
dayOfWeekIndexValues: dayOfWeekIndexValuesString
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.DayOfWeekIndexIsEqualTo,
dayOfWeekIndexValues: dayOfWeekIndexValuesString
});
}
} else {
// IS NULL
// IS NOT NULL
if ((r = common.MyRegex.BRICK_IS_NULL().exec(brick))) {
not = r[1];
nullValue = r[2];
condition = `(${proc} IS NULL)`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.DayOfWeekIndexIsNotNull
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.DayOfWeekIndexIsNull
});
}
// IS ANY VALUE
} else if ((r = common.MyRegex.BRICK_IS_ANY_VALUE().exec(brick))) {
condition = constants.SQL_TRUE_CONDITION;
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.DayOfWeekIndexIsAnyValue
});
}
// common for DayOfWeekIndex
if (not && condition) {
nots.push(`NOT ${condition}`);
} else if (condition) {
ors.push(condition);
} else if (not) {
nots.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
} else {
ors.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
}
}
} else if (result === common.FieldResultEnum.MonthName) {
// IS
// IS NOT
if ((r = common.MyRegex.BRICK_MONTH_NAME_IS().exec(brick))) {
not = r[1];
value = r[2];
condition = `UPPER(${proc}) = UPPER('${value}')`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.MonthNameIsNot,
monthNameValue: <any>value
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.MonthNameIs,
monthNameValue: <any>value
});
}
// IS NULL
// IS NOT NULL
} else if ((r = common.MyRegex.BRICK_IS_NULL().exec(brick))) {
not = r[1];
nullValue = r[2];
condition = `(${proc} IS NULL)`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.MonthNameIsNotNull
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.MonthNameIsNull
});
}
// IS ANY VALUE
} else if ((r = common.MyRegex.BRICK_IS_ANY_VALUE().exec(brick))) {
condition = constants.SQL_TRUE_CONDITION;
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.MonthNameIsAnyValue
});
}
// common for MonthName
if (not && condition) {
nots.push(`NOT ${condition}`);
} else if (condition) {
ors.push(condition);
} else if (not) {
nots.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
} else {
ors.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
}
} else if (result === common.FieldResultEnum.QuarterOfYear) {
// IS
// IS NOT
if ((r = common.MyRegex.BRICK_QUARTER_OF_YEAR_IS().exec(brick))) {
not = r[1];
value = r[2];
condition = `UPPER(${proc}) = UPPER('${value}')`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.QuarterOfYearIsNot,
quarterOfYearValue: <any>value
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.QuarterOfYearIs,
quarterOfYearValue: <any>value
});
}
// IS NULL
// IS NOT NULL
} else if ((r = common.MyRegex.BRICK_IS_NULL().exec(brick))) {
not = r[1];
nullValue = r[2];
condition = `(${proc} IS NULL)`;
if (not) {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.And,
type: common.FractionTypeEnum.QuarterOfYearIsNotNull
});
} else {
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.QuarterOfYearIsNull
});
}
// IS ANY VALUE
} else if ((r = common.MyRegex.BRICK_IS_ANY_VALUE().exec(brick))) {
condition = constants.SQL_TRUE_CONDITION;
fractions.push({
brick: brick,
operator: common.FractionOperatorEnum.Or,
type: common.FractionTypeEnum.QuarterOfYearIsAnyValue
});
}
// common for QuarterOfYear
if (not && condition) {
nots.push(`NOT ${condition}`);
} else if (condition) {
ors.push(condition);
} else if (not) {
nots.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
} else {
ors.push(constants.FAIL);
answerError = { valid: 0, brick: brick };
return;
}
}
});
if (answerError) {
return answerError;
}
return { valid: 1 };
} | the_stack |
import { TestCpuApi } from "../wa-interop/wa-api";
import { MemoryHelper } from "../wa-interop/memory-helpers";
import {
REG_AREA_INDEX,
CPU_STATE_BUFFER,
} from "../wa-interop/memory-map";
import { FlagsSetMask, Z80CpuState } from "../../cpu/Z80Cpu";
import { RunMode } from "../../../core/abstractions/vm-core-types";
const TEST_INPUT_BUFFER = 0x01000de3;
const IO_OPERATION_LOG = 0x01000ee3;
/**
* This class represents a test machine that can be used for testing the WA machine
*/
export class TestZ80Machine {
private _cpuStateBeforeRun: Z80CpuState;
private _memoryBeforeRun: Uint8Array;
/**
* Initializes a test machine
* @param cpuApi Module API obtained by the loader
*/
constructor(public cpuApi: TestCpuApi) {
this.cpuApi.resetMachine();
}
/**
* Resets the test machine
*/
reset(): void {
this.cpuApi.resetMachine();
this.cpuApi.resetCpu(true);
}
/**
* Initializes the machine with the specified code
* @param runMode Machine run mode
* @param code Intial code
*/
initCode(code: number[], runMode = RunMode.UntilEnd): Z80CpuState {
const mem = new Uint8Array(this.cpuApi.memory.buffer, 0, 0x1_0000);
let codeAddress = 0;
for (let i = 0; i < code.length; i++) {
mem[codeAddress++] = code[i];
}
this.cpuApi.prepareTest(runMode, codeAddress);
let ptr = codeAddress;
while (ptr < 0x10000) {
mem[ptr++] = 0;
}
// --- Init code execution
this.cpuApi.resetCpu(true);
return this.cpuState;
}
/**
* Initializes the input for a test machine run
* @param input List of input byte values
*/
initInput(input: number[]): void {
const mh = new MemoryHelper(this.cpuApi, TEST_INPUT_BUFFER);
for (let i = 0; i < input.length; i++) {
mh.writeByte(i, input[i]);
}
this.cpuApi.setTestInputLength(input.length);
}
/**
* Runs the injected code in test machine
*/
run(
state: Z80CpuState | null = null,
memory: Uint8Array | null = null
): Z80CpuState {
if (state !== null) {
this.cpuState = state;
}
if (memory !== null) {
this.memory = memory;
}
this._cpuStateBeforeRun = this.cpuState;
this._memoryBeforeRun = new Uint8Array(this.memory);
this.cpuApi.runTestCode();
return this.cpuState;
}
/**
* Gets the current CPU state of the test machine.
* @returns Test machine state
*/
get cpuState(): Z80CpuState {
const s = new Z80CpuState();
this.cpuApi.getCpuState();
// --- Get register data from the memory
let mh = new MemoryHelper(this.cpuApi, REG_AREA_INDEX);
s.af = mh.readUint16(0);
s.bc = mh.readUint16(2);
s.de = mh.readUint16(4);
s.hl = mh.readUint16(6);
s._af_ = mh.readUint16(8);
s._bc_ = mh.readUint16(10);
s._de_ = mh.readUint16(12);
s._hl_ = mh.readUint16(14);
s.pc = mh.readUint16(16);
s.sp = mh.readUint16(18);
s.i = mh.readByte(20);
s.r = mh.readByte(21);
s.ix = mh.readUint16(22);
s.iy = mh.readUint16(24);
s.wz = mh.readUint16(26);
mh = new MemoryHelper(this.cpuApi, CPU_STATE_BUFFER);
s.tactsInFrame = mh.readUint32(0);
s.tacts = mh.readUint32(4);
s.iff1 = mh.readBool(8);
s.iff2 = mh.readBool(9);
s.interruptMode = mh.readByte(10);
s.opCode = mh.readByte(11);
s.ddfdDepth = mh.readUint32(12);
s.useIx = mh.readBool(16);
s.cpuSignalFlags = mh.readUint32(17);
s.cpuSnoozed = mh.readBool(21);
s.intBacklog = mh.readUint32(22);
return s;
}
/**
* Sets the current CPU state of the test machine
* @param s New state to set
*/
set cpuState(s: Z80CpuState) {
let mh = new MemoryHelper(this.cpuApi, REG_AREA_INDEX);
mh.writeUint16(0, s.af);
mh.writeUint16(2, s.bc);
mh.writeUint16(4, s.de);
mh.writeUint16(6, s.hl);
mh.writeUint16(8, s._af_);
mh.writeUint16(10, s._bc_);
mh.writeUint16(12, s._de_);
mh.writeUint16(14, s._hl_);
mh.writeUint16(16, s.pc);
mh.writeUint16(18, s.sp);
mh.writeByte(20, s.i);
mh.writeByte(21, s.r);
mh.writeUint16(22, s.ix);
mh.writeUint16(24, s.iy);
mh.writeUint16(26, s.wz);
// --- Get state data
mh = new MemoryHelper(this.cpuApi, CPU_STATE_BUFFER);
mh.writeUint32(0, s.tactsInFrame);
mh.writeUint32(4, s.tacts);
mh.writeBool(8, s.iff1);
mh.writeBool(9, s.iff2);
mh.writeByte(10, s.interruptMode);
mh.writeByte(11, s.opCode);
mh.writeUint32(12, s.ddfdDepth);
mh.writeBool(16, s.useIx);
mh.writeUint32(17, s.cpuSignalFlags);
mh.writeBool(21, s.cpuSnoozed);
mh.writeUint32(22, s.intBacklog);
// --- Pass data to webAssembly
this.cpuApi.updateCpuState();
}
/**
* Gets the memory of the test machine
* @returns Test machine memory contents
*/
get memory(): Uint8Array {
const mem = new Uint8Array(this.cpuApi.memory.buffer, 0, 0x1_0000);
return new Uint8Array(mem);
}
/**
* Updates the memory contents of the test machine
*/
set memory(mem: Uint8Array) {
const memory = new Uint8Array(this.cpuApi.memory.buffer, 0, 0x1_0000);
for (let i = 0; i < mem.length; i++) {
memory[i] = mem[i];
}
}
/**
* Gets the memory access log of the test machine
*/
get ioAccessLog(): IoOp[] {
const mh = new MemoryHelper(this.cpuApi, IO_OPERATION_LOG);
const length = this.cpuApi.getIoLogLength();
const result: IoOp[] = [];
for (let i = 0; i < length; i++) {
const l = mh.readUint32(i * 4);
result.push({
address: l & 0xffff,
value: (l >> 16) & 0xff,
isOutput: ((l >> 24) & 0xff) !== 0,
});
}
return result;
}
// ==========================================================================
// Unit test helper methods
/**
* Checks if all registers keep their original values, except the ones
* listed in `except`
* @param except Names of registers that may change
*/
shouldKeepRegisters(except?: string): void {
const before = this._cpuStateBeforeRun;
const after = this.cpuState;
let exclude = except === undefined ? [] : except.split(",");
exclude = exclude.map((reg) => reg.toUpperCase().trim());
let differs: string[] = [];
if (before._af_ !== after._af_ && exclude.indexOf("AF'") < 0) {
differs.push("AF'");
}
if (before._bc_ !== after._bc_ && exclude.indexOf("BC'") < 0) {
differs.push("BC'");
}
if (before._de_ !== after._de_ && exclude.indexOf("DE'") < 0) {
differs.push("DE'");
}
if (before._hl_ !== after._hl_ && exclude.indexOf("HL'") < 0) {
differs.push("HL'");
}
if (
before.af !== after.af &&
!(
exclude.indexOf("AF") > -1 ||
exclude.indexOf("A") > -1 ||
exclude.indexOf("F") > -1
)
) {
differs.push("AF");
}
if (
before.bc !== after.bc &&
!(
exclude.indexOf("BC") > -1 ||
exclude.indexOf("B") > -1 ||
exclude.indexOf("C") > -1
)
) {
differs.push("BC");
}
if (
before.de !== after.de &&
!(
exclude.indexOf("DE") > -1 ||
exclude.indexOf("D") > -1 ||
exclude.indexOf("E") > -1
)
) {
differs.push("DE");
}
if (
before.hl !== after.hl &&
!(
exclude.indexOf("HL") > -1 ||
exclude.indexOf("H") > -1 ||
exclude.indexOf("L") > -1
)
) {
differs.push("HL");
}
if (before.sp !== after.sp && exclude.indexOf("SP") < 0) {
differs.push("SP");
}
if (before.ix !== after.ix && exclude.indexOf("IX") < 0) {
differs.push("IX");
}
if (before.iy !== after.iy && exclude.indexOf("IY") < 0) {
differs.push("IY");
}
if (
before.a !== after.a &&
exclude.indexOf("A") < 0 &&
exclude.indexOf("AF") < 0
) {
differs.push("A");
}
if (
before.f !== after.f &&
exclude.indexOf("F") < 0 &&
exclude.indexOf("AF") < 0
) {
differs.push("F");
}
if (
before.b !== after.b &&
exclude.indexOf("B") < 0 &&
exclude.indexOf("BC") < 0
) {
differs.push("B");
}
if (
before.c !== after.c &&
exclude.indexOf("C") < 0 &&
exclude.indexOf("BC") < 0
) {
differs.push("C");
}
if (
before.d !== after.d &&
exclude.indexOf("D") < 0 &&
exclude.indexOf("DE") < 0
) {
differs.push("D");
}
if (
before.e !== after.e &&
exclude.indexOf("E") < 0 &&
exclude.indexOf("DE") < 0
) {
differs.push("E");
}
if (
before.h !== after.h &&
exclude.indexOf("H") < 0 &&
exclude.indexOf("HL") < 0
) {
differs.push("H");
}
if (
before.l !== after.l &&
exclude.indexOf("L") < 0 &&
exclude.indexOf("HL") < 0
) {
differs.push("L");
}
if (differs.length === 0) {
return;
}
throw new Error(
"The following registers are expected to remain intact, " +
`but their values have been changed: ${differs.join(", ")}`
);
}
/**
* Tests if S flag keeps its value while running a test.
*/
shouldKeepSFlag(): void {
const before = (this._cpuStateBeforeRun.f & FlagsSetMask.S) !== 0;
const after = (this.cpuState.f & FlagsSetMask.S) !== 0;
if (after === before) {
return;
}
throw new Error(
`S flag expected to keep its value, but it changed from ${before} to ${after}`
);
}
/**
* Tests if Z flag keeps its value while running a test.
*/
shouldKeepZFlag(): void {
const before = (this._cpuStateBeforeRun.f & FlagsSetMask.Z) !== 0;
const after = (this.cpuState.f & FlagsSetMask.Z) !== 0;
if (after === before) {
return;
}
throw new Error(
`Z flag expected to keep its value, but it changed from ${before} to ${after}`
);
}
/**
* Tests if N flag keeps its value while running a test.
*/
shouldKeepNFlag(): void {
const before = (this._cpuStateBeforeRun.f & FlagsSetMask.N) !== 0;
const after = (this.cpuState.f & FlagsSetMask.N) !== 0;
if (after === before) {
return;
}
throw new Error(
`N flag expected to keep its value, but it changed from ${before} to ${after}`
);
}
/**
* Tests if PV flag keeps its value while running a test.
*/
shouldKeepPVFlag(): void {
const before = (this._cpuStateBeforeRun.f & FlagsSetMask.PV) !== 0;
const after = (this.cpuState.f & FlagsSetMask.PV) !== 0;
if (after === before) {
return;
}
throw new Error(
`PV flag expected to keep its value, but it changed from ${before} to ${after}`
);
}
/**
* Tests if H flag keeps its value while running a test.
*/
shouldKeepHFlag(): void {
const before = (this._cpuStateBeforeRun.f & FlagsSetMask.H) !== 0;
const after = (this.cpuState.f & FlagsSetMask.H) !== 0;
if (after === before) {
return;
}
throw new Error(
`PV flag expected to keep its value, but it changed from {before} to {after}`
);
}
/**
* Tests if C flag keeps its value while running a test.
*/
shouldKeepCFlag(): void {
const before = (this._cpuStateBeforeRun.f & FlagsSetMask.C) !== 0;
const after = (this.cpuState.f & FlagsSetMask.C) !== 0;
if (after === before) {
return;
}
throw new Error(
`C flag expected to keep its value, but it changed from ${before} to ${after}`
);
}
// Check if the machine's memory keeps its previous values, except
// the addresses and address ranges specified in <paramref name="except"/>
shouldKeepMemory(except?: string): void {
const cpu = this.cpuState;
const MAX_DEVS = 10;
const ranges: { From: number; To: number }[] = [];
const deviations: number[] = [];
// --- Parse ranges
let strRanges = except === undefined ? [] : except.split(",");
for (let i = 0; i < strRanges.length; i++) {
const range = strRanges[i];
const blocks = range.split("-");
let lower = 0xffff;
let upper = 0xffff;
if (blocks.length >= 1) {
lower = parseInt(blocks[0], 16);
upper = lower;
}
if (blocks.length >= 2) {
upper = parseInt(blocks[1], 16);
}
ranges.push({ From: lower, To: upper });
}
// --- Check each byte of memory, ignoring the stack
let upperMemoryBound = cpu.sp;
if (upperMemoryBound === 0) {
upperMemoryBound = 0x10000;
}
const memoryAfter = this.memory;
for (let idx = 0; idx < upperMemoryBound; idx++) {
if (memoryAfter[idx] === this._memoryBeforeRun[idx]) {
continue;
}
// --- Test allowed deviations
let found = ranges.some((range) => idx >= range.From && idx <= range.To);
if (found) {
continue;
}
// --- Report deviation
deviations.push(idx);
if (deviations.length >= MAX_DEVS) {
break;
}
}
if (deviations.length > 0) {
throw new Error(
"The following memory locations are expected to remain intact, " +
"but their values have been changed: " +
deviations.map((d) => d.toString(16)).join(", ")
);
}
}
}
/**
* Represents data in a particular I/O operation
*/
class IoOp {
address: number;
value: number;
isOutput: boolean;
}
/**
* Represents information for a TBBlue operation
*/
class TbBlueOp {
isIndex: boolean;
data: number;
} | the_stack |
import React, { useEffect, useState } from 'react';
import * as R from 'ramda';
import {
Panel,
PanelType,
TextField,
Toggle,
mergeStyles,
LayerHost,
PrimaryButton,
Stack,
Dropdown,
IDropdownOption,
Spinner,
ITextFieldProps,
IconButton,
Label,
Dialog,
DialogFooter,
Text,
Checkbox,
MessageBar,
MessageBarType,
getTheme,
} from '@fluentui/react';
import { useSelector, useDispatch } from 'react-redux';
import Axios from 'axios';
import { useLocation } from 'react-router-dom';
import { State } from 'RootStateType';
import {
checkSettingStatus,
updateNamespace,
updateKey,
thunkPostSetting,
patchIsCollectData,
thunkGetAllCvProjects,
} from '../store/setting/settingAction';
import { selectNonDemoProject, pullCVProjects } from '../store/trainingProjectSlice';
import { dummyFunction } from '../utils/dummyFunction';
import { WarningDialog } from './WarningDialog';
import { CreateProjectDialog } from './CreateProjectDialog';
type SettingPanelProps = {
isOpen: boolean;
onDismiss: () => void;
canBeDismissed: boolean;
showProjectDropdown: boolean;
openDataPolicyDialog: boolean;
};
const { palette } = getTheme();
const textFieldClass = mergeStyles({
width: 500,
});
const layerHostClass = mergeStyles({
position: 'absolute',
height: '100%',
width: '100%',
top: 0,
left: 0,
});
const MAIN_LAYER_HOST_ID = 'mainLayer';
export const SettingPanel: React.FC<SettingPanelProps> = ({
isOpen,
onDismiss,
canBeDismissed,
showProjectDropdown,
openDataPolicyDialog,
}) => {
const settingData = useSelector((state: State) => state.setting.current);
const cvProjectOptions = useSelector((state: State) =>
state.setting.cvProjects.map((e) => ({ key: e.id, text: e.name })),
);
const defaultCustomvisionId = useSelector((state: State) => {
const [selectedTrainingProject] = selectNonDemoProject(state);
return state.trainingProject.entities[selectedTrainingProject?.id]?.customVisionId;
});
const [selectedCustomvisionId, setselectedCustomvisionId] = useState(null);
const originSettingData = useSelector((state: State) => state.setting.origin);
const [loading, setloading] = useState(false);
const dontNeedUpdateOrSave = R.equals(settingData, originSettingData);
const [loadFullImages, setLoadFullImages] = useState(false);
const [loadImgWarning, setloadImgWarning] = useState(false);
const isCollectingData = useSelector((state: State) => state.setting.isCollectData);
const error = useSelector((state: State) => state.setting.error);
const location = useLocation();
const dispatch = useDispatch();
const onSave = async () => {
try {
await dispatch(thunkPostSetting());
} catch (e) {
alert(e);
}
};
const onDropdownChange = (_, option: IDropdownOption): void => {
setselectedCustomvisionId(option.key);
};
const onLoad = async () => {
setloading(true);
await dispatch(pullCVProjects({ selectedCustomvisionId, loadFullImages }));
window.location.reload();
setloading(false);
onDismiss();
};
const onLoadFullImgChange = (_, checked: boolean) => {
if (checked) setloadImgWarning(true);
else setLoadFullImages(checked);
};
const updateIsCollectData = (isCollectData, hasInit?): void => {
dispatch(patchIsCollectData({ id: settingData.id, isCollectData, hasInit }));
};
useEffect(() => {
dispatch(checkSettingStatus());
}, [dispatch]);
useEffect(() => {
setselectedCustomvisionId(defaultCustomvisionId);
}, [defaultCustomvisionId]);
useEffect(() => {
if (showProjectDropdown) dispatch(thunkGetAllCvProjects());
}, [dispatch, showProjectDropdown]);
const [gitSha1, setgitSha1] = useState('');
useEffect(() => {
// Could only get the file in production build
if (process.env.NODE_ENV === 'production') {
Axios.get('/static/git_sha1.txt')
.then((res) => {
setgitSha1(res.data);
return void 0;
})
.catch(alert);
}
}, []);
return (
<>
{isOpen && <LayerHost id={MAIN_LAYER_HOST_ID} className={layerHostClass} />}
<Panel
hasCloseButton={canBeDismissed}
headerText="Settings"
isOpen={isOpen}
type={PanelType.smallFluid}
onDismiss={onDismiss}
{...(!canBeDismissed && { onOuterClick: dummyFunction })}
layerProps={{
hostId: MAIN_LAYER_HOST_ID,
}}
isFooterAtBottom
onRenderFooterContent={() => (
<Text variant="small" styles={{ root: { color: palette.neutralTertiary } }}>
Version: {gitSha1}
</Text>
)}
>
<Stack tokens={{ childrenGap: 17 }}>
<h4>Azure Cognitive Services settings</h4>
<TextField
className={textFieldClass}
label="Endpoint"
required
value={settingData.namespace}
onChange={(_, value): void => {
dispatch(updateNamespace(value));
}}
onRenderLabel={(props) => <CustomLabel {...props} />}
/>
<TextField
className={textFieldClass}
label="Key"
required
value={settingData.key}
onChange={(_, value): void => {
dispatch(updateKey(value));
}}
/>
{error && <MessageBar messageBarType={MessageBarType.blocked}>{error.message}</MessageBar>}
<Stack.Item>
<WarningDialog
contentText={
<Text variant="large">
Update Key / Namespace will remove all the objects, sure you want to update?
</Text>
}
confirmButton="Yes"
onConfirm={onSave}
trigger={<PrimaryButton text="Save" disabled={dontNeedUpdateOrSave} />}
/>
</Stack.Item>
{showProjectDropdown && (
<>
<Dropdown
className={textFieldClass}
label="Project"
required
options={cvProjectOptions}
onChange={onDropdownChange}
selectedKey={selectedCustomvisionId}
calloutProps={{ calloutMaxHeight: 300 }}
/>
<CreateProjectDialog />
<Checkbox checked={loadFullImages} label="Load Full Images" onChange={onLoadFullImgChange} />
<WarningDialog
open={loadImgWarning}
contentText={
<Text variant="large">Depends on the number of images, loading full images takes time</Text>
}
onConfirm={() => {
setLoadFullImages(true);
setloadImgWarning(false);
}}
onCancel={() => setloadImgWarning(false)}
/>
<Stack horizontal tokens={{ childrenGap: 10 }}>
<PrimaryButton text="Load" disabled={loading} onClick={onLoad} />
{loading && <Spinner label="loading" />}
</Stack>
</>
)}
<Toggle
label="Allow sending usage data"
styles={{ root: { paddingTop: 50 } }}
checked={isCollectingData}
onChange={(_, checked) => updateIsCollectData(checked, true)}
/>
<WarningDialog
contentText={
<>
<h1 style={{ textAlign: 'center' }}>Data Collection Policy</h1>
<p>
The software may collect information about your use of the software and send it to
Microsoft. Microsoft may use this information to provide services and improve our products
and services. You may turn off the telemetry as described in the repository or clicking
settings on top right corner. Our privacy statement is located at{' '}
<a href="https://go.microsoft.com/fwlink/?LinkID=824704">
https://go.microsoft.com/fwlink/?LinkID=824704
</a>
. You can learn more about data collection and use in the help documentation and our privacy
statement. Your use of the software operates as your consent to these practices.
</p>
</>
}
open={openDataPolicyDialog}
confirmButton="I agree"
cancelButton="I don't agree"
onConfirm={(): void => updateIsCollectData(true, true)}
onCancel={(): void => updateIsCollectData(false, true)}
/>
</Stack>
</Panel>
</>
);
};
export const CustomLabel = (props: ITextFieldProps): JSX.Element => {
const [isModalOpen, setisModalOpen] = useState(false);
return (
<>
<Stack horizontal verticalAlign="center" tokens={{ childrenGap: 4 }}>
<Label required={props.required}>{props.label}</Label>
<IconButton iconProps={{ iconName: 'Info' }} onClick={() => setisModalOpen(true)} />
</Stack>
<Dialog
title="Get Endpoint and Key"
hidden={!isModalOpen}
modalProps={{ layerProps: { hostId: null } }}
maxWidth={800}
>
<Stack>
<p>
Step 1: Login Custom vision,{' '}
<a href="https://www.customvision.ai/" target="_blank" rel="noopener noreferrer">
https://www.customvision.ai/
</a>
</p>
<p>Step 2: Click on the setting icon on the top</p>
<img src="/icons/guide_step_2.png" style={{ width: '100%' }} />
<p>
Step 3: Choose the resources under the account, you will see information of "Key" and
"Endpoint"
</p>
<img src="/icons/guide_step_3.png" style={{ width: '100%' }} />
</Stack>
<DialogFooter>
<PrimaryButton text="Close" onClick={() => setisModalOpen(false)} />
</DialogFooter>
</Dialog>
</>
);
}; | the_stack |
import { IExecuteFunctions } from 'n8n-core';
import {
IDataObject,
INodeExecutionData,
INodeType,
INodeTypeDescription,
} from 'n8n-workflow';
import {
addConfigFields,
addFields,
cloneFields,
commitFields,
logFields,
pushFields,
tagFields,
} from './descriptions';
import simpleGit, {
LogOptions,
SimpleGit,
SimpleGitOptions,
} from 'simple-git';
import {
access,
mkdir,
} from 'fs/promises';
import { URL } from 'url';
export class Git implements INodeType {
description: INodeTypeDescription = {
displayName: 'Git',
name: 'git',
icon: 'file:git.svg',
group: ['transform'],
version: 1,
description: 'Control git.',
defaults: {
name: 'Git',
},
inputs: ['main'],
outputs: ['main'],
credentials: [
{
name: 'gitPassword',
required: true,
displayOptions: {
show: {
authentication: [
'gitPassword',
],
},
},
},
],
properties: [
{
displayName: 'Authentication',
name: 'authentication',
type: 'options',
options: [
{
name: 'Authenticate',
value: 'gitPassword',
},
{
name: 'None',
value: 'none',
},
],
displayOptions: {
show: {
operation: [
'clone',
'push',
],
},
},
default: 'none',
description: 'The way to authenticate.',
},
{
displayName: 'Operation',
name: 'operation',
type: 'options',
default: 'log',
description: 'Operation to perform',
options: [
{
name: 'Add',
value: 'add',
description: 'Add a file or folder to commit',
},
{
name: 'Add Config',
value: 'addConfig',
description: 'Add configuration property',
},
{
name: 'Clone',
value: 'clone',
description: 'Clone a repository',
},
{
name: 'Commit',
value: 'commit',
description: 'Commit files or folders to git',
},
{
name: 'Fetch',
value: 'fetch',
description: 'Fetch from remote repository',
},
{
name: 'List Config',
value: 'listConfig',
description: 'Return current configuration',
},
{
name: 'Log',
value: 'log',
description: 'Return git commit history',
},
{
name: 'Pull',
value: 'pull',
description: 'Pull from remote repository',
},
{
name: 'Push',
value: 'push',
description: 'Push to remote repository',
},
{
name: 'Push Tags',
value: 'pushTags',
description: 'Push Tags to remote repository',
},
{
name: 'Status',
value: 'status',
description: 'Return status of current repository',
},
{
name: 'Tag',
value: 'tag',
description: 'Create a new tag',
},
{
name: 'User Setup',
value: 'userSetup',
description: 'Set the user',
},
],
},
{
displayName: 'Repository Path',
name: 'repositoryPath',
type: 'string',
displayOptions: {
hide: {
operation: [
'clone',
],
},
},
default: '',
placeholder: '/tmp/repository',
required: true,
description: 'Local path of the git repository to operate on.',
},
{
displayName: 'New Repository Path',
name: 'repositoryPath',
type: 'string',
displayOptions: {
show: {
operation: [
'clone',
],
},
},
default: '',
placeholder: '/tmp/repository',
required: true,
description: 'Local path to which the git repository should be cloned into.',
},
...addFields,
...addConfigFields,
...cloneFields,
...commitFields,
...logFields,
...pushFields,
...tagFields,
// ...userSetupFields,
],
};
async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
const items = this.getInputData();
const prepareRepository = async (repositoryPath: string): Promise<string> => {
const authentication = this.getNodeParameter('authentication', 0) as string;
if (authentication === 'gitPassword') {
const gitCredentials = await this.getCredentials('gitPassword') as IDataObject;
const url = new URL(repositoryPath);
url.username = gitCredentials.username as string;
url.password = gitCredentials.password as string;
return url.toString();
}
return repositoryPath;
};
const operation = this.getNodeParameter('operation', 0) as string;
let item: INodeExecutionData;
const returnItems: INodeExecutionData[] = [];
for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
try {
item = items[itemIndex];
const repositoryPath = this.getNodeParameter('repositoryPath', itemIndex, '') as string;
const options = this.getNodeParameter('options', itemIndex, {}) as IDataObject;
if (operation === 'clone') {
// Create repository folder if it does not exist
try {
await access(repositoryPath);
} catch (error) {
await mkdir(repositoryPath);
}
}
const gitOptions: Partial<SimpleGitOptions> = {
baseDir: repositoryPath,
};
const git: SimpleGit = simpleGit(gitOptions)
// Tell git not to ask for any information via the terminal like for
// example the username. As nobody will be able to answer it would
// n8n keep on waiting forever.
.env('GIT_TERMINAL_PROMPT', '0');
if (operation === 'add') {
// ----------------------------------
// add
// ----------------------------------
const pathsToAdd = this.getNodeParameter('pathsToAdd', itemIndex, '') as string;
await git.add(pathsToAdd.split(','));
returnItems.push({ json: { success: true } });
} else if (operation === 'addConfig') {
// ----------------------------------
// addConfig
// ----------------------------------
const key = this.getNodeParameter('key', itemIndex, '') as string;
const value = this.getNodeParameter('value', itemIndex, '') as string;
let append = false;
if (options.mode === 'append') {
append = true;
}
await git.addConfig(key, value, append);
returnItems.push({ json: { success: true } });
} else if (operation === 'clone') {
// ----------------------------------
// clone
// ----------------------------------
let sourceRepository = this.getNodeParameter('sourceRepository', itemIndex, '') as string;
sourceRepository = await prepareRepository(sourceRepository);
await git.clone(sourceRepository, '.');
returnItems.push({ json: { success: true } });
} else if (operation === 'commit') {
// ----------------------------------
// commit
// ----------------------------------
const message = this.getNodeParameter('message', itemIndex, '') as string;
let pathsToAdd: string[] | undefined = undefined;
if (options.files !== undefined) {
pathsToAdd = (options.pathsToAdd as string).split(',');
}
await git.commit(message, pathsToAdd);
returnItems.push({ json: { success: true } });
} else if (operation === 'fetch') {
// ----------------------------------
// fetch
// ----------------------------------
await git.fetch();
returnItems.push({ json: { success: true } });
} else if (operation === 'log') {
// ----------------------------------
// log
// ----------------------------------
const logOptions: LogOptions = {};
const returnAll = this.getNodeParameter('returnAll', itemIndex, false) as boolean;
if (returnAll === false) {
logOptions.maxCount = this.getNodeParameter('limit', itemIndex, 100) as number;
}
if (options.file) {
logOptions.file = options.file as string;
}
const log = await git.log(logOptions);
// @ts-ignore
returnItems.push(...this.helpers.returnJsonArray(log.all));
} else if (operation === 'pull') {
// ----------------------------------
// pull
// ----------------------------------
await git.pull();
returnItems.push({ json: { success: true } });
} else if (operation === 'push') {
// ----------------------------------
// push
// ----------------------------------
if (options.repository) {
const targetRepository = await prepareRepository(options.targetRepository as string);
await git.push(targetRepository);
} else {
const authentication = this.getNodeParameter('authentication', 0) as string;
if (authentication === 'gitPassword') {
// Try to get remote repository path from git repository itself to add
// authentication data
const config = await git.listConfig();
let targetRepository;
for (const fileName of Object.keys(config.values)) {
if (config.values[fileName]['remote.origin.url']) {
targetRepository = config.values[fileName]['remote.origin.url'];
break;
}
}
targetRepository = await prepareRepository(targetRepository as string);
await git.push(targetRepository);
} else {
await git.push();
}
}
returnItems.push({ json: { success: true } });
} else if (operation === 'pushTags') {
// ----------------------------------
// pushTags
// ----------------------------------
await git.pushTags();
returnItems.push({ json: { success: true } });
} else if (operation === 'listConfig') {
// ----------------------------------
// listConfig
// ----------------------------------
const config = await git.listConfig();
const data = [];
for (const fileName of Object.keys(config.values)) {
data.push({
_file: fileName,
...config.values[fileName],
});
}
// @ts-ignore
returnItems.push(...this.helpers.returnJsonArray(data));
} else if (operation === 'status') {
// ----------------------------------
// status
// ----------------------------------
const status = await git.status();
// @ts-ignore
returnItems.push(...this.helpers.returnJsonArray([status]));
} else if (operation === 'tag') {
// ----------------------------------
// tag
// ----------------------------------
const name = this.getNodeParameter('name', itemIndex, '') as string;
await git.addTag(name);
returnItems.push({ json: { success: true } });
}
} catch (error) {
if (this.continueOnFail()) {
returnItems.push({ json: { error: error.toString() } });
continue;
}
throw error;
}
}
return this.prepareOutputData(returnItems);
}
} | the_stack |
declare module "pg-query-native-latest" {
type NodeLocation = { start: number; end: number };
export interface RawStmtDef {
stmt: StmtNode;
/**
* If not present, assume zero.
*/
stmt_location?: number;
/**
* The distance between the end of the previous statement and the end of the
* semicolon for this statement (I think).
*/
stmt_len: number;
}
export type RawStmtNode = { RawStmt: RawStmtDef } & NodeLocation;
export interface A_ExprDef {
[key: string]: any /* TODO */;
}
export type A_ExprNode = { A_Expr: A_ExprDef } & NodeLocation;
export interface AliasDef {
[key: string]: any /* TODO */;
}
export type AliasNode = { Alias: AliasDef } & NodeLocation;
export interface A_ArrayExprDef {
[key: string]: any /* TODO */;
}
export type A_ArrayExprNode = { A_ArrayExpr: A_ArrayExprDef } & NodeLocation;
export interface A_ConstDef {
[key: string]: any /* TODO */;
}
export type A_ConstNode = { A_Const: A_ConstDef } & NodeLocation;
export interface A_IndicesDef {
[key: string]: any /* TODO */;
}
export type A_IndicesNode = { A_Indices: A_IndicesDef } & NodeLocation;
export interface A_IndirectionDef {
[key: string]: any /* TODO */;
}
export type A_IndirectionNode = {
A_Indirection: A_IndirectionDef;
} & NodeLocation;
export interface A_StarDef {
[key: string]: any /* TODO */;
}
export type A_StarNode = { A_Star: A_StarDef } & NodeLocation;
export interface BitStringDef {
[key: string]: any /* TODO */;
}
export type BitStringNode = { BitString: BitStringDef } & NodeLocation;
export interface BoolExprDef {
[key: string]: any /* TODO */;
}
export type BoolExprNode = { BoolExpr: BoolExprDef } & NodeLocation;
export interface BooleanTestDef {
[key: string]: any /* TODO */;
}
export type BooleanTestNode = { BooleanTest: BooleanTestDef } & NodeLocation;
export interface CaseExprDef {
[key: string]: any /* TODO */;
}
export type CaseExprNode = { CaseExpr: CaseExprDef } & NodeLocation;
export interface CoalesceExprDef {
[key: string]: any /* TODO */;
}
export type CoalesceExprNode = {
CoalesceExpr: CoalesceExprDef;
} & NodeLocation;
export interface CollateClauseDef {
[key: string]: any /* TODO */;
}
export type CollateClauseNode = {
CollateClause: CollateClauseDef;
} & NodeLocation;
export interface ColumnDefDef {
[key: string]: any /* TODO */;
}
export type ColumnDefNode = { ColumnDef: ColumnDefDef } & NodeLocation;
export interface ColumnRefDef {
[key: string]: any /* TODO */;
}
export type ColumnRefNode = { ColumnRef: ColumnRefDef } & NodeLocation;
export interface CommonTableExprDef {
[key: string]: any /* TODO */;
}
export type CommonTableExprNode = {
CommonTableExpr: CommonTableExprDef;
} & NodeLocation;
export interface FloatDef {
[key: string]: any /* TODO */;
}
export type FloatNode = { Float: FloatDef } & NodeLocation;
export interface FuncCallDef {
[key: string]: any /* TODO */;
}
export type FuncCallNode = { FuncCall: FuncCallDef } & NodeLocation;
export interface GroupingFuncDef {
[key: string]: any /* TODO */;
}
export type GroupingFuncNode = {
GroupingFunc: GroupingFuncDef;
} & NodeLocation;
export interface GroupingSetDef {
[key: string]: any /* TODO */;
}
export type GroupingSetNode = { GroupingSet: GroupingSetDef } & NodeLocation;
export interface IntegerDef {
[key: string]: any /* TODO */;
}
export type IntegerNode = { Integer: IntegerDef } & NodeLocation;
export interface IntoClauseDef {
[key: string]: any /* TODO */;
}
export type IntoClauseNode = { IntoClause: IntoClauseDef } & NodeLocation;
export interface JoinExprDef {
[key: string]: any /* TODO */;
}
export type JoinExprNode = { JoinExpr: JoinExprDef } & NodeLocation;
export interface LockingClauseDef {
[key: string]: any /* TODO */;
}
export type LockingClauseNode = {
LockingClause: LockingClauseDef;
} & NodeLocation;
export interface MinMaxExprDef {
[key: string]: any /* TODO */;
}
export type MinMaxExprNode = { MinMaxExpr: MinMaxExprDef } & NodeLocation;
export interface NamedArgExprDef {
[key: string]: any /* TODO */;
}
export type NamedArgExprNode = {
NamedArgExpr: NamedArgExprDef;
} & NodeLocation;
export interface NullDef {
[key: string]: any /* TODO */;
}
export type NullNode = { Null: NullDef } & NodeLocation;
export interface NullTestDef {
[key: string]: any /* TODO */;
}
export type NullTestNode = { NullTest: NullTestDef } & NodeLocation;
export interface ParamRefDef {
[key: string]: any /* TODO */;
}
export type ParamRefNode = { ParamRef: ParamRefDef } & NodeLocation;
export interface RangeFunctionDef {
[key: string]: any /* TODO */;
}
export type RangeFunctionNode = {
RangeFunction: RangeFunctionDef;
} & NodeLocation;
export interface RangeSubselectDef {
[key: string]: any /* TODO */;
}
export type RangeSubselectNode = {
RangeSubselect: RangeSubselectDef;
} & NodeLocation;
export interface RangeTableSampleDef {
[key: string]: any /* TODO */;
}
export type RangeTableSampleNode = {
RangeTableSample: RangeTableSampleDef;
} & NodeLocation;
export interface RangeVarDef {
[key: string]: any /* TODO */;
}
export type RangeVarNode = { RangeVar: RangeVarDef } & NodeLocation;
export interface ResTargetDef {
[key: string]: any /* TODO */;
}
export type ResTargetNode = { ResTarget: ResTargetDef } & NodeLocation;
export interface RowExprDef {
[key: string]: any /* TODO */;
}
export type RowExprNode = { RowExpr: RowExprDef } & NodeLocation;
export interface SelectStmtDef {
[key: string]: any /* TODO */;
}
export type SelectStmtNode = { SelectStmt: SelectStmtDef } & NodeLocation;
export interface CreateStmtDef {
[key: string]: any /* TODO */;
}
export type CreateStmtNode = { CreateStmt: CreateStmtDef } & NodeLocation;
export interface ConstraintStmtDef {
[key: string]: any /* TODO */;
}
export type ConstraintStmtNode = {
ConstraintStmt: ConstraintStmtDef;
} & NodeLocation;
export interface ReferenceConstraintDef {
[key: string]: any /* TODO */;
}
export type ReferenceConstraintNode = {
ReferenceConstraint: ReferenceConstraintDef;
} & NodeLocation;
export interface ExclusionConstraintDef {
[key: string]: any /* TODO */;
}
export type ExclusionConstraintNode = {
ExclusionConstraint: ExclusionConstraintDef;
} & NodeLocation;
export interface ConstraintDef {
[key: string]: any /* TODO */;
}
export type ConstraintNode = { Constraint: ConstraintDef } & NodeLocation;
export interface FunctionParameterDef {
[key: string]: any /* TODO */;
}
export type FunctionParameterNode = {
FunctionParameter: FunctionParameterDef;
} & NodeLocation;
export interface CreateFunctionStmtDef {
[key: string]: any /* TODO */;
}
export type CreateFunctionStmtNode = {
CreateFunctionStmt: CreateFunctionStmtDef;
} & NodeLocation;
export interface CreateSchemaStmtDef {
[key: string]: any /* TODO */;
}
export type CreateSchemaStmtNode = {
CreateSchemaStmt: CreateSchemaStmtDef;
} & NodeLocation;
export interface TransactionStmtDef {
[key: string]: any /* TODO */;
}
export type TransactionStmtNode = {
TransactionStmt: TransactionStmtDef;
} & NodeLocation;
export interface SortByDef {
[key: string]: any /* TODO */;
}
export type SortByNode = { SortBy: SortByDef } & NodeLocation;
export interface StringDef {
[key: string]: any /* TODO */;
}
export type StringNode = { String: StringDef } & NodeLocation;
export interface SubLinkDef {
[key: string]: any /* TODO */;
}
export type SubLinkNode = { SubLink: SubLinkDef } & NodeLocation;
export interface TypeCastDef {
[key: string]: any /* TODO */;
}
export type TypeCastNode = { TypeCast: TypeCastDef } & NodeLocation;
export interface TypeNameDef {
[key: string]: any /* TODO */;
}
export type TypeNameNode = { TypeName: TypeNameDef } & NodeLocation;
export interface CaseWhenDef {
[key: string]: any /* TODO */;
}
export type CaseWhenNode = { CaseWhen: CaseWhenDef } & NodeLocation;
export interface WindowDefDef {
[key: string]: any /* TODO */;
}
export type WindowDefNode = { WindowDef: WindowDefDef } & NodeLocation;
export interface WithClauseDef {
[key: string]: any /* TODO */;
}
export type WithClauseNode = { WithClause: WithClauseDef } & NodeLocation;
export interface DefElemDef {
[key: string]: any /* TODO */;
}
export type DefElemNode = { DefElem: DefElemDef } & NodeLocation;
export type ExprNode =
| A_ExprNode
| A_ArrayExprNode
| BoolExprNode
| CaseExprNode
| CoalesceExprNode
| CommonTableExprNode
| JoinExprNode
| MinMaxExprNode
| NamedArgExprNode
| RowExprNode;
export type StmtNode =
| RawStmtNode
| SelectStmtNode
| CreateStmtNode
| ConstraintStmtNode
| CreateFunctionStmtNode
| CreateSchemaStmtNode
| TransactionStmtNode;
export type PGNode =
| RawStmtNode
| A_ExprNode
| AliasNode
| A_ArrayExprNode
| A_ConstNode
| A_IndicesNode
| A_IndirectionNode
| A_StarNode
| BitStringNode
| BoolExprNode
| BooleanTestNode
| CaseExprNode
| CoalesceExprNode
| CollateClauseNode
| ColumnDefNode
| ColumnRefNode
| CommonTableExprNode
| FloatNode
| FuncCallNode
| GroupingFuncNode
| GroupingSetNode
| IntegerNode
| IntoClauseNode
| JoinExprNode
| LockingClauseNode
| MinMaxExprNode
| NamedArgExprNode
| NullNode
| NullTestNode
| ParamRefNode
| RangeFunctionNode
| RangeSubselectNode
| RangeTableSampleNode
| RangeVarNode
| ResTargetNode
| RowExprNode
| SelectStmtNode
| CreateStmtNode
| ConstraintStmtNode
| ReferenceConstraintNode
| ExclusionConstraintNode
| ConstraintNode
| FunctionParameterNode
| CreateFunctionStmtNode
| CreateSchemaStmtNode
| TransactionStmtNode
| SortByNode
| StringNode
| SubLinkNode
| TypeCastNode
| TypeNameNode
| CaseWhenNode
| WindowDefNode
| WithClauseNode
| DefElemNode;
export interface ParseResult {
query: RawStmtNode[];
error: Error | null;
stderr: string;
}
export function parse(sql: string): ParseResult;
} | the_stack |
"use strict";
// uuid: 4293b25a-0b5f-4af9-8dd7-a351ff686908
// ------------------------------------------------------------------------
// Copyright (c) 2018 Alexandre Bento Freire. All rights reserved.
// Licensed under the MIT License+uuid License. See License.txt for details
// ------------------------------------------------------------------------
import * as globule from "globule";
import * as yaml from "js-yaml";
import * as sysFs from "fs";
import * as sysPath from "path";
import { fsix } from "../vendor/fsix.js";
import { DevCfg } from "../dev-config.js";
import * as versionLib from '../version.js';
/** @module developer | This module won't be part of release version */
/**
* ## Description
*
* Builds documentation files from the code.
*
* usage: `gulp build-docs-latest`
*
* Uses the following grammar:
*
* ```
* // @module <type> | <description text>
* <empty line>
* /**
* * <documentation-line-1>
* * ...
* * <documentation-line-n>
* *<end slash>
* ```
*
* If a line ends with any of the following signs `\.\`":` and is followed by another line starting with a character,
* it automatically adds 2 spaces at the line ending.
*
*/
export namespace BuildDocsLatest {
const EMPTY = ['', '', '', '', '', '', '', '', '', ''];
const MARKDOWN_FOLDER = 'docs';
export const API_FOLDER = 'api';
export const EN_LAST_VERSION_PATH = 'en';
type LocalWebLinks = (key: string, title: string) => string;
let badgeLine = '';
export const getTargets = (cfg: DevCfg.DevConfig) => [
{
id: 'end-user',
name: 'End User',
dstPath: cfg.paths.DOCS_LATEST_END_USER_PATH,
sourcePaths: [cfg.paths.DOCS_SOURCE_PATH],
moduleTypes: ['end-user'],
indexFile: './README.md',
isEndUser: true,
logFile: './build-docs-latest-end-user.log',
processIndexPage: (data: string) => {
return data
.replace(/^(.*)developer-badge\.gif(.*)$/m, (all, p1, p2) => {
badgeLine = all;
return p1 + 'end-user-badge.gif' + p2;
})
.replace(new RegExp(`${cfg.webLinks.webDomain}/`, 'g'), '/');
},
},
{
id: 'dev',
name: 'Developer',
dstPath: cfg.paths.DOCS_LATEST_DEVELOPER_PATH,
sourcePaths: [cfg.paths.DOCS_SOURCE_PATH, cfg.paths.DOCS_SOURCE_DEV_PATH],
moduleTypes: ['end-user', 'developer', 'internal'],
indexFile: `${cfg.paths.DOCS_SOURCE_PATH}-dev/README.md`,
isEndUser: false,
logFile: './build-docs-latest-dev.log',
processIndexPage: (data: string) => {
return data.replace(/^(# Description.*)$/m, (all) => {
if (!badgeLine) {
throw `end-user should had been processed already.`;
}
return all + '\n' + badgeLine + ' \n';
});
},
},
];
// ------------------------------------------------------------------------
// LogData
// ------------------------------------------------------------------------
interface Log {
notFound: string[];
found: string[];
generated: string[];
refs: {};
}
// ------------------------------------------------------------------------
// ReferenceBuilder
// ------------------------------------------------------------------------
/** Converts a text to a Markdown reference */
function textToRef(text: string): string {
return text.toLowerCase().replace(/ /g, '-').replace(/[^_a-z\-]/g, '');
}
/**
* Processes all output Markdown files, by scanning all the local links and
* filling the missing details.
*/
class ReferenceBuilder {
refs: { [ref: string]: string } = {};
constructor(public log: Log) { }
/** Stage 0. Generate references from the filename and headers */
private buildRefs(fileBase: string, content: string): void {
this.refs[textToRef(fileBase)] = `${fileBase}.md`;
content.replace(/^#+\s*(.+)\s*$/mg, (all, text) => {
const ref = textToRef(text);
const fullRef = `${fileBase}.md#${ref}`;
this.refs[ref] = fullRef;
this.refs[fullRef] = fullRef;
this.refs[`${fileBase}#${ref}`] = fullRef;
return all;
});
}
/** Processes the links from Markdown content, updating its content */
private updateLinks(fileBase: string, content: string): string {
return content.replace(/\[([^\]]*)\]\(([\w\-\s]*)(?:#([\w\-\s]*))?\)/g,
(_app, info, link, bookmark) => {
bookmark = bookmark || '';
link = link || '';
if (!info) {
info = bookmark || link;
}
const refBookmark = textToRef(bookmark || '');
const refLink = textToRef(link || fileBase);
let tracedLink;
if (refBookmark) {
tracedLink = this.refs[refLink + '#' + refBookmark] ||
this.refs[refBookmark];
} else {
tracedLink = this.refs[refLink];
}
if (!tracedLink) {
this.log.notFound.push(`${link}#${bookmark} in ${fileBase}`);
} else {
this.log.found.push(`${link}#${bookmark} in ${fileBase} = ${tracedLink}`);
[link, bookmark] = tracedLink.split('#');
}
return `[${info}](${link}${bookmark ? '#' + bookmark : ''})`;
});
}
/** Main entry point. Reads the files and calls appropriate action. */
build(path: string): void {
const fileBases = sysFs.readdirSync(path)
.filter(file => file.endsWith('.md')).map(file => file.replace(/\.md$/, ''));
[0, 1].forEach(stage => {
fileBases.forEach(fileBase => {
const fileName = `${path}/${fileBase}.md`;
const content = fsix.readUtf8Sync(fileName);
if (stage === 0) {
this.buildRefs(fileBase, content);
} else {
sysFs.writeFileSync(fileName, this.updateLinks(fileBase, content));
}
});
});
this.log.refs = this.refs;
}
}
// ------------------------------------------------------------------------
// DocParser
// ------------------------------------------------------------------------
const enum DocIdType {
EnumName,
TypeName,
ConstName,
FunctionName,
InterfaceName,
ClassName,
MethodName,
PropertyName,
GetterName,
SetterName,
ConstructorName,
}
/* enum ModuleType {
unknown,
developer,
internal,
shared,
'end-user',
} */
const BadgeNameOfDocIdType = [
"enum",
"type",
"const",
"function",
"interface",
"class",
"method",
"property",
"getter",
"setter",
"constructor",
];
const IdTypeAreFunctions = [DocIdType.FunctionName, DocIdType.MethodName];
const IdTypeAreSections = [
DocIdType.EnumName, DocIdType.ConstName, DocIdType.TypeName,
DocIdType.InterfaceName,
DocIdType.ClassName, DocIdType.FunctionName,
];
class DocParser {
outLines: string[] = [];
private inpLineNr: uint;
private inpLineCount: uint;
private inpLines: string[] = [];
private jsDocs: string[] = [];
private outerSpaces: string;
private innerSpaces: string;
// private isReadOnly: boolean = false;
private isInsideClassOrInterface = false;
private classOrInterfaceName = '';
private disabledClassOrInterface = false;
private isInterface = false;
private links: string[] = [];
private lastJsDocsLineNr = 0;
private lastPeekLineNr = 0;
constructor(private localWebLinks: LocalWebLinks,
private isEndUser: boolean) { }
private getLine(peekOnly: boolean = false): string {
const res = this.inpLines[this.inpLineNr] || '';
if (!peekOnly) {
this.inpLineNr++;
} else {
this.lastPeekLineNr = this.inpLineNr;
}
return res;
}
private isFinished = () => this.inpLineNr >= this.inpLineCount;
private _processDefContent(line: string, scanForComma: boolean): string {
line = line.trim();
const line1 = line;
let securityLineCount = 0;
do {
if (securityLineCount > 150) {
console.log(`too many lines ${scanForComma ? 'YES' : 'NO'}:\n${line1}\n${line}`);
return 'ERROR';
}
const matches = line.match(scanForComma ?
/((?:.|\n)+\S)\s*;\s*$/ :
/^([^{]*\S)\s*\{/);
if (matches) {
return matches[1] + ';';
}
line = line + '\n' + this.getLine();
securityLineCount++;
} while (true);
}
private _allowId(id: string, _idType: DocIdType,
accessTag: string, exportTag: string | undefined): boolean {
return (!this.isEndUser)
|| (id[0] !== '_' && accessTag === 'public'
&& (this.isInsideClassOrInterface || exportTag !== undefined));
}
private _processAccessTag(accessTag?): string {
return accessTag ? accessTag.trim() : 'public';
}
private _prepareBadges(id: string, idType: DocIdType, badges: string[],
accessTag: string, exportTag: string | undefined): string[] {
badges.push(accessTag);
if (exportTag) { badges.push(exportTag); }
if (!this.isEndUser && id.startsWith('_')) { badges.push('internal'); }
badges = (badges || [])
.filter(badge => badge !== undefined)
.map(badge => badge.trim());
badges.push(BadgeNameOfDocIdType[idType]);
return badges;
}
private addId(id: string, idType: DocIdType,
line: string, badges: string[],
accessTag?: string, exportTag?: string): boolean {
const svJsDocs = this.jsDocs;
this.jsDocs = [];
// this.isReadOnly = false;
accessTag = this._processAccessTag(accessTag);
badges = this._prepareBadges(id, idType, badges, accessTag, exportTag);
if (!this._allowId(id, idType, accessTag, exportTag)) {
return false;
}
this.outLines.push(
`##${IdTypeAreSections.indexOf(idType) !== -1 ? '' : '#'} `
+ `${this.classOrInterfaceName ? this.classOrInterfaceName + '.' : ''}`
+ `${id}${IdTypeAreFunctions.indexOf(idType) !== -1 ? '()' : ''}\n`);
if (this.classOrInterfaceName) {
this.links.push(this.classOrInterfaceName);
}
this.outLines.push(badges
.map(badge => `<span class="code-badge badge-${badge}">${badge}</span>`)
.join(' ')
+ ' ' + this.links.map(link => `[[${link}](${link})]`).join(' ')
+ ' ');
this.links = [];
this.outLines.push('```js\n' + line.trimLeft() + '\n```\n');
if (svJsDocs.length && this.lastJsDocsLineNr === this.lastPeekLineNr) {
const formattedJsDocs = formatJsDocsMarkdown(svJsDocs.join('\n'), this.localWebLinks);
this.outLines.push(formattedJsDocs);
} else {
}
return true;
}
private parseJsDocs(): void {
this.lastJsDocsLineNr = -1;
if (this.getLine(true).match(/^\s*\/\*\*/)) {
this.jsDocs = [];
let done: boolean;
do {
let line = this.getLine();
done = line.length === 0;
line = line.replace(/\s*\*\/\s*$/, () => {
done = true;
return '';
});
// removes the @readonly line
line = line.replace(/\s*\*\s*#end-user\s+@readonly\s*/, () => {
// this.isReadOnly = true;
return '';
});
// removes the start comment marker
line = line.replace(/^\s*\/?\*{1,2}\s?/, '');
this.jsDocs.push(line);
} while (!done);
this.lastJsDocsLineNr = this.inpLineNr;
}
}
private parseMethodsAndProperties(): void {
if (this.disabledClassOrInterface) {
return;
}
const [, spaces, accessTag, abstractTag, readonlyTag, getterTag, setterTag,
id, parenthesisTag] = this.getLine(true)
.match(
/^(\s*)(protected\s+|private\s+|public\s+)?(abstract\s+)?(readonly\s+)?(get\s+)?(set\s+)?(\w+)(\s*\()?/,
) || EMPTY;
if (spaces === this.innerSpaces) {
let idType: DocIdType = DocIdType.PropertyName;
if (parenthesisTag) {
if (getterTag) {
idType = DocIdType.GetterName;
} else if (setterTag) {
idType = DocIdType.SetterName;
} else if (id === 'constructor') {
idType = DocIdType.ConstructorName;
} else {
idType = DocIdType.MethodName;
}
}
this.addId(id, idType,
this._processDefContent(this.getLine(),
idType === DocIdType.PropertyName || this.isInterface
|| abstractTag !== undefined),
[abstractTag, readonlyTag], accessTag);
}
}
private parseInterfaceOrClass(): boolean {
const [, spaces, exportTag, abstractTag, idTypeTag, id] = this.getLine(true)
.match(/^(\s*)(?:(export)\s+)?(abstract\s+)?(interface\s+|class\s+)(\w+)/)
|| EMPTY;
if (spaces === this.outerSpaces) {
let line = this.getLine();
line = line.replace(/\s*\{?\s*\}?\s*$/, '{ }');
const idType = idTypeTag[0] === 'i'
? DocIdType.InterfaceName : DocIdType.ClassName;
this.disabledClassOrInterface = this.isEndUser
&& (!exportTag || !this._allowId(id, idType, 'public', exportTag));
if (!this.disabledClassOrInterface) {
this.outLines.push('<div class=class-interface-header> </div>');
this.addId(id, idType, line, [abstractTag], undefined, exportTag);
}
this.isInsideClassOrInterface = true;
this.classOrInterfaceName = id;
this.isInterface = idTypeTag.startsWith('interface');
return true;
}
return false;
}
private parseEndOfClassOrInterface(): void {
const [, spaces] = this.getLine(true)
.match(/^(\s*)}/) || EMPTY;
if (spaces === this.outerSpaces) {
this.isInsideClassOrInterface = false;
this.classOrInterfaceName = '';
}
}
private parseFunction(): void {
const [, spaces, exportTag, id] = this.getLine(true)
.match(/^(\s*)(export\s+)?function\s+(\w+)\b/) || EMPTY;
if (spaces === this.outerSpaces) {
let line = this.getLine();
this.addId(id, DocIdType.FunctionName,
this._processDefContent(line, false), [], undefined, exportTag);
while (true) {
line = this.getLine();
const [, endSpaces] = line.match(/^(\s*)\}\s*$/) || EMPTY;
if (endSpaces === this.outerSpaces) {
break;
}
}
}
}
private parseType(): void {
const [, spaces, exportTag, id] = this.getLine(true)
.match(/^(\s*)(export\s+)?type\s+(\w+)\b/) || EMPTY;
if (spaces === this.outerSpaces) {
this.addId(id, DocIdType.TypeName,
this._processDefContent(this.getLine(), true),
[], undefined, exportTag);
}
}
private parseEnum(): void {
const [, spaces, constTag, exportTag, id] = this.getLine(true)
.match(/^(\s*)(export\s+)?(const\s+)?enum\s+(\w+)\b/) || EMPTY;
if (spaces === this.outerSpaces) {
this.addId(id, DocIdType.EnumName,
this._processDefContent(this.getLine(), false),
[constTag], undefined, exportTag);
}
}
private parseConst(): void {
const [, spaces, exportTag, id] = this.getLine(true)
.match(/^(\s*)(export\s+)?const\s+(\w+)\b/) || EMPTY;
if (spaces === this.outerSpaces) {
this.addId(id, DocIdType.ConstName,
this._processDefContent(this.getLine(), true), [exportTag]);
}
}
parseFileData(text: string): void {
this.outerSpaces = ' ';
this.innerSpaces = this.outerSpaces + this.outerSpaces;
this.inpLines = text.split('\n');
this.inpLineNr = 0;
this.inpLineCount = this.inpLines.length;
while (!this.isFinished()) {
// if (this.getLine(false).includes('@stop-processing')) {
// console.log(`this.inpLineNr: ${this.inpLineNr}`);
// console.log(this.inpLines);
// break;
// }
const curLineNr = this.inpLineNr;
this.parseJsDocs();
if (this.isInsideClassOrInterface) {
this.parseMethodsAndProperties();
} {
if (!this.parseInterfaceOrClass()) {
this.parseEnum();
this.parseConst();
this.parseType();
this.parseFunction();
this.parseEndOfClassOrInterface();
}
}
if (curLineNr === this.inpLineNr) {
this.getLine();
}
}
}
}
// ------------------------------------------------------------------------
// MkDocs
// ------------------------------------------------------------------------
interface Opts {
name?: string;
folder?: string;
}
/**
* Loads a mkdocs.yml template file, adds and organizes pages,
* and generates the output.
*/
class MkDocsYml {
yamlDoc: {
site_name: string;
nav: (string | any)[];
production: any;
};
folderMap: { [name: string]: (string | any)[] } = {};
constructor(templateFileName: string, targetName: string) {
this.yamlDoc = yaml.safeLoad(fsix.readUtf8Sync(
templateFileName));
this.yamlDoc.site_name = this.yamlDoc.site_name
.replace(/%target%/, targetName)
.replace(/%version%/, versionLib.VERSION);
}
save(dstFileName: string): void {
sysFs.writeFileSync(dstFileName, yaml.safeDump(this.yamlDoc));
}
addSourceFile(opts: Opts, fileName: string, content: string): string {
const pageName = sysPath.posix.basename(fileName);
// gets document name from the source/markdown file
if (!opts.name) {
content = content.replace(/^\s*[\/\*]*\s*@doc-name\s+\b([\w ]+)\s*\n/m,
(_all, docName) => {
opts.name = docName;
return '';
});
}
// make a more double uppercase document index title
if (!opts.name && pageName.includes('-')) {
opts.name = pageName[0].toUpperCase() + pageName.substr(1)
.replace(/\.md$/, '')
.replace(/-(\w)/g, (_all, p) => ' ' + p.toUpperCase());
}
// gets the folder name from the source/markdown file
content.replace(/^\s*[\/\*]+\s*@doc-folder\s+\b([\w ]+)\s*\n/m,
(_all, folder) => {
opts.folder = folder;
return '';
});
let folderContainer = opts.folder ? this.folderMap[opts.folder] : this.yamlDoc.nav;
if (!folderContainer) {
folderContainer = this.folderMap[opts.folder] = [];
const subFolder = {};
subFolder[opts.folder] = folderContainer;
this.yamlDoc.nav.push(subFolder);
}
if (opts.name) {
const formattedPageName = {};
formattedPageName[opts.name] = pageName;
folderContainer.push(formattedPageName);
} else {
folderContainer.push(pageName);
}
return content;
}
}
// ------------------------------------------------------------------------
// formatMarkdown
// ------------------------------------------------------------------------
/**
* Modifies the markdown generate from the JsDocs to be more readable
* and processes links.
*/
function formatJsDocsMarkdown(text: string,
localWebLinks: LocalWebLinks): string {
// ensures that lines that end a paragraph generate a paragraph in markdown
text = text.replace(/([\.`":])\n(.|\n)/g, '$1 \n$2');
text = text.replace(/^\s*@(example|default)\b\s*`?(.*)`?\s*$/mg, '_$1_: `$2` ');
text = text.replace(/^\s*@(param)\s+(\w+)\s*/mg, '**$1**: `$2` ');
text = text.replace(/^\s*@(returns)\b\s*/mg, '**$1**: ');
text = text.replace(/^\s*@(type|memberof|readonly)\b(.*)$/mg, '');
text = text.replace(/@see\b\s*((https?:\/\/)?(\w+\/)?([^#\s]*)?(#\S*)?\b)/g, (
_all, link: string,
http: string, folder: string, title: string, bookmark: string) => {
if (http) {
title = link;
} else {
if (folder) {
const key = folder.substr(0, folder.length - 1);
return `_see_: ${localWebLinks(key, title)}. `;
} else {
link = (folder || '')
+ (title || '') + (title ? '.md' : '')
+ (!folder && bookmark
? bookmark.toLowerCase() // mkdocs lowercase the local bookmarks
: (bookmark || ''));
title = title || bookmark.substr(1);
}
}
return `_see_: [${title || link}](${link}). `;
});
return text;
}
// ------------------------------------------------------------------------
// buildMarkdownFromSourceFile
// ------------------------------------------------------------------------
/**
* Loads a TypeScript source file, scans for @module <type>,
* and if the `type` matches it generates the associated markdown
* and adds the file to mkdocs.
* If exists the api file, generated by build-d-ts, it concats at the end of the file.
*
*/
function buildMarkdownFromSourceFile(
inpFileName: string, outFileName: string, apiFileName: string,
moduleTypes: string[], mkDocsYml: MkDocsYml, mkDocsOpts: Opts,
localWebLinks: LocalWebLinks,
isEndUser: boolean, log: Log): void {
// if (isEndUser || inpFileName.indexOf('story') === -1) { return; }
const inpText = fsix.readUtf8Sync(inpFileName);
const matches = inpText.match(
/\/\*\*\s*@module ([\w+\-]+)(?:\s*\|.*)\n(?:(?:.|\n)*?)\/\*\*((?:.|\n)*?)\*\//) || EMPTY;
const moduleType = matches[1] || '';
if (moduleType && moduleTypes.indexOf(moduleType) !== -1) {
let outText = formatJsDocsMarkdown(matches[2].trim().split('\n').map(line => {
return line.replace(/^\s*\*\s/, '').trimRight()
.replace(/^\s*\*$/, ' '); // removes the end delimiter of JSDocs
}).join('\n'), localWebLinks);
let preDocText = '';
if (isEndUser && sysFs.existsSync(apiFileName)) {
preDocText = fsix.readUtf8Sync(apiFileName) + '\n';
// inpText = inpText.replace(/(namespace)/, '// @stop-processing\n$1');
}
if ((!isEndUser) || moduleType === 'end-user') {
const docParser = new DocParser(localWebLinks, isEndUser);
docParser.parseFileData(preDocText + inpText);
if (docParser.outLines.length) {
outText += ' \n \n<div class=api-header> </div>\n#API\n'
+ docParser.outLines.join('\n');
}
}
mkDocsYml.addSourceFile(mkDocsOpts, outFileName, inpText);
sysFs.writeFileSync(outFileName, outText);
log.generated.push(outFileName);
}
}
/**
* Copies a markdown file from to the destination
* and adds the file to mkdocs.
*/
function copyMarkdownFile(srcFileName: string, dstFileName: string,
mkDocs: MkDocsYml, mkDocsOpts: Opts, _cfg: DevCfg.DevConfig,
processPage?: (data: string) => string): string {
let data = fsix.readUtf8Sync(srcFileName);
data = mkDocs.addSourceFile(mkDocsOpts, dstFileName, data);
if (processPage) { data = processPage(data); }
sysFs.writeFileSync(dstFileName, data);
return dstFileName;
}
/**
* This is the main entry point.
* Read the module information for details.
*/
export function build(libModules: string[],
pluginModules: string[], cfg: DevCfg.DevConfig): void {
const localWebLinks = (key: string, title: string) => {
if (key === 'gallery') {
return `[${title}](/${cfg.paths.GALLERY_LATEST_PATH}/#${title})`;
} else {
return '';
}
};
// ------------------------------------------------------------------------
// buildWebLinks
// ------------------------------------------------------------------------
// in case of documentation, it's better to visualize the more specific at the top.
libModules.reverse();
getTargets(cfg).forEach(target => {
const baseDstPath = `${target.dstPath}/${EN_LAST_VERSION_PATH}`;
const markdownDstPath = `${baseDstPath}/${MARKDOWN_FOLDER}`;
fsix.mkdirpSync(markdownDstPath);
const mkDocsYml = new MkDocsYml(`${cfg.paths.DOCS_SOURCE_PATH}/.mkdocs-template.yml`,
target.name);
const log: Log = {
notFound: [],
found: [],
generated: [],
refs: {},
};
// index.html
copyMarkdownFile(target.indexFile,
`${markdownDstPath}/index.md`, mkDocsYml, {}, cfg, target.processIndexPage);
// copy sources
target.sourcePaths.forEach(sourcesPathName => {
sysFs.readdirSync(sourcesPathName).forEach(file => {
if (file.endsWith('.md') && !file.match(/-dev|README/)) {
copyMarkdownFile(`${sourcesPathName}/${file}`,
`${markdownDstPath}/${file}`, mkDocsYml, {}, cfg);
}
if (file.endsWith('.css') || file.endsWith('.png') || file.endsWith('.ico')) {
sysFs.writeFileSync(`${markdownDstPath}/${file}`,
sysFs.readFileSync(`${sourcesPathName}/${file}`));
}
});
});
// builds markdown files
[['abeamer-cli', 'cli/abeamer-cli.ts', ''],
['server-agent', 'server/server-agent.ts', 'Server'],
['exact', 'test/exact.ts', 'Testing'],
...libModules
.map(fileTitle => [fileTitle, `${cfg.paths.JS_PATH}/${fileTitle}.ts`, 'Library']),
...pluginModules
.map(fileTitle => [fileTitle, `${cfg.paths.PLUGINS_PATH}/${fileTitle}/${fileTitle}.ts`, 'Plugins']),
]
.forEach(item => {
const [fileTitle, srcFileName, folder] = item;
const dstFileName = `${markdownDstPath}/${fileTitle}.md`;
buildMarkdownFromSourceFile(srcFileName, dstFileName,
`${baseDstPath}/${API_FOLDER}/${fileTitle}.txt`,
target.moduleTypes,
mkDocsYml, { folder }, localWebLinks, target.isEndUser, log);
});
// writes mkdocs to be used by mkdocs command-line program
mkDocsYml.save(`${baseDstPath}/mkdocs.yml`);
// process all the links
new ReferenceBuilder(log).build(markdownDstPath);
// save log
fsix.writeJsonSync(target.logFile, log);
console.log(`
Generated: ${log.generated.length} files.
Not Found references: ${log.notFound.length}
`);
});
}
// ------------------------------------------------------------------------
// buildWebLinks
// ------------------------------------------------------------------------
export function postBuild(filePatterns: string[],
replacePaths: any[][], wordMap: DevCfg.DevDocsWordMap): void {
const highlightRegEx = new
RegExp(`\\b(${Object.keys(wordMap).join('|')})\\b`, 'g');
globule.find(filePatterns).forEach(file => {
let content = fsix.readUtf8Sync(file);
replacePaths.forEach((pathSrcDst) => {
content = content.replace(pathSrcDst[0], pathSrcDst[1] as string);
});
content = content.replace(/(<code class="js">)((?:.|\n)+?)(<\/code>)/g,
(_all, preTag, code, postTag) => {
code = code.replace(highlightRegEx, (_all2, word) => {
const wordInf = wordMap[word];
return `<span class="hljs-${wordInf.wordClass}"`
+ `${wordInf.title ? ` title="${wordInf.title}"` : ''}>${word}</span>`;
});
return preTag + code + postTag;
});
sysFs.writeFileSync(file, content);
});
}
}
/*
converting markdown to html was deprecated , since now
is done via `mkdocs`
this code is kept since it can be useful in the future
const SOURCES_FOLDER = 'sources';
const HTML_PATH = 'versions/latest/en';
targets.forEach(docsRec => {
[MARKDOWN_FOLDER, SOURCES_FOLDER].forEach(inpFolder => {
sysFs.readdirSync(`${docsRec.dstPath}/${inpFolder}`).forEach(file => {
if (file.endsWith('.md')) {
BuildDocs.markdownToHtml(`${docsRec.dstPath}/${inpFolder}/${file}`,
`${docsRec.dstPath}/${HTML_PATH}/${file.replace(/\.md$/, '.html')}`);
}
});
});
});
const markdownCompiler = require('marked');
const highlightJs = require('highlight.js');
markdownCompiler.setOptions({
renderer: new markdownCompiler.Renderer(),
highlight: (code) => highlightJs.highlightAuto(code).value,
pedantic: false,
gfm: true,
tables: true,
breaks: false,
sanitize: false,
smartLists: true,
smartypants: false,
xhtml: false,
});
export function markdownToHtml(inpFileName: string, outputFileName: string): void {
const inpData = fsix.readUtf8Sync(inpFileName);
const STYLING_PATH = '../../../../styling';
const html = '<html>\n<head>\n'
+ `
<link rel="stylesheet" href="${STYLING_PATH}/highlight.js/styles/github.css">
<link rel="stylesheet" href="${STYLING_PATH}/style.css">
<script src="${STYLING_PATH}/highlight.js/lib/highlight.js"></script>
<script>hljs.initHighlightingOnLoad();</script>\n`
+ '</head>\n<body>\n'
+ markdownCompiler(inpData)
+ '</body>\n</html>';
sysFs.writeFileSync(outputFileName, html);
console.log(`Generated ${outputFileName}`);
}
*/ | the_stack |
import { SFC, b, emit, machine, mount } from '../../src';
import * as fc from 'fast-check';
import {
machineRegistry,
machinesThatTransitioned,
} from '../../src/machineRegistry';
import { VNode } from '../../src/createElement';
import { markLIS } from '../../src/diff';
describe('machine property-based tests', () => {
let $root = document.body;
test('machine property 1', () => {
/**
* for any two sets of strings a (length n) and b (length k, k >= n),
* where a is the set of when and b is the set of events,
* and a[0] is the initial state, and each state[i] transitions to the
* next state[i + 1] on event[i], the state after emitting
* event[0] through event[k - 1] will be state[n - 1] (final state).
*
* emitting the excess events shouldn't affect state.
*
* this state is visible in the dom through the render function.
* */
fc.assert(
fc.property(
fc.set(fc.string(2, 10), 3, 10),
fc.set(fc.string(2, 10), 10, 10),
(when, events) => {
const whenSchema: {
[state: string]: {
on: {
[event: string]: {
to: string;
};
};
};
} = {};
for (let i = 0; i < when.length; i++) {
const state = when[i];
// no transition for the last state
if (i < when.length - 1) {
const nextState = when[i + 1];
const thisWhenSchema = {
on: {
[events[i]]: {
to: nextState,
},
},
};
whenSchema[state] = thisWhenSchema;
} else {
whenSchema[state] = { on: {} };
}
}
const Mach = machine({
id: 'Mach',
initial: when[0],
context: () => ({}),
when: whenSchema,
render: s => <p>{s}</p>,
});
$root = mount(Mach, $root);
// is initial state (when[0])
expect($root.nodeName).toBe('P');
expect($root.firstChild?.nodeValue).toBe(when[0]);
// emit all events
for (const eventType of events) {
emit({ type: eventType });
}
// is final state (when[n - 1])
expect($root.nodeName).toBe('P');
expect($root.firstChild?.nodeValue).toBe(when[when.length - 1]);
// have to clear bc its the same app instance
machineRegistry.clear();
machinesThatTransitioned.clear();
}
)
);
});
// test("diff property 1", () => {
// /**
// * properties of keyed diff:
// * - two sets of strings (both key and text node value)
// * -
// */
// })
test('machine property 2', () => {
/**
* for n machines rendered, there should be n instances in the machine registry.
*/
fc.assert(
fc.property(fc.integer(0, 50), n => {
const App = () => (
<div>
{Array.from({ length: n }).map((_, i) => (
<Machine i={i} />
))}
</div>
);
const Machine = machine<{ i: number }>({
id: props => `${props.i}`,
initial: 'exists',
context: () => ({}),
when: {
exists: {},
},
render: (_, _ctx, self) => <p>{self}</p>,
});
$root = mount(App, $root);
expect(machineRegistry.size).toBe(n);
machineRegistry.clear();
})
);
});
test('machine property 3', () => {
/**
*
* where t = n + k, t machines are rendered, and n machines transition,
* there should be n machines in 'machinesThatTransitioned.'
*
* k machines in the machine registry should have the property of oldVNode === newVNode
* (all the machines of the type that didn't transition should have the property of oldVNode -== newVNode)
*/
fc.assert(
fc.property(fc.integer(0, 50), fc.integer(0, 50), (numOne, numTwo) => {
const MachThatTransitions = machine<{ i: number }>({
id: props => `transitions-${props.i}`,
initial: 'loading',
context: () => ({}),
when: {
loading: {
on: {
LOADED: {
to: 'ready',
},
},
},
ready: {},
},
render: () => <p>i transition</p>,
});
const MachThatDoesntTransition = machine<{ i: number }>({
id: props => `doesnottransition-${props.i}`,
initial: 'loading',
context: () => ({}),
when: {
loading: {},
},
render: () => <p>i don't transition</p>,
});
const App: SFC = () => (
<div>
<div>
{Array.from({ length: numOne }).map((_, i) => (
<MachThatTransitions i={i} />
))}
</div>
{Array.from({ length: numTwo }).map((_, i) => (
<MachThatDoesntTransition i={i} />
))}
</div>
);
$root = mount(App, $root);
expect(machineRegistry.size).toBe(numOne + numTwo);
const oldVNodes = new Map<string, VNode | null>();
machineRegistry.forEach(machine => {
oldVNodes.set(machine.id, machine.v.c);
});
emit({ type: 'LOADED' });
const newVNodes = new Map<string, VNode | null>();
machineRegistry.forEach(machine => {
newVNodes.set(machine.id, machine.v.c);
});
// don't really have to count both but why not
let persistedNodes = 0;
let rerenderedNodes = 0;
for (const [id, newVNode] of newVNodes) {
const oldVNode = oldVNodes.get(id);
if (oldVNode) {
if (oldVNode === newVNode) {
persistedNodes++;
expect(id.slice(0, 7) === 'doesnot').toBe(true);
} else {
rerenderedNodes++;
expect(id.slice(0, 1) === 't').toBe(true);
}
}
}
expect(rerenderedNodes).toBe(numOne);
expect(persistedNodes).toBe(numTwo);
machineRegistry.clear();
})
);
expect(true).toBe(true);
});
/**
* this test works 99% of the time,
* fails on this counterexample:
* Counterexample: [["%20","","%2e","f","7=D=@3p"]]
*
* investigate more if router ever demonstrates bugs
*
* commented out bc i don't want to break builds for a non-bug
*/
// test('machine property 4', () => {
// /**
// * routers + machines
// *
// * (input of string array to id the machine + route)
// * for n routes and n machines, 1 machine for each route, only that instance
// * should be on the page for any given route.
// *
// */
// fc.assert(
// fc.property(fc.set(fc.webSegment(), 5, 10), names => {
// // nothing that starts with '*' or ':,
// // those are special cases for RouTrie. '.' doesn't work either for some reason
// const validNames = names.filter(
// name =>
// name.length > 0 &&
// name[0] !== '.' &&
// name[0] !== '*' &&
// name[0] !== ':'
// );
// const routeSchema: RouterSchema = {
// '/': () => <p>home</p>,
// };
// for (let i = 0; i < validNames.length; i++) {
// routeSchema[`/page/${validNames[i]}`] = () => (
// <div>
// <PageMachine routeName={validNames[i]} />
// </div>
// );
// }
// const PageMachine = machine<{ routeName: string }>({
// id: ({ routeName }) => routeName,
// initial: 'here',
// context: () => ({}),
// when: { here: {} },
// render: (_s, _c, self) => <p>{self}</p>,
// });
// const MyRouter = router(routeSchema);
// const App: SFC = () => (
// <div>
// <MyRouter />
// </div>
// );
// $root = mount(App, $root);
// expect($root.nodeName).toBe('DIV');
// for (let i = 0; i < validNames.length; i++) {
// linkTo(`/page/${validNames[i]}`);
// expect($root.firstChild?.nodeName).toBe('DIV');
// expect($root.firstChild?.firstChild?.firstChild?.nodeValue).toBe(
// validNames[i]
// );
// expect(machineRegistry.get(validNames[i])).toBeDefined();
// expect(machineRegistry.size).toBe(1);
// }
// machineRegistry.clear();
// })
// );
// });
test('dom count', () => {
const length = 10;
const MyApp: SFC = () => (
<div id="root">
{Array.from({ length }).map((_, i) => (
<p>paragraph {i}</p>
))}
</div>
);
$root = mount(MyApp, $root);
const numOfKids = document.getElementById('root')?.childNodes.length;
expect(numOfKids).toBe(length);
});
});
/**
* properties for LIS:
*
* - with input array of unique integers >= 0:
*
* - length of before and after must be equal
* - no negative numbers (other than -1/-2), and number >=0 must be unique
*/
test('markLIS property', () => {
fc.assert(
fc.property(fc.set(fc.integer(0, 3000), 2, 100), arr => {
const lisMarked = markLIS(Int32Array.from(arr));
expect(lisMarked.length).toBe(arr.length);
let smallest = -2;
// 0+. represents moves (position in old array)
let nonNegative = [];
for (let i = 0; i < lisMarked.length; i++) {
lisMarked[i] < smallest && (smallest = lisMarked[i]);
lisMarked[i] >= 0 && nonNegative.push(lisMarked[i]);
}
const nonNegativeSet = [...new Set(nonNegative)];
expect(smallest >= -2).toBe(true);
expect(nonNegative).toStrictEqual(nonNegativeSet);
})
);
}); | the_stack |
import * as path from "path";
import chai from "chai";
import * as dotnetUtils from "../utils/dotnet";
import * as funcUtils from "../utils/funcTool";
import * as nodeUtils from "../utils/node";
import { isLinux } from "../../../../src/common/deps-checker/util/system";
import { DepsType } from "../../../../src/common/deps-checker/depsChecker";
import { DependencyStatus, DepsManager } from "../../../../src/common/deps-checker/depsManager";
import { cpUtils } from "../../../../src/common/deps-checker/util/cpUtils";
import { logger } from "../adapters/testLogger";
import { TestTelemetry } from "../adapters/testTelemetry";
import "mocha";
import { isNonEmptyDir } from "../utils/common";
import { testCsprojFileName, testOutputDirName } from "../utils/backendExtensionsInstaller";
import { installExtension } from "../../../../src/common/deps-checker/util/extensionInstaller";
const expect = chai.expect;
const assert = chai.assert;
describe("All checkers E2E test", async () => {
let backendProjectDir: string;
let backendOutputPath: string;
let cleanupProjectDir: () => void;
beforeEach(async function () {
[backendProjectDir, cleanupProjectDir] = await dotnetUtils.createTmpBackendProjectDir(
dotnetUtils.testCsprojFileName
);
backendOutputPath = path.resolve(backendProjectDir, dotnetUtils.testOutputDirName);
await dotnetUtils.cleanup();
await funcUtils.cleanup();
});
afterEach(async function () {
// cleanup to make sure the environment is clean
await dotnetUtils.cleanup();
cleanupProjectDir();
});
it("All installed", async function () {
const nodeVersion = await nodeUtils.getNodeVersion();
if (!(nodeVersion != null && nodeUtils.azureSupportedNodeVersions.includes(nodeVersion))) {
this.skip();
}
if (
!(await dotnetUtils.hasAnyDotnetVersions(
dotnetUtils.dotnetCommand,
dotnetUtils.dotnetSupportedVersions
))
) {
this.skip();
}
if (!(await funcUtils.isFuncCoreToolsInstalled())) {
this.skip();
}
const depsTypes = [DepsType.AzureNode, DepsType.FuncCoreTools, DepsType.Dotnet];
const depsManger = new DepsManager(logger, new TestTelemetry());
const depsStatus = await depsManger.ensureDependencies(depsTypes, { fastFail: true });
verifyAllSuccess(depsStatus);
// verify node (and order = 0)
const node = depsStatus[0];
assert.equal(node.type, DepsType.AzureNode);
// verify dotnet (and order = 1)
const dotnet = depsStatus[1];
assert.equal(dotnet.type, DepsType.Dotnet);
chai.assert.isTrue(
await dotnetUtils.hasAnyDotnetVersions(dotnet.command!, dotnetUtils.dotnetSupportedVersions)
);
// verify funcTools (and order = 2)
const funcTool = depsStatus[2];
assert.equal(funcTool.type, DepsType.FuncCoreTools);
assert.equal(funcTool.command, "func", `should use global func-core-tools`);
const funcStartResult: cpUtils.ICommandResult = await cpUtils.tryExecuteCommand(
undefined,
logger,
{ shell: true },
`${funcTool.command} start`
);
// func start can work: "Unable to find project root. Expecting to find one of host.json, local.settings.json in project root."
chai.assert.isTrue(
funcStartResult.cmdOutputIncludingStderr.includes("Unable to find project root"),
`func start should return error message that contains "Unable to find project root", but actual output: "${funcStartResult.cmdOutputIncludingStderr}"`
);
// verify backendExtension installer
chai.assert.isFalse(await isNonEmptyDir(backendOutputPath));
await installExtension(
backendProjectDir,
dotnet.command,
logger,
testCsprojFileName,
testOutputDirName
);
chai.assert.isTrue(await isNonEmptyDir(backendOutputPath));
// verify get deps status
const depsStatusFromQuery = await depsManger.getStatus(depsTypes);
for (const status of depsStatusFromQuery) {
chai.assert.isTrue(status.isInstalled);
}
});
it("None installed - Linux", async function () {
const nodeVersion = await nodeUtils.getNodeVersion();
if (nodeVersion != null) {
this.skip();
}
if (
await dotnetUtils.hasAnyDotnetVersions(
dotnetUtils.dotnetCommand,
dotnetUtils.dotnetSupportedVersions
)
) {
this.skip();
}
if (await funcUtils.isFuncCoreToolsInstalled()) {
this.skip();
}
if (!isLinux()) {
this.skip();
}
const depsTypes = [DepsType.Ngrok, DepsType.AzureNode, DepsType.FuncCoreTools, DepsType.Dotnet];
const depsManger = new DepsManager(logger, new TestTelemetry());
const depsStatus = await depsManger.ensureDependencies(depsTypes, { fastFail: true });
// verify node
const node = depsStatus[0];
assert.equal(node.type, DepsType.AzureNode);
assert.isFalse(node.isInstalled);
// verify dotnet
const dotnet = depsStatus[1];
assert.equal(dotnet.type, DepsType.Dotnet);
assert.isFalse(dotnet.isInstalled);
assert.isFalse(
await dotnetUtils.hasAnyDotnetVersions(dotnet.command!, dotnetUtils.dotnetSupportedVersions)
);
// verify funcTools
const funcTool = depsStatus[2];
assert.equal(funcTool.type, DepsType.FuncCoreTools);
assert.isFalse(funcTool.isInstalled);
chai.assert.isTrue(
"npx azure-functions-core-tools@3" == funcTool.command,
"for linux, should use: npx azure-functions-core-tools@3"
);
// verify ngrok
await verifyNgrok(depsStatus[3]);
});
it("None installed - Not Linux", async function () {
const nodeVersion = await nodeUtils.getNodeVersion();
if (nodeVersion != null) {
this.skip();
}
if (
await dotnetUtils.hasAnyDotnetVersions(
dotnetUtils.dotnetCommand,
dotnetUtils.dotnetSupportedVersions
)
) {
this.skip();
}
if (await funcUtils.isFuncCoreToolsInstalled()) {
this.skip();
}
if (isLinux()) {
this.skip();
}
const depsTypes = [DepsType.Ngrok, DepsType.AzureNode, DepsType.FuncCoreTools, DepsType.Dotnet];
const depsManger = new DepsManager(logger, new TestTelemetry());
const depsStatus = await depsManger.ensureDependencies(depsTypes, { fastFail: true });
// verify node
const node = depsStatus[0];
assert.equal(node.type, DepsType.AzureNode);
assert.isFalse(node.isInstalled);
// verify dotnet
const dotnet = depsStatus[1];
assert.equal(dotnet.type, DepsType.Dotnet);
assert.isTrue(dotnet.isInstalled);
assert.isTrue(
await dotnetUtils.hasAnyDotnetVersions(dotnet.command!, dotnetUtils.dotnetSupportedVersions)
);
// verify funcTools
await verifyFuncInstall(depsStatus[2]);
// verify ngrok
await verifyNgrok(depsStatus[3]);
// verify backendExtension installer
chai.assert.isFalse(await isNonEmptyDir(backendOutputPath));
await installExtension(
backendProjectDir,
dotnet.command,
logger,
testCsprojFileName,
testOutputDirName
);
chai.assert.isTrue(await isNonEmptyDir(backendOutputPath));
});
it("Only Node installed - Not Linux", async function () {
const nodeVersion = await nodeUtils.getNodeVersion();
if (nodeVersion == null) {
this.skip();
}
if (
await dotnetUtils.hasAnyDotnetVersions(
dotnetUtils.dotnetCommand,
dotnetUtils.dotnetSupportedVersions
)
) {
this.skip();
}
if (await funcUtils.isFuncCoreToolsInstalled()) {
this.skip();
}
if (isLinux()) {
this.skip();
}
const depsTypes = [DepsType.Ngrok, DepsType.AzureNode, DepsType.FuncCoreTools, DepsType.Dotnet];
const depsManger = new DepsManager(logger, new TestTelemetry());
const depsStatus = await depsManger.ensureDependencies(depsTypes, { fastFail: true });
verifyAllSuccess(depsStatus);
// verify node
const node = depsStatus[0];
assert.equal(node.type, DepsType.AzureNode);
assert.isTrue(node.isInstalled);
assert.isNotNull(node.command);
assert.isNull(node.error);
// verify dotnet
const dotnet = depsStatus[1];
assert.equal(dotnet.type, DepsType.Dotnet);
assert.isTrue(dotnet.isInstalled);
assert.isTrue(
await dotnetUtils.hasAnyDotnetVersions(dotnet.command!, dotnetUtils.dotnetSupportedVersions)
);
// verify funcTools
await verifyFuncInstall(depsStatus[2]);
// verify ngrok
await verifyNgrok(depsStatus[3]);
});
});
function verifyAllSuccess(depsStatus: DependencyStatus[]) {
// verify all install
for (const dep of depsStatus) {
assert.isTrue(dep.isInstalled);
assert.isNotNull(dep.command);
assert.isNull(dep.error);
assert.isNotNull(dep.details.supportedVersions);
}
}
async function verifyFuncInstall(funcTool: DependencyStatus) {
assert.equal(funcTool.type, DepsType.FuncCoreTools);
const funcExecCommand = `${funcTool.command} start`;
chai.assert.isTrue(
/node "[^"]*" start/g.test(funcExecCommand),
`should use private func-core-tools`
);
const funcStartResult: cpUtils.ICommandResult = await cpUtils.tryExecuteCommand(
undefined,
logger,
{ shell: true },
funcExecCommand
);
// func start can work: "Unable to find project root. Expecting to find one of host.json, local.settings.json in project root."
chai.assert.isTrue(
funcStartResult.cmdOutputIncludingStderr.includes("Unable to find project root"),
`func start should return error message that contains "Unable to find project root", but actual output: "${funcStartResult.cmdOutputIncludingStderr}"`
);
}
async function verifyNgrok(ngrok: DependencyStatus) {
assert.equal(ngrok.type, DepsType.Ngrok);
assert.isTrue(ngrok.isInstalled);
assert.isNotNull(ngrok.details.binFolders);
const ngrokVersionResult: cpUtils.ICommandResult = await cpUtils.tryExecuteCommand(
undefined,
logger,
{
shell: true,
env: { PATH: ngrok.details.binFolders?.[0] },
},
"ngrok version"
);
// ngrok version 2.3.x
expect(ngrokVersionResult.cmdOutputIncludingStderr).to.includes(
"ngrok version 2.3.",
`ngrok version should return version string contains "ngrok version 2.3.", but actual output: "${ngrokVersionResult.cmdOutputIncludingStderr}"`
);
} | the_stack |
import React, { Component } from 'react'
import {
StyleSheet,
Text,
View,
Image,
TouchableNativeFeedback,
InteractionManager,
ActivityIndicator,
Animated,
FlatList,
Linking,
Alert
} from 'react-native'
import Ionicons from 'react-native-vector-icons/Ionicons'
import { standardColor, idColor, accentColor } from '../../constant/colorConfig'
import SimpleComment from '../../component/SimpleComment'
import {
getBattleAPI
} from '../../dao'
import {
close
} from '../../dao/sync'
declare var global
/* tslint:disable */
let toolbarActions = [
{
title: '回复', iconName: 'md-create', show: 'always', iconSize: 22, onPress: function () {
const { params } = this.props.navigation.state
if (this.isReplyShowing === true) return
this.props.navigation.navigate('Reply', {
type: params.type,
id: params.rowData.id,
callback: this.preFetch,
shouldSeeBackground: true
})
return
}
},
{
title: '刷新', iconName: 'md-refresh', show: 'never', onPress: function () {
this.preFetch()
}
},
{
title: '在浏览器中打开', iconName: 'md-refresh', show: 'never', onPress: function () {
const { params = {} } = this.props.navigation.state
Linking.openURL(params.URL).catch(err => global.toast(err.toString()))
}
},
{
title: '分享', iconName: 'md-share-alt', show: 'never', onPress: function () {
try {
const { params } = this.props.navigation.state
global.Share.open({
url: params.URL,
message: '[PSNINE] ' + this.state.data.titleInfo.title,
title: 'PSNINE'
}).catch((err) => { err && console.log(err) })
} catch (err) { }
}
}
]
/* tslint:enable */
class CommunityTopic extends Component<any, any> {
static navigationOptions({ navigation }) {
return {
title: navigation.state.params.title || '约战'
}
}
constructor(props) {
super(props)
this.state = {
data: false,
isLoading: true,
mainContent: false,
rotation: new Animated.Value(1),
scale: new Animated.Value(1),
opacity: new Animated.Value(1),
openVal: new Animated.Value(0),
modalVisible: false,
modalOpenVal: new Animated.Value(0),
topicMarginTop: new Animated.Value(0)
}
}
componentWillMount() {
this.preFetch()
}
preFetch = () => {
const { params } = this.props.navigation.state
this.setState({
isLoading: true
})
InteractionManager.runAfterInteractions(() => {
getBattleAPI(params.URL).then(data => {
const html = data.contentInfo.html
const emptyHTML = '<div></div>'
this.hasContent = html !== emptyHTML
this.hasTrophyTable = data.contentInfo.trophyTable.length !== 0
this.hasComment = data.commentList.length !== 0
this.hasReadMore = this.hasComment ? data.commentList[0].isGettingMoreComment === true ? true : false : false
this.setState({
data,
mainContent: html,
commentList: data.commentList,
isLoading: false
})
})
})
}
handleImageOnclick = (url) => this.props.navigation.navigate('ImageViewer', {
images: [
{ url }
]
})
hasContent = false
renderContent = (html) => {
const { modeInfo } = this.props.screenProps
return (
<View key={'content'} style={{
elevation: 1,
margin: 5,
marginTop: 0,
backgroundColor: modeInfo.backgroundColor,
padding: 10
}}>
<global.HTMLView
value={html}
modeInfo={modeInfo}
shouldShowLoadingIndicator={true}
stylesheet={styles}
imagePaddingOffset={30}
onImageLongPress={this.handleImageOnclick}
/>
</View>
)
}
renderGame = (rowData) => {
const { modeInfo } = this.props.screenProps
return (
<View style={{ elevation: 1, margin: 5, marginTop: 0, backgroundColor: modeInfo.backgroundColor }}>
<View style={{
backgroundColor: modeInfo.backgroundColor
}}>
<TouchableNativeFeedback
onPress={() => {
this.props.navigation.navigate('GamePage', {
URL: rowData.url,
title: rowData.title,
rowData,
type: 'game'
})
}}
useForeground={true}
background={TouchableNativeFeedback.SelectableBackgroundBorderless()}
>
<View style={{ flex: 1, flexDirection: 'row', padding: 12 }}>
<Image
source={{ uri: rowData.avatar }}
style={[styles.avatar, { width: 91 }]}
/>
<View style={{ marginLeft: 10, flex: 1, flexDirection: 'column' }}>
<Text
ellipsizeMode={'tail'}
numberOfLines={3}
style={{ flex: 2.5, color: modeInfo.titleTextColor }}>
{rowData.title}
</Text>
<View style={{ flex: 1.1, flexDirection: 'row', justifyContent: 'space-between' }}>
<Text selectable={false} style={{ flex: -1,
color: modeInfo.standardColor, textAlign: 'center', textAlignVertical: 'center' }} onPress={
() => {
this.props.navigation.navigate('Home', {
title: rowData.psnid,
id: rowData.psnid,
URL: `https://psnine.com/psnid/${rowData.psnid}`
})
}
}>{rowData.psnid}</Text>
<Text selectable={false} style={{ flex: -1,
color: modeInfo.standardTextColor, textAlign: 'center', textAlignVertical: 'center' }}>{rowData.date}</Text>
</View>
</View>
</View>
</TouchableNativeFeedback>
</View>
</View>
)
}
hasTrophyTable = false
renderTrophyTable = (trophyTable) => {
const { modeInfo } = this.props.screenProps
const list: any[] = []
for (const rowData of trophyTable) {
list.push(
<View key={rowData.id || (list.length - 1)} style={{
backgroundColor: modeInfo.backgroundColor
}}>
<TouchableNativeFeedback
onPress={() => {
this.props.navigation.navigate('Trophy', {
URL: rowData.href,
title: '@' + rowData.title,
rowData,
type: 'trophy'
})
}}
useForeground={true}
background={TouchableNativeFeedback.SelectableBackgroundBorderless()}
>
<View pointerEvents='box-only' style={{ flex: 1, flexDirection: 'row', padding: 12 }}>
<Image
source={{ uri: rowData.avatar }}
style={[styles.avatar, { width: 91 }]}
/>
<View style={{ marginLeft: 10, flex: 1, flexDirection: 'column', alignContent: 'center' }}>
<View style={{ flexDirection: 'row', alignItems: 'flex-start' }}>
<Text
ellipsizeMode={'tail'}
style={{ flex: -1, color: modeInfo.titleTextColor }}>
{rowData.title}
</Text>
<Text selectable={false} style={{
flex: -1,
marginLeft: 5,
color: idColor,
textAlign: 'center',
textAlignVertical: 'center'
}}>{rowData.tip}</Text>
</View>
<View style={{ flex: 1.1, flexDirection: 'row', justifyContent: 'space-between' }}>
<Text selectable={false} style={{
flex: -1,
color: modeInfo.standardTextColor,
textAlign: 'center',
textAlignVertical: 'center',
fontSize: 10
}}>{rowData.text}</Text>
<Text selectable={false} style={{
flex: 1,
color: modeInfo.standardTextColor,
textAlign: 'center',
textAlignVertical: 'center',
fontSize: 10
}}>{rowData.rare}</Text>
</View>
</View>
</View>
</TouchableNativeFeedback>
</View>
)
}
return (
<View style={{ elevation: 1, margin: 5, marginTop: 0, backgroundColor: modeInfo.backgroundColor }}>
{list}
</View>
)
}
hasComment = false
hasReadMore = false
renderComment = (commentList) => {
const { modeInfo } = this.props.screenProps
const { navigation } = this.props
const list: any[] = []
let readMore: any = null
for (const rowData of commentList) {
if (rowData.isGettingMoreComment === false) {
list.push(
<SimpleComment key={rowData.id || list.length} {...{
navigation,
rowData,
modeInfo,
onLongPress: () => {
this.onCommentLongPress(rowData)
},
index: list.length
}} />
)
} else {
readMore = (
<View key={'readmore'} style={{
backgroundColor: modeInfo.backgroundColor,
elevation: 1
}}>
<TouchableNativeFeedback
onPress={() => {
this._readMore(`${this.props.navigation.state.params.URL}/comment?page=1`)
}}
useForeground={true}
background={TouchableNativeFeedback.SelectableBackgroundBorderless()}
>
<View pointerEvents='box-only' style={{ flex: 1, flexDirection: 'row', padding: 12 }}>
<View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ flex: 2.5, color: accentColor }}>{'阅读更多评论'}</Text>
</View>
</View>
</TouchableNativeFeedback>
</View>
)
}
}
const shouldMarginTop = !this.hasContent && !this.hasTrophyTable
return (
<View style={{ marginTop: shouldMarginTop ? 5 : 0 }}>
{readMore && <View style={{ elevation: 1,
margin: 5, marginTop: 0, marginBottom: 5, backgroundColor: modeInfo.backgroundColor }}>{readMore}</View>}
<View style={{ elevation: 1, margin: 5, marginTop: 0, backgroundColor: modeInfo.backgroundColor }}>
{list}
</View>
{readMore && <View style={{ elevation: 1,
margin: 5, marginTop: 0, marginBottom: 5, backgroundColor: modeInfo.backgroundColor }}>{readMore}</View>}
</View>
)
}
isReplyShowing = false
onCommentLongPress = (rowData) => {
if (this.isReplyShowing === true) return
const { params } = this.props.navigation.state
this.props.navigation.navigate('Reply', {
type: params.type,
id: params.rowData.id,
at: rowData.psnid,
shouldSeeBackground: true
})
}
_readMore = (URL) => {
this.props.navigation.navigate('CommentList', {
URL
})
}
render() {
const { params } = this.props.navigation.state
// console.log('CommunityTopic.js rendered');
const { modeInfo } = this.props.screenProps
const { data: source } = this.state
const data: any[] = []
const renderFuncArr: any[] = []
const shouldPushData = !this.state.isLoading
if (shouldPushData) {
data.push(source.contentInfo.game)
renderFuncArr.push(this.renderGame)
}
if (shouldPushData && this.hasTrophyTable) {
data.push(source.contentInfo.trophyTable)
renderFuncArr.push(this.renderTrophyTable)
}
if (shouldPushData && this.hasContent) {
data.push(this.state.mainContent)
renderFuncArr.push(this.renderContent)
}
if (shouldPushData && this.hasComment) {
data.push(this.state.commentList)
renderFuncArr.push(this.renderComment)
}
const targetActions: any = toolbarActions.slice()
if (shouldPushData && source.contentInfo.game && source.contentInfo.game.edit) {
targetActions.push(
{
title: '编辑', iconName: 'md-create', show: 'never', iconSize: 22, onPress: function () {
const { navigation } = this.props
navigation.navigate('NewBattle', {
URL: source.contentInfo.game.edit
})
}
}
)
targetActions.push({
title: '关闭', iconName: 'md-create', iconSize: 22, show: 'never',
onPress: function () {
const onPress = () => close({
type: 'battle',
id: params.URL.split('/').pop()
}).then(res => res.text()).then(html => html ? global.toast('关闭失败: ' + html) : global.toast('关闭成功'))
Alert.alert('提示', '关闭后,只有管理员和发布者可以看到本帖', [
{
text: '取消'
},
{
text: '继续关闭',
onPress: () => onPress()
}
])
}
})
}
return (
<View
style={{ flex: 1, backgroundColor: modeInfo.backgroundColor }}
onStartShouldSetResponder={() => false}
onMoveShouldSetResponder={() => false}
>
<Ionicons.ToolbarAndroid
navIconName='md-arrow-back'
overflowIconName='md-more'
iconColor={modeInfo.isNightMode ? '#000' : '#fff'}
title={params.title ? params.title : `No.${params.rowData.id}`}
titleColor={modeInfo.isNightMode ? '#000' : '#fff'}
style={[styles.toolbar, { backgroundColor: modeInfo.standardColor }]}
actions={targetActions}
onIconClicked={() => {
this.props.navigation.goBack()
}}
onActionSelected={(index) => targetActions[index].onPress.bind(this)()}
/>
{this.state.isLoading && (
<ActivityIndicator
animating={this.state.isLoading}
style={{
flex: 999,
justifyContent: 'center',
alignItems: 'center'
}}
color={modeInfo.accentColor}
size={50}
/>
)}
{!this.state.isLoading && <FlatList style={{
flex: -1,
backgroundColor: modeInfo.standardColor
}}
ref={flatlist => this.flatlist = flatlist}
data={data}
keyExtractor={(item, index) => item.id || index}
renderItem={({ item, index }) => {
return renderFuncArr[index](item)
}}
extraData={this.state}
windowSize={999}
disableVirtualization={true}
viewabilityConfig={{
minimumViewTime: 3000,
viewAreaCoveragePercentThreshold: 100,
waitForInteraction: true
}}
>
</FlatList>
}
</View>
)
}
flatlist: any = false
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: '#F5FCFF'
},
toolbar: {
backgroundColor: standardColor,
height: 56,
elevation: 4
},
selectedTitle: {
// backgroundColor: '#00ffff'
// fontSize: 20
},
avatar: {
width: 50,
height: 50
},
a: {
fontWeight: '300',
color: idColor // make links coloured pink
}
})
export default CommunityTopic | the_stack |
import fs from 'fs'
import type { Style } from 'windicss/utils/style'
import { StyleSheet } from 'windicss/utils/style'
import { CSSParser } from 'windicss/utils/parser'
import { generateCompletions } from 'windicss/utils'
import { createSingletonPromise } from '@antfu/utils'
import fg from 'fast-glob'
import _debug from 'debug'
import micromatch from 'micromatch'
import Processor from 'windicss'
import { htmlTags, preflightTags } from './constants'
import type { ResolvedOptions, UserOptions, WindiPluginUtilsOptions } from './options'
import { resolveOptions } from './resolveOptions'
import { exclude, include, kebabCase, partition, slash } from './utils'
import { buildAliasTransformer, transformGroups } from './transforms'
import { applyExtractors as _applyExtractors } from './extractors/helper'
import { regexClassSplitter } from './regexes'
export type CompletionsResult = ReturnType<typeof generateCompletions>
export type LayerName = 'base' | 'utilities' | 'components'
export const SupportedLayers = ['base', 'utilities', 'components'] as const
export interface LayerMeta {
cssCache?: string
timestamp?: number
}
export interface TransformCssOptions {
onLayerUpdated?: () => void
globaliseKeyframes?: boolean
}
export interface WindiPluginUtils {
init(): Promise<Processor>
ensureInit(): Promise<Processor>
extractFile(code: string, id?: string, applyTransform?: boolean): Promise<boolean>
applyExtractors: typeof _applyExtractors
generateCSS(layer?: LayerName): Promise<string>
getFiles(): Promise<string[]>
clearCache(clearAll?: boolean): void
transformCSS(css: string, id: string, transformOptions?: TransformCssOptions): string
transformGroups: typeof transformGroups
transformAlias: ReturnType<typeof buildAliasTransformer>
buildPendingStyles(): void
isDetectTarget(id: string): boolean
isScanTarget(id: string): boolean
isCssTransformTarget(id: string): boolean
isExcluded(id: string): boolean
scan(): Promise<void>
classesGenerated: Set<string>
classesPending: Set<string>
tagsGenerated: Set<string>
tagsPending: Set<string>
tagsAvailable: Set<string>
layersMeta: Record<LayerName, LayerMeta>
addClasses(classes: string[]): boolean
addTags(tags: string[]): boolean
getCompletions(): ReturnType<typeof generateCompletions>
lock(fn: () => Promise<void>): Promise<void>
waitLocks(): Promise<void>
initialized: boolean
options: ResolvedOptions
files: string[]
globs: string[]
processor: Processor
scanned: boolean
configFilePath: string | undefined
hasPending: boolean
}
export function createUtils(
userOptions: UserOptions | ResolvedOptions = {},
utilsOptions: WindiPluginUtilsOptions = {
name: 'windicss-plugin-utils',
},
) {
let options = {} as ResolvedOptions
const name = utilsOptions.name
const debug = {
config: _debug(`${name}:config`),
debug: _debug(`${name}:debug`),
compile: _debug(`${name}:compile`),
scan: _debug(`${name}:scan`),
scanGlob: _debug(`${name}:scan:glob`),
scanTransform: _debug(`${name}:scan:transform`),
detectClass: _debug(`${name}:detect:class`),
detectTag: _debug(`${name}:detect:tag`),
detectAttrs: _debug(`${name}:detect:attrs`),
compileLayer: _debug(`${name}:compile:layer`),
}
let processor: Processor
let completions: CompletionsResult | undefined
let files: string[] = []
const classesGenerated = new Set<string>()
const classesPending = new Set<string>()
const tagsGenerated = new Set<string>()
const tagsPending = new Set<string>()
const attrsGenerated = new Set<string>()
const tagsAvailable = new Set<string>()
const attributes: [string, string][] = []
let _transformAlias: ReturnType<typeof buildAliasTransformer> = () => null
const _locks: Promise<void>[] = []
function getCompletions() {
if (!completions)
completions = generateCompletions(processor)
return completions
}
async function getFiles() {
await ensureInit()
debug.scanGlob('include', options.scanOptions.include)
debug.scanGlob('exclude', options.scanOptions.exclude)
const files = await fg(
options.scanOptions.include,
{
cwd: options.root,
ignore: options.scanOptions.exclude,
onlyFiles: true,
absolute: true,
},
)
files.sort()
debug.scanGlob('files', files)
return files
}
let scanned = false
const scan = createSingletonPromise(async() => {
await ensureInit()
debug.scan('started')
files.push(...await getFiles())
const contents = await Promise.all(
files
.filter(id => isDetectTarget(id))
.map(async id => [await fs.promises.readFile(id, 'utf-8'), id]),
)
await Promise.all(contents.map(
async([content, id]) => {
if (isCssTransformTarget(id))
return transformCSS(content, id)
else
return extractFile(content, id, true)
},
))
scanned = true
debug.scan('finished')
})
function isExcluded(id: string) {
return micromatch.contains(slash(id), options.scanOptions.exclude, { dot: true })
}
function isIncluded(id: string) {
return micromatch.isMatch(slash(id), options.scanOptions.include)
}
function isDetectTarget(id: string) {
if (options.scanOptions.extraTransformTargets.detect.some(i => typeof i === 'string' ? i === id : i(id)))
return true
if (files.includes(id) || files.includes(id.slice(0, id.indexOf('?'))))
return true
id = slash(id)
return isIncluded(id) && !isExcluded(id)
}
function isScanTarget(id: string) {
return options.enableScan
? files.some(file => id.startsWith(file))
: isDetectTarget(id)
}
function isCssTransformTarget(id: string) {
if (options.scanOptions.extraTransformTargets.css.some(i => typeof i === 'string' ? i === id : i(id)))
return true
if (id.match(/\.(?:postcss|pcss|scss|sass|css|stylus|less)(?:$|\?)/i) && !isExcluded(id))
return true
return false
}
function addClasses(classes: string[]) {
let changed = false
classes.forEach((i) => {
if (!i || classesGenerated.has(i) || classesPending.has(i) || options.blocklist.has(i))
return
classesPending.add(i)
changed = true
})
return changed
}
function addTags(tags: string[]) {
if (options.preflightOptions.includeAll)
return false
let changed = false
tags.forEach((tag) => {
if (!tagsAvailable.has(tag))
tag = options.preflightOptions.alias[kebabCase(tag)]
if (options.preflightOptions.blocklist.has(tag))
return
if (tagsAvailable.has(tag) && !tagsPending.has(tag)) {
tagsPending.add(tag)
tagsAvailable.delete(tag)
changed = true
}
})
return changed
}
async function applyExtractors(code: string, id?: string) {
return await _applyExtractors(code, id, options.scanOptions.extractors)
}
async function extractFile(code: string, id?: string, applyTransform = true) {
if (applyTransform) {
code = _transformAlias(code, false)?.code ?? code
if (options.transformGroups)
code = transformGroups(code, false)?.code ?? code
}
if (id) {
debug.scanTransform(id)
for (const trans of options.scanOptions.transformers) {
const result = trans(code, id)
if (result != null)
code = result
}
}
const extractResult = await applyExtractors(code, id)
let changed = false
if (options.enablePreflight && !options.preflightOptions.includeAll) {
// preflight
changed = addTags(extractResult.tags || []) || changed
}
if (options.config.attributify) {
const extractedAttrs = extractResult.attributes
if (extractedAttrs?.names.length) {
extractedAttrs.names.forEach((name, i) => {
attributes.push([name, extractedAttrs.values[i]])
})
changed = true
}
// @ts-expect-error
changed = addClasses(extractedAttrs?.classes || extractResult.classes || []) || changed
}
else {
// classes
changed = addClasses(extractResult.classes || []) || changed
}
if (changed) {
debug.detectClass(classesPending)
debug.detectTag(tagsPending)
debug.detectAttrs(attributes)
}
return changed
}
function transformCSS(css: string, id: string, transformOptions?: TransformCssOptions) {
if (!options.transformCSS)
return css
const style = new CSSParser(css, processor).parse()
// if we should move locally scoped keyframes to the global stylesheet, avoids possible duplicates
if (transformOptions?.globaliseKeyframes) {
const [nonKeyframeBlocks, keyframeBlocks] = partition(style.children,
i => !i.atRules || !i.atRules[0].match(/keyframes (pulse|spin|ping|bounce)/),
)
// register the keyframe blocks to our global classes
updateLayers(keyframeBlocks, '__classes', false)
// set the children without the keyframes
style.children = nonKeyframeBlocks
}
const [layerBlocks, blocks] = partition(style.children, i => i.meta.group === 'layer-block' && SupportedLayers.includes(i.meta.type))
if (layerBlocks.length) {
updateLayers(layerBlocks, id)
style.children = blocks
}
const transformed = style.build()
if (layerBlocks.length)
transformOptions?.onLayerUpdated?.()
return transformed
}
const layers: Record<LayerName, LayerMeta> = {
base: {},
utilities: {},
components: {},
}
const layerStylesMap = new Map<string, Style[]>()
function updateLayers(styles: Style[], filepath: string, replace = true) {
const timestamp = +Date.now()
debug.compileLayer('update', filepath)
const changedLayers = new Set<LayerName>()
styles.forEach(i => changedLayers.add(i.meta.type))
if (replace) {
layerStylesMap.get(filepath)?.forEach(i => changedLayers.add(i.meta.type))
layerStylesMap.set(filepath, styles)
}
else {
const prevStyles = layerStylesMap.get(filepath) || []
layerStylesMap.set(filepath, prevStyles.concat(styles))
}
for (const name of changedLayers) {
const layer = layers[name]
if (layer) {
layer.timestamp = timestamp
layer.cssCache = undefined
}
}
}
function buildLayerCss(name: LayerName) {
const layer = layers[name]
if (layer.cssCache == null) {
const style = new StyleSheet(Array.from(layerStylesMap.values()).flatMap(i => i).filter(i => i.meta.type === name))
style.prefixer = options.config.prefixer ?? true
debug.compileLayer(name, style.children.length)
if (options.sortUtilities)
style.sort()
layer.cssCache = `/* windicss layer ${name} */\n${style.build()}`
}
return layer.cssCache
}
function buildPendingStyles() {
options.onBeforeGenerate?.({
classesPending,
tagsPending,
})
if (classesPending.size) {
const result = processor.interpret(Array.from(classesPending).join(' '))
if (result.success.length) {
debug.compile(`compiled ${result.success.length} classes out of ${classesPending.size}`)
debug.compile(result.success)
updateLayers(result.styleSheet.children, '__classes', false)
include(classesGenerated, result.success)
classesPending.clear()
}
}
if (options.enablePreflight) {
if (options.preflightOptions.includeAll) {
// only on initialize
if (!layerStylesMap.has('__preflights')) {
const preflightStyle = processor.preflight(
undefined,
options.preflightOptions.includeBase,
options.preflightOptions.includeGlobal,
options.preflightOptions.includePlugin,
)
updateLayers(preflightStyle.children, '__preflights', true)
}
}
else if (tagsPending.size) {
const preflightStyle = processor.preflight(
Array.from(tagsPending).map(i => `<${i}/>`).join(' '),
options.preflightOptions.includeBase,
options.preflightOptions.includeGlobal,
options.preflightOptions.includePlugin,
)
updateLayers(preflightStyle.children, '__preflights', false)
include(tagsGenerated, tagsPending)
tagsPending.clear()
}
}
if (options.config.attributify) {
if (attributes.length) {
const attributesObject: Record<string, string[]> = {}
attributes.forEach(([name, value]) => {
if (!attributesObject[name])
attributesObject[name] = []
attributesObject[name].push(...value.split(regexClassSplitter).filter(Boolean))
})
const attributifyStyle = processor.attributify(
attributesObject,
)
updateLayers(attributifyStyle.styleSheet.children, '__attributify', false)
attributes.length = 0
}
}
options.onGenerated?.({
classes: classesGenerated,
tags: tagsGenerated,
})
}
async function generateCSS(layer?: LayerName) {
await ensureInit()
if (options.enableScan && options.scanOptions.runOnStartup)
await scan()
buildPendingStyles()
return layer
? buildLayerCss(layer)
: [
buildLayerCss('base'),
buildLayerCss('components'),
buildLayerCss('utilities'),
].join('\n').trim()
}
function clearCache(clearAll = false) {
layers.base = {}
layers.utilities = {}
layers.components = {}
layerStylesMap.clear()
completions = undefined
if (clearAll) {
classesPending.clear()
tagsPending.clear()
tagsAvailable.clear()
}
else {
include(classesPending, classesGenerated)
include(tagsPending, tagsGenerated)
include(tagsPending, preflightTags)
}
include(tagsAvailable, htmlTags as any as string[])
include(classesPending, options.safelist)
include(tagsPending, options.preflightOptions.safelist)
exclude(tagsAvailable, preflightTags)
exclude(tagsAvailable, options.preflightOptions.safelist)
classesGenerated.clear()
tagsGenerated.clear()
attrsGenerated.clear()
}
async function lock(fn: () => Promise<void>) {
const p = fn()
_locks.push(p)
await p
const i = _locks.indexOf(p)
if (i >= 0)
_locks.splice(i, 1)
}
async function waitLocks() {
await Promise.all(_locks)
}
const utils: WindiPluginUtils = {
init,
ensureInit,
extractFile,
applyExtractors,
generateCSS,
getFiles,
clearCache,
transformCSS,
transformGroups,
get transformAlias() {
return _transformAlias
},
buildPendingStyles,
isDetectTarget,
isScanTarget,
isCssTransformTarget,
isExcluded,
scan,
classesGenerated,
classesPending,
tagsGenerated,
tagsPending,
tagsAvailable,
layersMeta: layers,
addClasses,
addTags,
getCompletions,
lock,
waitLocks,
get initialized() {
return !!processor
},
get options() {
return options
},
get files() {
return files
},
get globs() {
return options.scanOptions.include
},
get processor() {
return processor
},
get scanned() {
return scanned
},
get configFilePath() {
return options.configFilePath
},
get hasPending() {
return Boolean(tagsPending.size || classesPending.size)
},
}
async function _init() {
options = await resolveOptions(userOptions, utilsOptions, true)
files = []
processor = new Processor(options.config)
clearCache(false)
options.onInitialized?.(utils)
_transformAlias = buildAliasTransformer(options.config.alias)
return processor
}
// ensure only init once with `ensureInit`
let _promise_init: Promise<Processor> | undefined
async function init() {
_promise_init = _init()
return _promise_init
}
async function ensureInit(): Promise<Processor> {
if (processor)
return processor
if (!_promise_init)
_promise_init = _init()
return _promise_init
}
return utils
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [deepracer](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdeepracer.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Deepracer extends PolicyStatement {
public servicePrefix = 'deepracer';
/**
* Statement provider for service [deepracer](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdeepracer.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 add access for a private leaderboard
*
* Access Level: Write
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-manage-community-races.html
*/
public toAddLeaderboardAccessPermission() {
return this.to('AddLeaderboardAccessPermission');
}
/**
* Grants permission to get current admin multiuser configuration for this account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-admin-set-account-config.html
*/
public toAdminGetAccountConfig() {
return this.to('AdminGetAccountConfig');
}
/**
* Grants permission to list all deepracer users with their associated resources created under this account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-admin-list-associated-resources.html
*/
public toAdminListAssociatedResources() {
return this.to('AdminListAssociatedResources');
}
/**
* Grants permission to list user data for all users associated with this account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-admin-list-associated-users.html
*/
public toAdminListAssociatedUsers() {
return this.to('AdminListAssociatedUsers');
}
/**
* Grants permission to manage a user associated with this account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-admin-manage-user.html
*/
public toAdminManageUser() {
return this.to('AdminManageUser');
}
/**
* Grants permission to set configuration options for this account
*
* Access Level: Write
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-admin-set-account-config.html
*/
public toAdminSetAccountConfig() {
return this.to('AdminSetAccountConfig');
}
/**
* Grants permission to clone an existing DeepRacer model
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-console-train-evaluate-models.html#deepracer-clone-trained-model
*/
public toCloneReinforcementLearningModel() {
return this.to('CloneReinforcementLearningModel');
}
/**
* Grants permission to create a DeepRacer car in your garage
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-choose-race-type.html
*/
public toCreateCar() {
return this.to('CreateCar');
}
/**
* Grants permission to create a leaderboard
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-create-community-race.html
*/
public toCreateLeaderboard() {
return this.to('CreateLeaderboard');
}
/**
* Grants permission to create an access token for a private leaderboard
*
* Access Level: Write
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-manage-community-races.html
*/
public toCreateLeaderboardAccessToken() {
return this.to('CreateLeaderboardAccessToken');
}
/**
* Grants permission to submit a DeepRacer model to be evaluated for leaderboards
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-submit-model-to-leaderboard.html
*/
public toCreateLeaderboardSubmission() {
return this.to('CreateLeaderboardSubmission');
}
/**
* Grants permission to create ra einforcement learning model for DeepRacer
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-get-started-training-model.html
*/
public toCreateReinforcementLearningModel() {
return this.to('CreateReinforcementLearningModel');
}
/**
* Grants permission to delete a leaderboard
*
* Access Level: Write
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-manage-community-races.html
*/
public toDeleteLeaderboard() {
return this.to('DeleteLeaderboard');
}
/**
* Grants permission to delete a DeepRacer model
*
* Access Level: Write
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-get-started-training-model.html
*/
public toDeleteModel() {
return this.to('DeleteModel');
}
/**
* Grants permission to edit a leaderboard
*
* Access Level: Write
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-manage-community-races.html
*/
public toEditLeaderboard() {
return this.to('EditLeaderboard');
}
/**
* Grants permission to get current multiuser configuration for this account
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-admin-set-account-config.html
*/
public toGetAccountConfig() {
return this.to('GetAccountConfig');
}
/**
* Grants permission to retrieve the user's alias for submitting a DeepRacer model to leaderboards
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-submit-model-to-leaderboard.html
*/
public toGetAlias() {
return this.to('GetAlias');
}
/**
* Grants permission to download artifacts for an existing DeepRacer model
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-console-train-evaluate-models.html
*/
public toGetAssetUrl() {
return this.to('GetAssetUrl');
}
/**
* Grants permission to retrieve a specific DeepRacer car from your garage
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-choose-race-type.html
*/
public toGetCar() {
return this.to('GetCar');
}
/**
* Grants permission to view all the DeepRacer cars in your garage
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-choose-race-type.html
*/
public toGetCars() {
return this.to('GetCars');
}
/**
* Grants permission to retrieve information about an existing DeepRacer model's evaluation jobs
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-get-started-test-in-simulator.html
*/
public toGetEvaluation() {
return this.to('GetEvaluation');
}
/**
* Grants permission to retrieve information about how the latest submitted DeepRacer model for a user performed on a leaderboard
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-submit-model-to-leaderboard.html
*/
public toGetLatestUserSubmission() {
return this.to('GetLatestUserSubmission');
}
/**
* Grants permission to retrieve information about leaderboards
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-submit-model-to-leaderboard.html
*/
public toGetLeaderboard() {
return this.to('GetLeaderboard');
}
/**
* Grants permission to retrieve information about an existing DeepRacer model
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-get-started-training-model.html
*/
public toGetModel() {
return this.to('GetModel');
}
/**
* Grants permission to retrieve information about private leaderboards
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-join-community-race.html
*/
public toGetPrivateLeaderboard() {
return this.to('GetPrivateLeaderboard');
}
/**
* Grants permission to retrieve information about the performance of a user's DeepRacer model that got placed on a leaderboard
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-submit-model-to-leaderboard.html
*/
public toGetRankedUserSubmission() {
return this.to('GetRankedUserSubmission');
}
/**
* Grants permission to retrieve information about DeepRacer tracks
*
* Access Level: Read
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-console-train-evaluate-models.html
*/
public toGetTrack() {
return this.to('GetTrack');
}
/**
* Grants permission to retrieve information about an existing DeepRacer model's training job
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-get-started-training-model.html
*/
public toGetTrainingJob() {
return this.to('GetTrainingJob');
}
/**
* Grants permission to import a reinforcement learning model for DeepRacer
*
* Access Level: Write
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-troubleshooting-service-migration-errors.html
*/
public toImportModel() {
return this.to('ImportModel');
}
/**
* Grants permission to list a DeepRacer model's evaluation jobs
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-get-started-test-in-simulator.html
*/
public toListEvaluations() {
return this.to('ListEvaluations');
}
/**
* Grants permission to list all the DeepRacer model submissions of a user on a leaderboard
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-submit-model-to-leaderboard.html
*/
public toListLeaderboardSubmissions() {
return this.to('ListLeaderboardSubmissions');
}
/**
* Grants permission to list all the available leaderboards
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-submit-model-to-leaderboard.html
*/
public toListLeaderboards() {
return this.to('ListLeaderboards');
}
/**
* Grants permission to list all existing DeepRacer models
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-get-started-training-model.html
*/
public toListModels() {
return this.to('ListModels');
}
/**
* Grants permission to retrieve participant information about private leaderboards
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-join-community-race.html
*/
public toListPrivateLeaderboardParticipants() {
return this.to('ListPrivateLeaderboardParticipants');
}
/**
* Grants permission to list all the available private leaderboards
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-join-community-race.html
*/
public toListPrivateLeaderboards() {
return this.to('ListPrivateLeaderboards');
}
/**
* Grants permission to list all the subscribed private leaderboards
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-join-community-race.html
*/
public toListSubscribedPrivateLeaderboards() {
return this.to('ListSubscribedPrivateLeaderboards');
}
/**
* Grants permission to lists tag for a resource
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-tagging.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to list all DeepRacer tracks
*
* Access Level: Read
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-console-train-evaluate-models.html
*/
public toListTracks() {
return this.to('ListTracks');
}
/**
* Grants permission to list a DeepRacer model's training jobs
*
* Access Level: Read
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-get-started-training-model.html
*/
public toListTrainingJobs() {
return this.to('ListTrainingJobs');
}
/**
* Grants permission to migrate previous reinforcement learning models for DeepRacer
*
* Access Level: Write
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-troubleshooting-service-migration-errors.html
*/
public toMigrateModels() {
return this.to('MigrateModels');
}
/**
* Grants permission to performs the leaderboard operation mentioned in the operation attribute
*
* Access Level: Write
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-perform-leaderboard-operation.html
*/
public toPerformLeaderboardOperation() {
return this.to('PerformLeaderboardOperation');
}
/**
* Grants permission to remove access for a private leaderboard
*
* Access Level: Write
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-manage-community-races.html
*/
public toRemoveLeaderboardAccessPermission() {
return this.to('RemoveLeaderboardAccessPermission');
}
/**
* Grants permission to set the user's alias for submitting a DeepRacer model to leaderboards
*
* Access Level: Write
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-submit-model-to-leaderboard.html
*/
public toSetAlias() {
return this.to('SetAlias');
}
/**
* Grants permission to evaluate a DeepRacer model in a simulated environment
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-get-started-test-in-simulator.html
*/
public toStartEvaluation() {
return this.to('StartEvaluation');
}
/**
* Grants permission to stop DeepRacer model evaluations
*
* Access Level: Write
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-get-started-test-in-simulator.html
*/
public toStopEvaluation() {
return this.to('StopEvaluation');
}
/**
* Grants permission to stop training a DeepRacer model
*
* Access Level: Write
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-get-started-training-model.html
*/
public toStopTrainingReinforcementLearningModel() {
return this.to('StopTrainingReinforcementLearningModel');
}
/**
* Grants permission to tag a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-tagging.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to test reward functions for correctness
*
* Access Level: Write
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-console-train-evaluate-models.html#deepracer-train-models-define-reward-function
*/
public toTestRewardFunction() {
return this.to('TestRewardFunction');
}
/**
* Grants permission to untag a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-tagging.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update a DeepRacer car in your garage
*
* Access Level: Write
*
* Possible conditions:
* - .ifUserToken()
* - .ifMultiUser()
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-choose-race-type.html
*/
public toUpdateCar() {
return this.to('UpdateCar');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AddLeaderboardAccessPermission",
"AdminManageUser",
"AdminSetAccountConfig",
"CloneReinforcementLearningModel",
"CreateCar",
"CreateLeaderboard",
"CreateLeaderboardAccessToken",
"CreateLeaderboardSubmission",
"CreateReinforcementLearningModel",
"DeleteLeaderboard",
"DeleteModel",
"EditLeaderboard",
"ImportModel",
"MigrateModels",
"PerformLeaderboardOperation",
"RemoveLeaderboardAccessPermission",
"SetAlias",
"StartEvaluation",
"StopEvaluation",
"StopTrainingReinforcementLearningModel",
"TestRewardFunction",
"UpdateCar"
],
"Read": [
"AdminGetAccountConfig",
"AdminListAssociatedResources",
"AdminListAssociatedUsers",
"GetAccountConfig",
"GetAlias",
"GetAssetUrl",
"GetCar",
"GetCars",
"GetEvaluation",
"GetLatestUserSubmission",
"GetLeaderboard",
"GetModel",
"GetPrivateLeaderboard",
"GetRankedUserSubmission",
"GetTrack",
"GetTrainingJob",
"ListEvaluations",
"ListLeaderboardSubmissions",
"ListLeaderboards",
"ListModels",
"ListPrivateLeaderboardParticipants",
"ListPrivateLeaderboards",
"ListSubscribedPrivateLeaderboards",
"ListTagsForResource",
"ListTracks",
"ListTrainingJobs"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type car to the statement
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-choose-race-type.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onCar(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:deepracer:${Region}:${Account}:car/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type evaluation_job to the statement
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-get-started-test-in-simulator.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onEvaluationJob(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:deepracer:${Region}:${Account}:evaluation_job/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type leaderboard to the statement
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-submit-model-to-leaderboard.html
*
* @param resourceId - Identifier for the resourceId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onLeaderboard(resourceId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:deepracer:${Region}::leaderboard/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type leaderboard_evaluation_job to the statement
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-submit-model-to-leaderboard.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onLeaderboardEvaluationJob(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:deepracer:${Region}:${Account}:leaderboard_evaluation_job/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type reinforcement_learning_model to the statement
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-get-started-training-model.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onReinforcementLearningModel(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:deepracer:${Region}:${Account}:model/reinforcement_learning/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type track to the statement
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-console-train-evaluate-models.html
*
* @param resourceId - Identifier for the resourceId.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onTrack(resourceId: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:deepracer:${Region}::track/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type training_job to the statement
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/deepracer-get-started-training-model.html
*
* @param resourceId - Identifier for the resourceId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onTrainingJob(resourceId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:deepracer:${Region}:${Account}:training_job/${ResourceId}';
arn = arn.replace('${ResourceId}', resourceId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Filters access by multiuser flag
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/reference_policies_iam-condition-keys.html#condition-keys-multiuser
*
* Applies to actions:
* - .toAddLeaderboardAccessPermission()
* - .toCloneReinforcementLearningModel()
* - .toCreateCar()
* - .toCreateLeaderboard()
* - .toCreateLeaderboardAccessToken()
* - .toCreateLeaderboardSubmission()
* - .toCreateReinforcementLearningModel()
* - .toDeleteLeaderboard()
* - .toDeleteModel()
* - .toEditLeaderboard()
* - .toGetAccountConfig()
* - .toGetAlias()
* - .toGetAssetUrl()
* - .toGetCar()
* - .toGetCars()
* - .toGetEvaluation()
* - .toGetLatestUserSubmission()
* - .toGetLeaderboard()
* - .toGetModel()
* - .toGetPrivateLeaderboard()
* - .toGetRankedUserSubmission()
* - .toGetTrainingJob()
* - .toImportModel()
* - .toListEvaluations()
* - .toListLeaderboardSubmissions()
* - .toListLeaderboards()
* - .toListModels()
* - .toListPrivateLeaderboardParticipants()
* - .toListPrivateLeaderboards()
* - .toListSubscribedPrivateLeaderboards()
* - .toListTagsForResource()
* - .toListTrainingJobs()
* - .toPerformLeaderboardOperation()
* - .toRemoveLeaderboardAccessPermission()
* - .toSetAlias()
* - .toStartEvaluation()
* - .toStopEvaluation()
* - .toStopTrainingReinforcementLearningModel()
* - .toTagResource()
* - .toUntagResource()
* - .toUpdateCar()
*
* @param value `true` or `false`. **Default:** `true`
*/
public ifMultiUser(value?: boolean) {
return this.if(`MultiUser`, (typeof value !== 'undefined' ? value : true), 'Bool');
}
/**
* Filters access by user token in the request
*
* https://docs.aws.amazon.com/deepracer/latest/developerguide/reference_policies_iam-condition-keys.html#condition-keys-usertoken
*
* Applies to actions:
* - .toAddLeaderboardAccessPermission()
* - .toCloneReinforcementLearningModel()
* - .toCreateCar()
* - .toCreateLeaderboard()
* - .toCreateLeaderboardAccessToken()
* - .toCreateLeaderboardSubmission()
* - .toCreateReinforcementLearningModel()
* - .toDeleteLeaderboard()
* - .toDeleteModel()
* - .toEditLeaderboard()
* - .toGetAccountConfig()
* - .toGetAlias()
* - .toGetAssetUrl()
* - .toGetCar()
* - .toGetCars()
* - .toGetEvaluation()
* - .toGetLatestUserSubmission()
* - .toGetLeaderboard()
* - .toGetModel()
* - .toGetPrivateLeaderboard()
* - .toGetRankedUserSubmission()
* - .toGetTrainingJob()
* - .toImportModel()
* - .toListEvaluations()
* - .toListLeaderboardSubmissions()
* - .toListLeaderboards()
* - .toListModels()
* - .toListPrivateLeaderboardParticipants()
* - .toListPrivateLeaderboards()
* - .toListSubscribedPrivateLeaderboards()
* - .toListTagsForResource()
* - .toListTrainingJobs()
* - .toPerformLeaderboardOperation()
* - .toRemoveLeaderboardAccessPermission()
* - .toSetAlias()
* - .toStartEvaluation()
* - .toStopEvaluation()
* - .toStopTrainingReinforcementLearningModel()
* - .toTagResource()
* - .toUntagResource()
* - .toUpdateCar()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifUserToken(value: string | string[], operator?: Operator | string) {
return this.if(`UserToken`, value, operator || 'StringLike');
}
} | the_stack |
import {Get, Post, Delete, Param, BodyParam, CurrentUser, Authorized,
UseBefore, JsonController, BadRequestError, ForbiddenError, NotFoundError, InternalServerError} from 'routing-controllers';
import passportJwtMiddleware from '../security/passportJwtMiddleware';
import {NotificationSettings, API_NOTIFICATION_TYPE_ALL_CHANGES} from '../models/NotificationSettings';
import {Notification} from '../models/Notification';
import {Course, ICourseModel} from '../models/Course';
import {Lecture, ILectureModel} from '../models/Lecture';
import {Unit, IUnitModel} from '../models/units/Unit';
import {User} from '../models/User';
import {ICourse} from '../../../shared/models/ICourse';
import {ILecture} from '../../../shared/models/ILecture';
import {IUnit} from '../../../shared/models/units/IUnit';
import {IUser} from '../../../shared/models/IUser';
import {SendMailOptions} from 'nodemailer';
import emailService from '../services/EmailService';
import {errorCodes} from '../config/errorCodes';
@JsonController('/notification')
@UseBefore(passportJwtMiddleware)
export class NotificationController {
static async resolveTarget(targetId: string, targetType: string, currentUser: IUser) {
let course: ICourseModel;
let lecture: ILectureModel;
let unit: IUnitModel;
switch (targetType) {
case 'course':
course = await Course.findById(targetId).orFail(new NotFoundError());
break;
case 'lecture':
lecture = await Lecture.findById(targetId).orFail(new NotFoundError());
course = await Course.findOne({lectures: targetId})
.orFail(new InternalServerError(errorCodes.notification.missingCourseOfLecture.text));
break;
case 'unit':
unit = await Unit.findById(targetId).orFail(new NotFoundError());
course = await Course.findById(unit._course)
.orFail(new InternalServerError(errorCodes.notification.missingCourseOfUnit.text));
break;
default:
throw new BadRequestError(errorCodes.notification.invalidTargetType.text);
}
if (!course.checkPrivileges(currentUser).userCanEditCourse) {
throw new ForbiddenError();
}
return {course, lecture, unit};
}
/**
* @api {post} /api/notification/ Create notifications
* @apiName PostNotifications
* @apiGroup Notification
* @apiPermission teacher
* @apiPermission admin
*
* @apiParam {String} targetId Target id of the changed course, lecture or unit.
* @apiParam {String} targetType Which type the targetId represents: Either 'course', 'lecture' or 'unit'.
* @apiParam {String} text Message that the new notification(s) will contain.
*
* @apiSuccess {Object} result Empty object.
*
* @apiSuccessExample {json} Success-Response:
* {}
*
* @apiError NotFoundError Did not find the targetId of targetType.
* @apiError BadRequestError Invalid targetType.
* @apiError ForbiddenError The teacher doesn't have access to the corresponding course.
* @apiError InternalServerError No course was found for a given existing lecture.
* @apiError InternalServerError No course was found for a given existing unit.
*/
@Authorized(['teacher', 'admin'])
@Post('/')
async createNotifications(@BodyParam('targetId', {required: true}) targetId: string,
@BodyParam('targetType', {required: true}) targetType: string,
@BodyParam('text', {required: true}) text: string,
@CurrentUser() currentUser: IUser) {
const {course, lecture, unit} = await NotificationController.resolveTarget(targetId, targetType, currentUser);
await Promise.all(course.students.map(async student => {
if (await this.shouldCreateNotification(student, course, unit)) {
await this.createNotification(student, text, course, lecture, unit);
}
}));
return {};
}
/**
* @api {post} /api/notification/user/:id Create notification for user
* @apiName PostNotification
* @apiGroup Notification
* @apiPermission teacher
* @apiPermission admin
*
* @apiParam {String} id ID of the user that the new notification is assigned/sent to.
* @apiParam {String} targetId Target id of the changed course, lecture or unit.
* @apiParam {String} targetType Which type the targetId represents: Either 'course', 'lecture', 'unit' or 'text'.
* The 'text' type only uses the 'text' parameter while ignoring the 'targetId'.
* @apiParam {String} text Message that the new notification(s) will contain.
*
* @apiSuccess {Object} result Empty object.
*
* @apiSuccessExample {json} Success-Response:
* {}
*
* @apiError NotFoundError Did not find the targetId of targetType.
* @apiError BadRequestError Invalid targetType.
* @apiError ForbiddenError The teacher doesn't have access to the corresponding course (if targetType isn't 'text'-only).
* @apiError InternalServerError No course was found for a given existing lecture.
* @apiError InternalServerError No course was found for a given existing unit.
*/
@Authorized(['teacher', 'admin'])
@Post('/user/:id')
async createNotificationForStudent(@Param('id') userId: string,
@BodyParam('targetId', {required: false}) targetId: string,
@BodyParam('targetType', {required: true}) targetType: string,
@BodyParam('text', {required: false}) text: string,
@CurrentUser() currentUser: IUser) {
if (targetType === 'text' && !text) {
throw new BadRequestError(errorCodes.notification.textOnlyWithoutText.text);
}
const {course, lecture, unit} = targetType === 'text'
? {course: undefined, lecture: undefined, unit: undefined}
: await NotificationController.resolveTarget(targetId, targetType, currentUser);
const user = await User.findById(userId).orFail(new NotFoundError(errorCodes.notification.targetUserNotFound.text));
if (await this.shouldCreateNotification(user, course, unit)) {
await this.createNotification(user, text, course, lecture, unit);
}
return {};
}
async shouldCreateNotification(user: IUser, changedCourse: ICourseModel, changedUnit?: IUnitModel) {
if (!changedCourse && !changedUnit) {
// The notificaiton does not depend on any unit/course. We can create a notification.
return true;
}
if (!changedUnit) {
return !(await Notification.findOne({user, changedCourse}));
}
return !(await Notification.findOne({user, changedUnit}));
}
async createNotification(user: IUser, text: string, changedCourse?: ICourse, changedLecture?: ILecture, changedUnit?: IUnit) {
// create no notification if course is not active
if (changedCourse && !changedCourse.active) {
return;
}
// create no notification for unit if unit is invisible
if (changedUnit && !changedUnit.visible) {
return;
}
const notification = new Notification();
notification.user = user;
notification.text = text;
notification.isOld = false;
if (changedCourse) {
notification.changedCourse = changedCourse;
const settings = await this.getOrCreateSettings(user, changedCourse);
if (settings.notificationType === API_NOTIFICATION_TYPE_ALL_CHANGES) {
if (changedLecture) {
notification.changedLecture = changedLecture;
}
if (changedUnit) {
notification.changedUnit = changedUnit;
}
if (settings.emailNotification) {
await this.sendNotificationMail(user, 'you received new notifications for the course ' + changedCourse.name + '.');
}
}
}
return await notification.save();
}
async getOrCreateSettings(user: IUser, changedCourse: ICourse) {
let settings = await NotificationSettings.findOne({'user': user, 'course': changedCourse});
if (settings === undefined || settings === null) {
settings = await new NotificationSettings({
user: user,
course: changedCourse,
notificationType: API_NOTIFICATION_TYPE_ALL_CHANGES,
emailNotification: false
}).save();
}
return settings;
}
async sendNotificationMail(user: IUser, text: string) {
const message: SendMailOptions = {};
user = await User.findById(user);
message.to = user.profile.firstName + ' ' + user.profile.lastName + '<' + user.email + '>';
message.subject = 'Geli informs: you have new notifications :)';
message.text = 'Hello ' + user.profile.firstName + ', \n\n' +
+text + '\n' + 'Please check your notifications in geli.\n' +
'Your GELI Team.';
message.html = '<p>Hello ' + user.profile.firstName + ',</p><br>' +
'<p>' + text + '<br>Please check your notifications in geli.</p><br>' +
'<p>Your GELI Team.</p>';
await emailService.sendFreeFormMail(message);
}
/**
* @api {get} /api/notification/ Get own notifications
* @apiName GetNotifications
* @apiGroup Notification
* @apiPermission student
* @apiPermission teacher
* @apiPermission admin
*
* @apiSuccess {INotificationView[]} notifications List of notifications.
*
* @apiSuccessExample {json} Success-Response:
* [{
* "_id": "5ab2fbe464efe60006cef0b1",
* "changedCourse": "5c0fb47d8d583532143c68a7",
* "changedLecture": "5bdb49f11a09bb3ca8ce0a10",
* "changedUnit": "5be0691ee3859d38308dab18",
* "text": "Course ProblemSolver has an updated text unit.",
* "isOld": false
* }, {
* "_id": "5ab2fc7b64efe60006cef0bb",
* "changedCourse": "5be0691ee3859d38308dab19",
* "changedLecture": "5bdb49ef1a09bb3ca8ce0a01",
* "changedUnit": "5bdb49f11a09bb3ca8ce0a12",
* "text": "Course katacourse has an updated unit.",
* "isOld": false
* }]
*/
@Authorized(['student', 'teacher', 'admin'])
@Get('/')
async getNotifications(@CurrentUser() currentUser: IUser) {
const notifications = await Notification.find({user: currentUser});
return notifications.map(notification => notification.forView());
}
/**
* @api {delete} /api/notification/:id Delete notification
* @apiName DeleteNotification
* @apiGroup Notification
* @apiPermission student
* @apiPermission teacher
* @apiPermission admin
*
* @apiParam {String} id Notification ID.
*
* @apiSuccess {Object} result Empty object.
*
* @apiSuccessExample {json} Success-Response:
* {}
*
* @apiError NotFoundError Notification could not be found.
*/
@Authorized(['student', 'teacher', 'admin'])
@Delete('/:id')
async deleteNotification(@Param('id') id: string, @CurrentUser() currentUser: IUser) {
const notification = await Notification.findOne({_id: id, user: currentUser}).orFail(new NotFoundError());
await notification.remove();
return {};
}
} | the_stack |
import {
parse,
isLeafType,
visit,
GraphQLNamedType,
GraphQLSchema,
Visitor,
ASTKindToNode,
GraphQLField,
DocumentNode,
ASTNode,
getNamedType,
TypeInfo,
visitWithTypeInfo,
FieldNode,
InlineFragmentNode,
GraphQLObjectType,
GraphQLUnionType,
print,
isScalarType,
} from 'graphql'
import set from 'lodash.set'
type VisitorType = Visitor<ASTKindToNode, ASTNode>
/**
*
* Given a valid GraphQL query,the `formify` will populate the query
* with additional information needed by Tina on the frontend so we're able
* to render a Tina form.
*
* ```graphql
* query getPostsDocument($relativePath: String!) {
* getPostsDocument(relativePath: $relativePath) {
* data {
* ... on Post_Doc_Data {
* title
* }
* }
* }
* }
* ```
* Would become:
* ```graphql
* query getPostsDocument($relativePath: String!) {
* getPostsDocument(relativePath: $relativePath) {
* data {
* ... on Post_Doc_Data {
* title
* }
* }
* form {
* __typename
* ... on Post_Doc_Form {
* label
* name
* fields {
* # ...
* }
* }
* }
* values {
* __typename
* ... on Post_Doc_Values {
* title
* author
* image
* hashtags
* _body
* _template
* }
* }
* sys {
* filename
* basename
* breadcrumbs
* path
* relativePath
* extension
* }
* }
* }
* ```
*/
export const formify = (query: DocumentNode, schema: GraphQLSchema) => {
const typeInfo = new TypeInfo(schema)
const pathsToPopulate: {
path: string
paths: {
path: string[]
ast: object
}[]
}[] = []
const visitor: VisitorType = {
leave(node, key, parent, path, ancestors) {
const type = typeInfo.getType()
if (type) {
const namedType = getNamedType(type)
if (namedType instanceof GraphQLObjectType) {
const hasNodeInterface = !!namedType
.getInterfaces()
.find(i => i.name === 'Node')
if (hasNodeInterface) {
// Instead of this, there's probably a more fine-grained visitor key to use
if (typeof path[path.length - 1] === 'number') {
assertIsObjectType(namedType)
const valuesNode = namedType.getFields().values
const namedValuesNode = getNamedType(
valuesNode.type
) as GraphQLNamedType
const pathForValues = [...path]
pathForValues.push('selectionSet')
pathForValues.push('selections')
const valuesAst = buildValuesForType(namedValuesNode)
// High number to make sure this index isn't taken
// might be more performant for it to be a low number though
// use setWith instead
pathForValues.push(100)
const formNode = namedType.getFields().form
const namedFormNode = getNamedType(
formNode.type
) as GraphQLNamedType
const pathForForm = [...path]
pathForForm.push('selectionSet')
pathForForm.push('selections')
// High number to make sure this index isn't taken
// might be more performant for it to be a low number though
// use setWith instead
const formAst = buildFormForType(namedFormNode)
pathForForm.push(101)
const sysNode = namedType.getFields().sys
const namedSysNode = getNamedType(
sysNode.type
) as GraphQLNamedType
const pathForSys = [...path]
pathForSys.push('selectionSet')
pathForSys.push('selections')
const sysAst = buildSysForType(namedSysNode)
pathForSys.push(102)
pathsToPopulate.push({
path: path.map(p => p.toString()).join('-'),
paths: [
{
path: pathForValues.map(p => p.toString()),
ast: valuesAst,
},
{
path: pathForForm.map(p => p.toString()),
ast: formAst,
},
{
path: pathForSys.map(p => p.toString()),
ast: sysAst,
},
],
})
}
}
}
}
},
}
visit(query, visitWithTypeInfo(typeInfo, visitor))
// We don't want to build form/value fields for nested nodes (for now)
// so filter out paths which aren't "top-level" ones
const topLevelPaths = pathsToPopulate.filter((p, i) => {
const otherPaths = pathsToPopulate.filter((_, index) => index !== i)
const isChildOfOtherPaths = otherPaths.some(op => {
if (p.path.startsWith(op.path)) {
return true
} else {
return false
}
})
if (isChildOfOtherPaths) {
return false
} else {
return true
}
})
topLevelPaths.map(p => {
p.paths.map(pathNode => {
set(query, pathNode.path, pathNode.ast)
})
})
return query
}
/**
*
* Builds out `sys` values except for `section`
*
* TODO: if `sys` is already provided, use that, or provide
* an alias query for this node
*
*/
const buildSysForType = (type: GraphQLNamedType): FieldNode => {
assertIsObjectType(type)
return {
kind: 'Field' as const,
alias: {
kind: 'Name',
value: '_internalSys',
},
name: {
kind: 'Name' as const,
value: 'sys',
},
selectionSet: {
kind: 'SelectionSet' as const,
selections: buildSelectionsFields(
Object.values(type.getFields()),
fields => {
return {
continue: true,
// prevent infinite loop by not include documents
filteredFields: fields.filter(field => field.name !== 'documents'),
}
}
),
},
}
}
const buildValuesForType = (type: GraphQLNamedType): FieldNode => {
try {
assertIsUnionType(type)
return {
kind: 'Field' as const,
name: {
kind: 'Name' as const,
value: 'values',
},
selectionSet: {
kind: 'SelectionSet' as const,
selections: buildSelectionInlineFragments(type.getTypes()),
},
}
} catch (e) {
// FIXME: PRIMITIVE types
return {
kind: 'Field' as const,
name: {
kind: 'Name' as const,
value: 'values',
},
}
}
}
const buildFormForType = (type: GraphQLNamedType): FieldNode => {
try {
assertIsUnionType(type)
return {
kind: 'Field' as const,
name: {
kind: 'Name' as const,
value: 'form',
},
selectionSet: {
kind: 'SelectionSet' as const,
selections: buildSelectionInlineFragments(type.getTypes()),
},
}
} catch (e) {
// FIXME: PRIMITIVE types
return {
kind: 'Field' as const,
name: {
kind: 'Name' as const,
value: 'form',
},
}
}
}
const buildSelectionInlineFragments = (
types: GraphQLObjectType<any, any>[],
callback?: (
fields: GraphQLField<any, any>[]
) => {
continue: boolean
filteredFields: GraphQLField<any, any>[]
}
): InlineFragmentNode[] => {
return types.map(type => {
return {
kind: 'InlineFragment' as const,
typeCondition: {
kind: 'NamedType' as const,
name: {
kind: 'Name' as const,
value: type.name,
},
},
selectionSet: {
kind: 'SelectionSet' as const,
selections: [
...Object.values(type.getFields()).map(
(field): FieldNode => {
const namedType = getNamedType(field.type)
if (isLeafType(namedType)) {
return {
kind: 'Field' as const,
name: {
kind: 'Name' as const,
value: field.name,
},
}
} else if (namedType instanceof GraphQLUnionType) {
return {
kind: 'Field' as const,
name: {
kind: 'Name' as const,
value: field.name,
},
selectionSet: {
kind: 'SelectionSet' as const,
selections: [
...buildSelectionInlineFragments(
namedType.getTypes(),
callback
),
],
},
}
} else if (namedType instanceof GraphQLObjectType) {
return {
kind: 'Field' as const,
name: {
kind: 'Name' as const,
value: field.name,
},
selectionSet: {
kind: 'SelectionSet' as const,
selections: [
...buildSelectionsFields(
Object.values(namedType.getFields()),
callback
),
],
},
}
} else {
throw new Error(
`Unexpected GraphQL type for field ${namedType.name}`
)
}
}
),
],
},
}
})
}
export const buildSelectionsFields = (
fields: GraphQLField<any, any>[],
callback?: (
fields: GraphQLField<any, any>[]
) => {
continue: boolean
filteredFields: GraphQLField<any, any>[]
}
): FieldNode[] => {
let filteredFields = fields
if (callback) {
const result = callback(fields)
if (!result.continue) {
if (
fields.every(field => {
return !isScalarType(getNamedType(field.type))
})
) {
return [
{
kind: 'Field' as const,
name: {
kind: 'Name' as const,
value: '__typename',
},
},
]
}
return buildSelectionsFields(
result.filteredFields.filter(field => {
if (isScalarType(getNamedType(field.type))) {
return true
}
return false
})
)
} else {
filteredFields = result.filteredFields
}
}
return filteredFields.map(
(field): FieldNode => {
const namedType = getNamedType(field.type)
if (isLeafType(namedType)) {
return {
kind: 'Field' as const,
name: {
kind: 'Name' as const,
value: field.name,
},
}
} else if (namedType instanceof GraphQLUnionType) {
return {
kind: 'Field' as const,
name: {
kind: 'Name' as const,
value: field.name,
},
selectionSet: {
kind: 'SelectionSet' as const,
selections: [
...buildSelectionInlineFragments(namedType.getTypes(), callback),
],
},
}
} else if (namedType instanceof GraphQLObjectType) {
return {
kind: 'Field' as const,
name: {
kind: 'Name' as const,
value: field.name,
},
selectionSet: {
kind: 'SelectionSet' as const,
selections: [
...buildSelectionsFields(
Object.values(namedType.getFields()),
callback
),
],
},
}
} else {
return {
kind: 'Field' as const,
name: {
kind: 'Name' as const,
value: field.name,
},
selectionSet: {
kind: 'SelectionSet' as const,
selections: [],
},
}
}
}
)
}
function assertIsObjectType(
type: GraphQLNamedType
): asserts type is GraphQLObjectType {
if (type instanceof GraphQLObjectType) {
// do nothing
} else {
throw new Error(
`Expected an instance of GraphQLObjectType for type ${type.name}`
)
}
}
function assertIsUnionType(
type: GraphQLNamedType
): asserts type is GraphQLUnionType {
if (type instanceof GraphQLUnionType) {
// do nothing
} else {
throw new Error(
`Expected an instance of GraphQLUnionType for type ${type.name}`
)
}
} | the_stack |
import {
options, cleanNode
} from '@tko/utils'
import {
observable, observableArray
} from '@tko/observable'
import {
computed
} from '@tko/computed'
import {
NativeProvider
} from '@tko/provider.native'
import {
VirtualProvider
} from '@tko/provider.virtual'
import {
applyBindings, contextFor
} from '@tko/bind'
import {
ComponentABC
} from '@tko/utils.component'
import {
bindings as componentBindings
} from '@tko/binding.component'
import {
ComponentProvider
} from '@tko/provider.component'
import {
JsxObserver
} from '../dist'
import { ORIGINAL_JSX_SYM } from '../dist/JsxObserver';
class JsxTestObserver extends JsxObserver {
// For testing purposes, we make this synchronous.
detachAndDispose (node) {
super.detachAndDispose(node)
cleanNode(node)
}
}
/**
* Simple wrapper for testing.
*/
function jsxToNode (jsx, xmlns, node = document.createElement('div')) {
new JsxTestObserver(jsx, node, null, xmlns)
return node.childNodes[0]
}
describe('jsx', function () {
it('converts a simple node', () => {
window.o = observableArray
const node = jsxToNode({
elementName: "abc-def",
children: [],
attributes: {'aaa': 'bbb' }
})
assert.equal(node.outerHTML,
'<abc-def aaa="bbb"></abc-def>')
})
it('converts a node with children', () => {
const child = {
elementName: "div-som",
children: [],
attributes: { 'attrx': 'y' }
}
const node = jsxToNode({
elementName: "abc-def",
children: ['some text', child, 'more text'],
attributes: {'aaa': 'bbb' }
})
assert.equal(node.outerHTML, `<abc-def aaa="bbb">` +
`some text` +
`<div-som attrx="y"></div-som>` +
`more text</abc-def>`)
})
it('unwraps and monitors the parameter', function () {
const obs = observable()
const parent = document.createElement('div')
const jo = new JsxTestObserver(obs, parent)
const child0 = parent.childNodes[0]
assert.instanceOf(child0, Comment)
assert.equal(child0.nodeValue, 'O')
assert.strictEqual(child0, parent.childNodes[0])
obs('text')
assert.lengthOf(parent.childNodes, 2)
assert.instanceOf(parent.childNodes[0], Text)
assert.equal(parent.childNodes[0].nodeValue, 'text')
obs({elementName: 'b', attributes: {}, children: []})
assert.equal(parent.innerHTML, '<b></b><!--O-->')
obs(undefined)
assert.equal(parent.innerHTML, '<!--O-->')
})
it('interjects a text observable', function () {
const obs = observable('zzz')
const child = {
elementName: "span",
children: [obs],
attributes: {}
}
const node = jsxToNode({
elementName: "div",
children: ['x', child, obs, 'y'],
attributes: {}
})
assert.equal(node.outerHTML, '<div>x<span>zzz<!--O--></span>zzz<!--O-->y</div>')
obs('fff')
assert.equal(node.outerHTML, '<div>x<span>fff<!--O--></span>fff<!--O-->y</div>')
})
it('interjects child nodes', function () {
const obs = observable({
elementName: 'span', children: [], attributes: { in: 'x' }
})
const node = jsxToNode({
elementName: "div",
children: ['x', obs, 'y'],
attributes: { }
})
assert.equal(node.outerHTML, '<div>x<span in="x"></span><!--O-->y</div>')
obs(undefined)
assert.equal(node.outerHTML, '<div>x<!--O-->y</div>')
obs({
elementName: 'abbr', children: [], attributes: { in: 'y' }
})
assert.equal(node.outerHTML, '<div>x<abbr in="y"></abbr><!--O-->y</div>')
})
it('updates from observable child nodes', function () {
const obs = observable(["abc", {
elementName: 'span', children: [], attributes: { in: 'x' }
}, "def"])
const node = jsxToNode({ elementName: "div", children: obs, attributes: { } })
assert.equal(node.outerHTML, '<div>abc<span in="x"></span>def<!--O--></div>')
obs(undefined)
assert.equal(node.outerHTML, '<div><!--O--></div>')
obs(['x', {
elementName: 'abbr', children: [], attributes: { in: 'y' }
}, 'y'])
assert.equal(node.outerHTML, '<div>x<abbr in="y"></abbr>y<!--O--></div>')
})
it('tracks observables in observable arrays', function () {
const obs = observable([])
const o2 = observable()
const node = jsxToNode({ elementName: "i", children: obs, attributes: { } })
assert.equal(node.outerHTML, '<i><!--O--></i>')
obs([o2])
assert.equal(node.outerHTML, '<i><!--O--></i>')
o2('text')
assert.equal(node.outerHTML, '<i>text<!--O--></i>')
o2(['123', '456'])
assert.equal(node.outerHTML, '<i>123456<!--O--></i>')
o2([])
assert.equal(node.outerHTML, '<i><!--O--></i>')
o2('r2d2')
assert.equal(node.outerHTML, '<i>r2d2<!--O--></i>')
})
it('does not unwrap observables for binding handlers', function () {
const obs = observable('x')
const node = jsxToNode({
elementName: 'div',
children: [],
attributes: { 'ko-x': obs, 'ko-y': 'z', 'any': obs, 'any2': 'e' }
})
const nodeValues = NativeProvider.getNodeValues(node)
assert.strictEqual(nodeValues['ko-x'], obs)
assert.equal(nodeValues['ko-y'], 'z')
assert.strictEqual(nodeValues['any'], obs)
assert.equal(nodeValues['any2'], 'e')
})
it('inserts after a comment parent-node', () => {
const parent = document.createElement('div')
const comment = document.createComment('comment-parent')
parent.appendChild(comment)
parent.appendChild(document.createComment('end'))
const o = new JsxTestObserver('r', comment)
assert.equal(parent.innerHTML, `<!--comment-parent-->r<!--end-->`)
})
it('inserts SVG nodes and children correctly', function () {
const obs = observable()
const circle = { elementName: 'circle', children: [], attributes: {} }
const svg = { elementName: 'svg', children: [circle, obs], attributes: { abc: '123' } }
const node = jsxToNode(svg)
assert.instanceOf(node, SVGElement)
assert.instanceOf(node.childNodes[0], SVGElement)
assert.lengthOf(node.childNodes, 2)
obs({ elementName: 'rect', children: [], attributes: {} })
assert.equal(node.childNodes[1].tagName, 'rect')
assert.instanceOf(node.childNodes[1], SVGElement)
assert.equal(node.outerHTML, '<svg abc="123"><circle></circle><rect></rect><!--O--></svg>')
})
it('inserts actual nodes correctly', () => {
const parent = document.createElement('div')
const itag = document.createElement('i')
const jsx = { elementName: 'div', children: [itag], attributes: {} }
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `<div><i></i></div>`)
jo.dispose()
})
it('inserts multiple nodes', () => {
const parent = document.createElement('div')
const itag = document.createElement('i')
const btag = document.createElement('b')
const jsx = { elementName: 'div', children: [itag, btag], attributes: {} }
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `<div><i></i><b></b></div>`)
jo.dispose()
})
it('moves nodes inserted multiple times', () => {
const parent = document.createElement('div')
const itag = document.createElement('i')
const jsx = { elementName: 'div', children: [itag, itag], attributes: {} }
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `<div><i></i></div>`)
jo.dispose()
})
it('injects a cloneable (JSX) node twice', () => {
const parent = document.createElement('div')
const itag = { elementName: 'i', children: [], attributes: { 'ko-counter': 'abc' }}
const io = observable()
const jsx = { elementName: 'div', children: [itag, io], attributes: {} }
const jo = new JsxTestObserver(jsx, parent)
let counter = 0
const provider = new NativeProvider()
options.bindingProviderInstance = provider
provider.bindingHandlers.set({ counter: () => ++counter })
applyBindings({ abc: '123' }, parent)
assert.equal(counter, 1)
const inode = parent.children[0].children[0]
io(inode) // <i ko-counter />
assert.equal(counter, 2)
jo.dispose()
})
it('errors injecting a non-JSX node with bindings twice', () => {
const parent = document.createElement('div')
const itag = { elementName: 'i', children: [], attributes: { 'ko-counter': 'abc' }}
const io = observable()
const jsx = { elementName: 'div', children: [itag, io], attributes: {} }
const jo = new JsxTestObserver(jsx, parent)
let counter = 0
const provider = new NativeProvider()
options.bindingProviderInstance = provider
provider.bindingHandlers.set({ counter: () => ++counter })
applyBindings({ abc: '123' }, parent)
assert.equal(counter, 1)
const inode = parent.children[0].children[0]
delete inode[ORIGINAL_JSX_SYM]
assert.throws(() => io(inode), /You cannot apply bindings multiple times/)
jo.dispose()
})
it('errors injecting a non-JSX node with binding child twice', () => {
const parent = document.createElement('div')
const itag = { elementName: 'i', children: [], attributes: { 'ko-counter': 'abc' } }
const btag = { elementName: 'b', children: [itag], attributes: {} }
const io = observable()
const jsx = { elementName: 'div', children: [btag, io], attributes: {} }
const jo = new JsxTestObserver(jsx, parent)
let counter = 0
const provider = new NativeProvider()
options.bindingProviderInstance = provider
provider.bindingHandlers.set({ counter: () => ++counter })
applyBindings({ abc: '123' }, parent)
assert.equal(counter, 1)
const inode = parent.children[0].children[0]
delete inode[ORIGINAL_JSX_SYM]
assert.throws(() => io(inode), /You cannot apply bindings multiple times/)
jo.dispose()
})
it('moves (remove+append) non-JSX nodes with no bindings', () => {
const parent = document.createElement('div')
const itag = document.createElement('i')
const io = observable()
const jsx = { elementName: 'div', children: [itag, io], attributes: {} }
const jo = new JsxTestObserver(jsx, parent)
const provider = new NativeProvider()
options.bindingProviderInstance = provider
provider.bindingHandlers.set({ counter: () => ++counter })
applyBindings({abc: '123'}, parent)
const inode = parent.children[0].children[0]
delete inode[ORIGINAL_JSX_SYM]
const p = Symbol('An arbitrary property')
inode[p] = 12341
assert.equal(parent.innerHTML, '<div><i></i><!--O--></div>')
io(inode)
assert.equal(inode[p], 12341)
assert.equal(parent.innerHTML, '<div><i></i><!--O--></div>')
jo.dispose()
})
it('inserts nodes from original JSX correctly', () => {
const parent = document.createElement('div')
const itag = document.createElement('i')
itag[ORIGINAL_JSX_SYM] = { elementName: 'b', children: [], attributes: {} }
const jsx = { elementName: 'div', children: [itag], attributes: {} }
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `<div><b></b></div>`)
jo.dispose()
})
it('inserts nodes from original JSX multiple times', () => {
const parent = document.createElement('div')
const itag = document.createElement('i')
itag[ORIGINAL_JSX_SYM] = { elementName: 'b', children: [], attributes: {} }
const jsx = { elementName: 'div', children: [itag, itag], attributes: {} }
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `<div><b></b><b></b></div>`)
jo.dispose()
})
it('inserts null and undefined values as comments', () => {
const parent = document.createElement('div')
const jsx = {
elementName: 'div',
children: ['a', null, 'b', undefined, 'c'],
attributes: {}
}
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `<div>a<!--null-->b<!--undefined-->c</div>`)
jo.dispose()
})
it('inserts sparse arrays', () => {
// The JSX preprocessor can generate sparse arrays with e.g.
// <div>{/* thing */}</div>
const parent = document.createElement('div')
const jsx = []
jsx[0] = 'a'
jsx[2] = 'b'
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `ab`)
jo.dispose()
})
it('inserts arrays of arrays', () => {
const parent = document.createElement('div')
const jsx = [['a'], [['b']], [[['c']]]]
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `abc`)
jo.dispose()
})
/**
* Simple generator of the given parameter.
*/
function * gX (...args) { yield * args }
/**
* Simple generator of [G0, G1, G2]
*/
function * g3 () { yield * gX('G0', 'G1', 'G2') }
it('a generator', () => {
const parent = document.createElement('div')
const jsx = g3()
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `G0G1G2`)
jo.dispose()
})
it('inserts array of generators', () => {
const parent = document.createElement('div')
const jsx = [g3(), g3()]
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `G0G1G2G0G1G2`)
jo.dispose()
})
it('inserts generators of arrays', () => {
function * gA () { yield * [['a'], ['b'], ['c']]}
const parent = document.createElement('div')
const jsx = gA()
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `abc`)
jo.dispose()
})
it('inserts nested arrays/generators', () => {
const parent = document.createElement('div')
const jsx = [gX('a', 'b', ['c', gX('d', 'e')])]
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `abcde`)
jo.dispose()
})
describe('primitives', () => {
const PRIMITIVES = [1, '2', true, false, 0, 11.1]
for (const p of PRIMITIVES) {
it(`inserts ${p} as a primitive`, () => {
const parent = document.createElement('div')
const jsx = p
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, String(p))
jo.dispose()
})
it(`inserts ${p} as an observable`, () => {
const parent = document.createElement('div')
const jsx = observable(p)
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `${p}<!--O-->`)
jo.dispose()
})
it(`inserts ${p} as a primitive child of a node`, () => {
const parent = document.createElement('div')
const jsx = {elementName: 'j', children: [p], attributes: {}}
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `<j>${p}</j>`)
jo.dispose()
})
it(`inserts ${p} as an observable child of a node`, () => {
const parent = document.createElement('div')
const v = observable(p)
const jsx = {elementName: 'j', children: [v], attributes: {}}
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `<j>${p}<!--O--></j>`)
v.modify(x => `[${x}]`)
assert.equal(parent.innerHTML, `<j>[${p}]<!--O--></j>`)
jo.dispose()
})
it(`inserts ${p} as a primitive child of an array`, () => {
const parent = document.createElement('div')
const jsx = [p]
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `${p}`)
jo.dispose()
})
it(`inserts ${p} as an observable child of an array`, () => {
const parent = document.createElement('div')
const v = observable(p)
const jsx = [v]
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `${p}<!--O-->`)
v.modify(x => `[${x}]`)
assert.equal(parent.innerHTML, `[${p}]<!--O-->`)
jo.dispose()
})
it(`inserts ${p} as an attribute`, () => {
const parent = document.createElement('div')
const jsx = {elementName: 'j', children: [], attributes: {p}}
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `<j p="${p}"></j>`)
jo.dispose()
})
it(`inserts ${p} as an observable attribute`, () => {
const parent = document.createElement('div')
const v = observable(p)
const jsx = {elementName: 'j', children: [], attributes: {v}}
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, `<j v="${p}"></j>`)
v.modify(x => `[${x}]`)
assert.equal(parent.innerHTML, `<j v="[${p}]"></j>`)
jo.dispose()
})
}
})
it('converts and updates an observable number', () => {
const parent = document.createElement('div')
const jsx = observable(4)
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, '4<!--O-->')
jsx.modify(v => 17 + v)
assert.equal(parent.innerHTML, '21<!--O-->')
jo.dispose()
})
it('converts and updates an observable child number', () => {
const parent = document.createElement('div')
const jsx = {elementName: 'x', children: [observable(4)], attributes: {}}
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, '<x>4<!--O--></x>')
jsx.children[0].modify(v => 17 + v)
assert.equal(parent.innerHTML, '<x>21<!--O--></x>')
jo.dispose()
})
it('calls functions to unwrap', () => {
const parent = document.createElement('div')
const jsx = [() => 'bca']
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, 'bca')
jo.dispose()
})
it('inserts null/undefined/symbol as comments', () => {
const parent = document.createElement('div')
const jsx = [null, undefined, Symbol('z')]
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, '<!--null--><!--undefined--><!--Symbol(z)-->')
jo.dispose()
})
it('inserts BigInt as a string', () => {
const supported = 'BigInt' in window
if (!supported) { return }
const parent = document.createElement('div')
const jsx = [BigInt(123)]
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, '123')
jo.dispose()
})
it('inserts arbitrary objects as string comments', () => {
// Arbitrary objects ought to never show up here, but in the event
// that they do, we add them as comments to make KO more debuggable.
const parent = document.createElement('div')
const jsx = [{x: '123'}]
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, '<!--{"x":"123"}-->')
jo.dispose()
})
it('unwraps multiple text computeds at root', () => {
const parent = document.createElement('div')
const o = observable(false)
const c1 = computed(() => [o, '123'])
const c0 = computed(() => o() ? c1 : 'abc')
const jo = new JsxTestObserver(c0, parent)
assert.equal(parent.innerHTML, 'abc<!--O-->')
o('zzz')
assert.equal(parent.innerHTML, 'zzz123<!--O-->')
jo.dispose()
})
it('unwraps null computeds at root', () => {
const parent = document.createElement('div')
const o = observable(null)
const c0 = computed(() => o())
const jo = new JsxTestObserver(c0, parent)
assert.equal(parent.innerHTML, '<!--null--><!--O-->')
o('zaz')
assert.equal(parent.innerHTML, 'zaz<!--O-->')
jo.dispose()
})
it('unwraps multiple text computeds as children', () => {
const parent = document.createElement('div')
const o = observable(false)
const c1 = computed(() => [o, '123'])
const c0 = computed(() => o() ? c1 : 'abc')
const jsx = { elementName: 'r', children: [c0], attributes: {} }
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, '<r>abc<!--O--></r>')
o('zzz')
assert.equal(parent.innerHTML, '<r>zzz123<!--O--></r>')
jo.dispose()
})
it('unwraps multiple element computeds as children', () => {
const parent = document.createElement('div')
const o = observable(false)
const v = { elementName: 'v', children: ['VV'], attributes: {} }
const w = { elementName: 'w', children: ['WW'], attributes: {} }
const c1 = computed(() => v)
const c0 = computed(() => o() ? c1 : w)
const jsx = { elementName: 'r', children: [c0], attributes: {} }
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, '<r><w>WW</w><!--O--></r>')
o('zzz')
assert.equal(parent.innerHTML, '<r><v>VV</v><!--O--></r>')
jo.dispose()
})
/**
* Promises
*/
describe('promises', () => {
it('inserts a promise after it resolves', async () => {
const parent = document.createElement('div')
const obs = observable()
const p = obs.when(true)
const jsx = [p]
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, '<!--O-->')
obs(true)
await p
assert.equal(parent.innerHTML, 'true<!--O-->')
jo.dispose()
})
it('resolves a promise to a working observable', async () => {
const parent = document.createElement('div')
const obs = observable()
const jsx = ['a', Promise.resolve(obs), 'b']
const jo = new JsxTestObserver(jsx, parent)
assert.equal(parent.innerHTML, 'a<!--O-->b')
await jsx[0]
assert.equal(parent.innerHTML, 'a<!--O-->b')
obs('123')
assert.equal(parent.innerHTML, 'a123<!--O-->b')
obs('345')
assert.equal(parent.innerHTML, 'a345<!--O-->b')
obs(null)
assert.equal(parent.innerHTML, 'a<!--O-->b')
obs(undefined)
assert.equal(parent.innerHTML, 'a<!--O-->b')
obs({elementName: 'x', children: [], attributes: {y: 1}})
assert.equal(parent.innerHTML, 'a<x y="1"></x><!--O-->b')
jo.dispose()
})
it('binds nodes created by promises', async () => {
let counter = 0
const parent = document.createElement('div')
const provider = new NativeProvider()
options.bindingProviderInstance = provider
provider.bindingHandlers.set({ counter: () => ++counter })
const jsx = Promise.resolve({
elementName: 'r',
children: [],
attributes: {'ko-counter': true}
})
const jo = new JsxTestObserver(jsx, parent)
applyBindings({}, parent)
assert.equal(counter, 0)
await jsx
assert.equal(counter, 1)
jo.dispose()
})
it('removes promises from arrays before the promise resolves', async () => {
const parent = document.createElement('div')
const p = Promise.resolve('1')
const obs = observableArray(['a', p, 'b'])
const jsx = obs
const jo = new JsxTestObserver(jsx, parent)
obs(['c'])
assert.equal(parent.innerHTML, 'c<!--O-->')
await p
assert.equal(parent.innerHTML, 'c<!--O-->')
jo.dispose()
})
it('removes promises from arrays after the promise resolves', async () => {
const parent = document.createElement('div')
const p = Promise.resolve('1')
const obs = observableArray(['a', p, 'b'])
const jsx = obs
const jo = new JsxTestObserver(jsx, parent)
await p
obs(['c'])
assert.equal(parent.innerHTML, 'c<!--O-->')
jo.dispose()
})
it('adds a comment with the text of an error', async () => {
const parent = document.createElement('div')
const p0 = Promise.reject(new Error('Ex'))
const p1 = Promise.reject('Ey')
const jsx = [p0, p1]
const jo = new JsxTestObserver(jsx, parent)
try { await p0 } catch (err) {}
try { await p1 } catch (err) {}
assert.equal(parent.innerHTML, '<!--Error: Ex--><!--O--><!--Error: Ey--><!--O-->')
jo.dispose()
})
})
/**
* Attributes
*/
describe('attributes', () => {
it('interjects an attribute observable', function () {
const obs = observable('zzz')
const child = {
elementName: "span",
children: [],
attributes: { xorz: obs }
}
const node = jsxToNode({
elementName: "div",
children: ['x', child, 'y'],
attributes: { xorz: obs }
})
assert.equal(node.outerHTML, '<div xorz="zzz">x<span xorz="zzz"></span>y</div>')
obs('f2')
assert.equal(node.outerHTML, '<div xorz="f2">x<span xorz="f2"></span>y</div>')
})
it('interjects all attributes', function () {
const obs = observable({ xorz: 'abc' })
const child = {
elementName: "span",
children: [],
attributes: obs
}
const node = jsxToNode({
elementName: "div",
children: ['x', child, 'y'],
attributes: obs
})
assert.equal(node.outerHTML, '<div xorz="abc">x<span xorz="abc"></span>y</div>')
obs({ xandy: 'P' })
assert.equal(node.outerHTML, '<div xandy="P">x<span xandy="P"></span>y</div>')
})
it('toggles an empty observable attribute', () => {
const o = observable(undefined)
const node = jsxToNode({ elementName: 'i', children: [], attributes: {x: o}})
assert.equal(node.outerHTML, '<i></i>')
o('')
assert.equal(node.outerHTML, '<i x=""></i>')
o(undefined)
assert.equal(node.outerHTML, '<i></i>')
})
it('toggles an observable attribute existence', () => {
const o = observable(undefined)
const node = jsxToNode({ elementName: 'i', children: [], attributes: {x: o}})
assert.equal(node.outerHTML, '<i></i>')
o('123')
assert.equal(node.outerHTML, '<i x="123"></i>')
o(undefined)
assert.equal(node.outerHTML, '<i></i>')
})
it('resolves a thenable when complete', async () => {
const o = observable(false)
const x = o.when(true).then(() => 'abc')
const node = jsxToNode({ elementName: 'i', children: [], attributes: {x}})
assert.equal(node.outerHTML, '<i></i>')
o(true)
await x
assert.equal(node.outerHTML, '<i x="abc"></i>')
})
describe('namespaces', () => {
// Note: https://stackoverflow.com/questions/52571125
const NS = {
svg: 'http://www.w3.org/2000/svg',
html: 'http://www.w3.org/1999/xhtml',
xml: 'http://www.w3.org/XML/1998/namespace',
xlink: 'http://www.w3.org/1999/xlink',
xmlns: 'http://www.w3.org/2000/xmlns/'
}
it('xmlns', () => {
// Setting `xmlns` with node.setAttributeNS throws:
// Failed to execute 'setAttributeNS' on 'Element': '' is an
// invalid namespace for attributes.
// So when setting `xmlns` we use node.setAttribute. This *could*
// apply to other node types.
// See: https://stackoverflow.com/questions/52571125
const node = jsxToNode({
elementName: 'svg',
children: ['x'],
attributes: { xmlns: NS.svg }
})
assert.equal(node.outerHTML, `<svg xmlns="${NS.svg}">x</svg>`)
})
it('xlink:href', () => {
const node = jsxToNode({
elementName: 'svg',
children: ['x'],
attributes: { xmlns: NS.svg, 'xmlns:xlink': NS.xlink }
})
assert.equal(node.outerHTML, `<svg xmlns="${NS.svg}" xmlns:xlink="${NS.xlink}">x</svg>`)
})
it('xml:space', () => {
const node = jsxToNode({
elementName: 'div',
children: ['x'],
attributes: { 'xml:space': 'preserve' }
})
assert.equal(node.outerHTML, `<div xml:space="preserve">x</div>`)
})
})
})
describe('bindings', () => {
it('applies bindings attached to the nodes', () => {
let counter = 0
const parent = document.createElement('div')
const provider = new NativeProvider()
options.bindingProviderInstance = provider
provider.bindingHandlers.set({ counter: () => ++counter })
const jsx = {
elementName: 'r',
children: [],
attributes: {'ko-counter': true}
}
const jo = new JsxTestObserver(jsx, parent)
applyBindings({}, parent)
assert.equal(counter, 1)
jo.dispose()
})
it('applies bindings attached to array/nested observable nodes', () => {
let counter = 0
const parent = document.createElement('div')
const provider = new NativeProvider()
options.bindingProviderInstance = provider
provider.bindingHandlers.set({ counter: () => ++counter })
const q = { elementName: 'q', children: [], attributes: { 'ko-counter': true }}
const oq = observable()
const jsx = {
elementName: 'r',
children: [computed(() => oq())],
attributes: {}
}
const jo = new JsxTestObserver(jsx, parent)
applyBindings({}, parent)
oq([q, q])
assert.equal(counter, 2)
oq([q, q, q])
assert.equal(counter, 3)
oq(observable([{ elementName: 'v', children: [q], attributes: {} }]))
assert.equal(counter, 4)
oq(observable([{ elementName: 'v', children: [observable([q, q])], attributes: {} }]))
assert.equal(counter, 6)
jo.dispose()
})
it('noInitialBinding applies no bindings to array/nested observable nodes', () => {
let counter = 0
const parent = document.createElement('div')
const provider = new NativeProvider()
options.bindingProviderInstance = provider
provider.bindingHandlers.set({ counter: () => {console.trace(); ++counter }})
const q = { elementName: 'q', children: [], attributes: { 'ko-counter': true }}
const oq = observable([q])
const jsx = {
elementName: 'r',
children: [computed(() => oq())],
attributes: {}
}
assert.equal(counter, 0, 'a')
const jo = new JsxTestObserver(jsx, parent, undefined, undefined, true)
assert.equal(counter, 0, 'after jsx binding')
applyBindings({}, parent)
assert.equal(counter, 1, 'after jsx binding')
oq([q,q,q])
assert.equal(counter, 3, 'after jsx binding')
jo.dispose()
})
})
describe('components', () => {
it('binds components that return JSX', () => {
class TestComponent extends ComponentABC {
get template () {
return { elementName: 'a', children: ['A'], attributes: {} }
}
}
TestComponent.register()
options.bindingProviderInstance = new ComponentProvider()
options.bindingProviderInstance.bindingHandlers.component = componentBindings.component
const parent = document.createElement('div')
const jsx = {
elementName: 'test-component', children: ['B'], attributes: {} }
const jo = new JsxTestObserver(jsx, parent)
applyBindings({}, parent)
assert.equal(parent.innerHTML,
'<test-component><a>A</a></test-component>')
jo.dispose()
})
it('binds components array', () => {
const arr = observableArray([])
class TestComponentInner extends ComponentABC {
get template () {
return { elementName: 'i', children: ['I'], attributes: {} }
}
}
class TestComponentOuter extends ComponentABC {
get template () {
return { elementName: 'a', children: [arr], attributes: {} }
}
}
TestComponentOuter.register('t-o')
TestComponentInner.register('t-i')
options.bindingProviderInstance = new ComponentProvider()
options.bindingProviderInstance.bindingHandlers.component = componentBindings.component
const parent = document.createElement('div')
const jsx = {
elementName: 't-o', children: ['B'], attributes: {} }
const jo = new JsxTestObserver(jsx, parent)
applyBindings({}, parent)
assert.equal(parent.innerHTML, '<t-o><a><!--O--></a></t-o>')
arr([{ elementName: 't-i', attributes: {}, children: ['Z'] }])
assert.equal(parent.innerHTML, '<t-o><a><t-i><i>I</i></t-i><!--O--></a></t-o>')
jo.dispose()
})
})
describe('$context', () => {
function testContext (jsxConvertible, nodeToTest = n => n.childNodes[0]) {
const parent = document.createElement('div')
const view = {}
options.bindingProviderInstance = new VirtualProvider()
const jo = new JsxTestObserver(jsxConvertible, parent)
applyBindings(view, parent)
assert.strictEqual(contextFor(nodeToTest(parent)).$data, view)
jo.dispose()
}
it('applies to a jsx object', () => {
testContext({ elementName: 'x', children: [], attributes: {} })
})
it('applies to a jsx object in an array', () => {
testContext([{ elementName: 'x', children: [], attributes: {} }])
})
it('applies to a jsx object in an observable', () => {
testContext(observable({ elementName: 'x', children: [], attributes: {} }))
})
it('applies to a jsx array in an observable', () => {
testContext(observable([{ elementName: 'x', children: [], attributes: {} }]))
})
it('applies to an array with a an observable', () => {
const inner = { elementName: 'i1', children: [], attributes: {} }
testContext([observable(inner)])
})
it('applies to jsx with children', () => {
const jsx = {
elementName: 'x',
children: [ { elementName: 'y', children: [], attributes: {} } ],
attributes: {}
}
testContext(jsx, n => n.childNodes[0].childNodes[0])
})
it('applies to observable jsx children', () => {
const jsx = {
elementName: 'x',
children: observable(
[ { elementName: 'y', children: [], attributes: {} } ]
),
attributes: {}
}
testContext(jsx, n => n.childNodes[0].childNodes[0])
})
it('applies to jsx children that are observable', () => {
const jsx = observable({
elementName: 'x',
children: [
observable({ elementName: 'y', children: [], attributes: {} })
],
attributes: {}
})
testContext(jsx, n => n.childNodes[0].childNodes[0])
})
it('applies to observables when they are updated', () => {
const obs = observable()
testContext(obs, n => {
obs({ elementName: 'x', children: [], attributes: {} })
return n.childNodes[0]
})
})
})
describe('array changes', () => {
it('reverses an array correctly', () => {
const obs = observable(['a', 'b', 'c', 'd'])
const parent = document.createElement('div')
const jo = new JsxTestObserver(obs, parent)
assert.equal(parent.innerHTML, 'abcd<!--O-->')
obs(obs().reverse())
assert.equal(parent.innerHTML, 'dcba<!--O-->')
jo.dispose()
})
it('adds at start/end correctly', () => {
const obs = observable(['a', 'b', 'c', 'd'])
const parent = document.createElement('div')
const jo = new JsxTestObserver(obs, parent)
obs(['X', 'a', 'b', 'c', 'd'])
assert.equal(parent.innerHTML, 'Xabcd<!--O-->')
obs(['X', 'a', 'b', 'c', 'd', 'Y'])
assert.equal(parent.innerHTML, 'XabcdY<!--O-->')
jo.dispose()
})
it('inserts into the middle correctly', () => {
const obs = observable(['a', 'b', 'c', 'd'])
const parent = document.createElement('div')
const jo = new JsxTestObserver(obs, parent)
obs(['a', 'b', 'X', 'c', 'd'])
assert.equal(parent.innerHTML, 'abXcd<!--O-->')
jo.dispose()
})
it('removes from the start/middle/end correctly', () => {
const obs = observable(['a', 'b', 'c', 'd'])
const parent = document.createElement('div')
const jo = new JsxTestObserver(obs, parent)
obs(['b', 'c', 'd'])
assert.equal(parent.innerHTML, 'bcd<!--O-->')
obs(['b','d'])
assert.equal(parent.innerHTML, 'bd<!--O-->')
obs(['b'])
assert.equal(parent.innerHTML, 'b<!--O-->')
jo.dispose()
})
it('inserts / flattens an observable array', () => {
const obs = observableArray(['x'])
const parent = document.createElement('div')
const jo = new JsxTestObserver([obs], parent)
assert.equal(parent.innerHTML, 'x<!--O-->')
jo.dispose()
})
it('updates an observable array', () => {
const obs = observableArray(['x'])
const parent = document.createElement('div')
const jo = new JsxTestObserver([obs], parent)
obs(['y', 'z'])
assert.equal(parent.innerHTML, 'yz<!--O-->')
obs(['z', '2'])
assert.equal(parent.innerHTML, 'z2<!--O-->')
obs('r')
assert.equal(parent.innerHTML, 'r<!--O-->')
jo.dispose()
})
it('updates arbitrarily nexted observables', () => {
const obs = observableArray([
observableArray(['x']),
observableArray([
observableArray(['y'])
])
])
const parent = document.createElement('div')
const jo = new JsxTestObserver([obs], parent)
assert.equal(parent.innerHTML, 'xy<!--O-->')
jo.dispose()
})
it('removes and adds computed array', () => {
const x = observable(false)
const arr = computed(() => x() ? ['X', 'Y'] : ['Y', 'X'])
const parent = document.createElement('div')
const jo = new JsxTestObserver(arr, parent)
assert.equal(parent.innerHTML, 'YX<!--O-->')
x(true)
assert.equal(parent.innerHTML, 'XY<!--O-->')
jo.dispose()
})
it('removes and adds observables', () => {
const o0 = observable('A')
const o1 = observable('B')
const x = observable(false)
const arr = computed(() => x() ? [o0, o1] : [o0, o1, o0])
const parent = document.createElement('div')
const jo = new JsxTestObserver(arr, parent)
assert.equal(parent.innerHTML, 'ABA<!--O-->')
x(true)
assert.equal(parent.innerHTML, 'AB<!--O-->')
jo.dispose()
})
})
}) | the_stack |
import GL from '@luma.gl/constants';
import Resource, {ResourceProps} from './resource';
import {AccessorObject} from '../types';
import Accessor from './accessor';
import {getGLTypeFromTypedArray, getTypedArrayFromGLType} from '../webgl-utils';
import {assertWebGL2Context, log} from '@luma.gl/gltools';
import {assert, checkProps} from '../utils';
const DEBUG_DATA_LENGTH = 10;
// Shared prop checks for constructor and setProps
const DEPRECATED_PROPS = {
offset: 'accessor.offset',
stride: 'accessor.stride',
type: 'accessor.type',
size: 'accessor.size',
divisor: 'accessor.divisor',
normalized: 'accessor.normalized',
integer: 'accessor.integer',
instanced: 'accessor.divisor',
isInstanced: 'accessor.divisor'
};
// Prop checks for constructor
const PROP_CHECKS_INITIALIZE = {
removedProps: {},
replacedProps: {
bytes: 'byteLength'
},
// new Buffer() with individual accessor props is still used in apps, emit warnings
deprecatedProps: DEPRECATED_PROPS
};
// Prop checks for setProps
const PROP_CHECKS_SET_PROPS = {
// Buffer.setProps() with individual accessor props is rare => emit errors
removedProps: DEPRECATED_PROPS
};
export type BufferProps = ResourceProps & {
data?: any; // ArrayBufferView;
byteLength?: number;
target?: number;
usage?: number;
accessor?: AccessorObject;
/** @deprecated */
index?: number;
/** @deprecated */
offset?: number;
/** @deprecated */
size?: number;
/** @deprecated */
type?: number
}
export default class Buffer extends Resource {
// readonly handle: WebGLBuffer;
byteLength: number;
bytesUsed: number;
usage: number;
accessor: Accessor;
target: number;
debugData;
constructor(gl: WebGLRenderingContext, props?: BufferProps);
constructor(gl: WebGLRenderingContext, data: ArrayBufferView | number[]);
constructor(gl: WebGLRenderingContext, byteLength: number);
constructor(gl: WebGLRenderingContext, props = {}) {
super(gl, props);
// In WebGL1, need to make sure we use GL.ELEMENT_ARRAY_BUFFER when initializing element buffers
// otherwise buffer type will lock to generic (non-element) buffer
// In WebGL2, we can use GL.COPY_READ_BUFFER which avoids locking the type here
// @ts-expect-error
this.target = props.target || (this.gl.webgl2 ? GL.COPY_READ_BUFFER : GL.ARRAY_BUFFER);
this.initialize(props);
Object.seal(this);
}
// returns number of elements in the buffer (assuming that the full buffer is used)
getElementCount(accessor = this.accessor): number {
return Math.round(this.byteLength / Accessor.getBytesPerElement(accessor));
}
// returns number of vertices in the buffer (assuming that the full buffer is used)
getVertexCount(accessor = this.accessor): number {
return Math.round(this.byteLength / Accessor.getBytesPerVertex(accessor));
}
// Creates and initializes the buffer object's data store.
// Signature: `new Buffer(gl, {data: new Float32Array(...)})`
// Signature: `new Buffer(gl, new Float32Array(...))`
// Signature: `new Buffer(gl, 100)`
initialize(props: BufferProps = {}): this {
// Signature `new Buffer(gl, new Float32Array(...)`
if (ArrayBuffer.isView(props)) {
props = {data: props};
}
// Signature: `new Buffer(gl, 100)`
if (Number.isFinite(props)) {
// @ts-expect-error
props = {byteLength: props};
}
props = checkProps('Buffer', props, PROP_CHECKS_INITIALIZE);
// Initialize member fields
this.usage = props.usage || GL.STATIC_DRAW;
this.debugData = null;
// Deprecated: Merge main props and accessor
this.setAccessor(Object.assign({}, props, props.accessor));
// Set data: (re)initializes the buffer
if (props.data) {
this._setData(props.data, props.offset, props.byteLength);
} else {
this._setByteLength(props.byteLength || 0);
}
return this;
}
setProps(props: BufferProps): this {
props = checkProps('Buffer', props, PROP_CHECKS_SET_PROPS);
if ('accessor' in props) {
this.setAccessor(props.accessor);
}
return this;
}
// Optionally stores an accessor with the buffer, makes it easier to use it as an attribute later
// {type, size = 1, offset = 0, stride = 0, normalized = false, integer = false, divisor = 0}
setAccessor(accessor): this {
// NOTE: From luma.gl v7.0, Accessors have an optional `buffer `field
// (mainly to support "interleaving")
// To avoid confusion, ensure `buffer.accessor` does not have a `buffer.accessor.buffer` field:
accessor = Object.assign({}, accessor);
delete accessor.buffer;
// This new statement ensures that an "accessor object" is re-packaged as an Accessor instance
this.accessor = new Accessor(accessor);
return this;
}
// Allocate a bigger GPU buffer (if the current buffer is not big enough).
// If a reallocation is triggered it clears the buffer
// Returns:
// `true`: buffer was reallocated, data was cleared
// `false`: buffer was big enough, data is intact
reallocate(byteLength) {
if (byteLength > this.byteLength) {
this._setByteLength(byteLength);
return true;
}
this.bytesUsed = byteLength;
return false;
}
// Update with new data. Reinitializes the buffer
setData(props) {
return this.initialize(props);
}
// Updates a subset of a buffer object's data store.
// Data (Typed Array or ArrayBuffer), length is inferred unless provided
// Offset into buffer
// WebGL2 only: Offset into srcData
// WebGL2 only: Number of bytes to be copied
subData(props) {
// Signature: buffer.subData(new Float32Array([...]))
if (ArrayBuffer.isView(props)) {
props = {data: props};
}
const {data, offset = 0, srcOffset = 0} = props;
const byteLength = props.byteLength || props.length;
assert(data);
// Create the buffer - binding it here for the first time locks the type
// In WebGL2, use GL.COPY_WRITE_BUFFER to avoid locking the type
// @ts-expect-error
const target = this.gl.webgl2 ? GL.COPY_WRITE_BUFFER : this.target;
this.gl.bindBuffer(target, this.handle);
// WebGL2: subData supports additional srcOffset and length parameters
if (srcOffset !== 0 || byteLength !== undefined) {
assertWebGL2Context(this.gl);
// @ts-expect-error
this.gl.bufferSubData(this.target, offset, data, srcOffset, byteLength);
} else {
this.gl.bufferSubData(target, offset, data);
}
this.gl.bindBuffer(target, null);
// TODO - update local `data` if offsets are right
this.debugData = null;
this._inferType(data);
return this;
}
/**
* Copies part of the data of another buffer into this buffer
* @note WEBGL2 ONLY
*/
copyData(options: {
sourceBuffer: any;
readOffset?: number;
writeOffset?: number;
size: any;
}): this {
const {sourceBuffer, readOffset = 0, writeOffset = 0, size} = options;
const {gl, gl2} = this;
assertWebGL2Context(gl);
// Use GL.COPY_READ_BUFFER+GL.COPY_WRITE_BUFFER avoid disturbing other targets and locking type
gl.bindBuffer(GL.COPY_READ_BUFFER, sourceBuffer.handle);
gl.bindBuffer(GL.COPY_WRITE_BUFFER, this.handle);
gl2.copyBufferSubData(GL.COPY_READ_BUFFER, GL.COPY_WRITE_BUFFER, readOffset, writeOffset, size);
gl.bindBuffer(GL.COPY_READ_BUFFER, null);
gl.bindBuffer(GL.COPY_WRITE_BUFFER, null);
// TODO - update local `data` if offsets are 0
this.debugData = null;
return this;
}
/**
* Reads data from buffer into an ArrayBufferView or SharedArrayBuffer.
* @note WEBGL2 ONLY
*/
getData(options?: {
dstData?: any;
srcByteOffset?: number;
dstOffset?: number;
length?: number;
}): any {
let {dstData = null, length = 0} = options || {};
const {srcByteOffset = 0, dstOffset = 0} = options || {};
assertWebGL2Context(this.gl);
const ArrayType = getTypedArrayFromGLType(this.accessor.type || GL.FLOAT, {clamped: false});
const sourceAvailableElementCount = this._getAvailableElementCount(srcByteOffset);
const dstElementOffset = dstOffset;
let dstAvailableElementCount;
let dstElementCount;
if (dstData) {
dstElementCount = dstData.length;
dstAvailableElementCount = dstElementCount - dstElementOffset;
} else {
// Allocate ArrayBufferView with enough size to copy all eligible data.
dstAvailableElementCount = Math.min(
sourceAvailableElementCount,
length || sourceAvailableElementCount
);
dstElementCount = dstElementOffset + dstAvailableElementCount;
}
const copyElementCount = Math.min(sourceAvailableElementCount, dstAvailableElementCount);
length = length || copyElementCount;
assert(length <= copyElementCount);
dstData = dstData || new ArrayType(dstElementCount);
// Use GL.COPY_READ_BUFFER to avoid disturbing other targets and locking type
this.gl.bindBuffer(GL.COPY_READ_BUFFER, this.handle);
this.gl2.getBufferSubData(GL.COPY_READ_BUFFER, srcByteOffset, dstData, dstOffset, length);
this.gl.bindBuffer(GL.COPY_READ_BUFFER, null);
// TODO - update local `data` if offsets are 0
return dstData;
}
/**
* Binds a buffer to a given binding point (target).
* GL.TRANSFORM_FEEDBACK_BUFFER and GL.UNIFORM_BUFFER take an index, and optionally a range.
* - GL.TRANSFORM_FEEDBACK_BUFFER and GL.UNIFORM_BUFFER need an index to affect state
* - GL.UNIFORM_BUFFER: `offset` must be aligned to GL.UNIFORM_BUFFER_OFFSET_ALIGNMENT.
* - GL.UNIFORM_BUFFER: `size` must be a minimum of GL.UNIFORM_BLOCK_SIZE_DATA.
*/
bind(options?: {target?: number; index?: any; offset?: number; size: any}): this {
const {
target = this.target, // target for the bind operation
// @ts-expect-error
index = this.accessor && this.accessor.index, // index = index of target (indexed bind point)
offset = 0,
size
} = options || {};
// NOTE: While GL.TRANSFORM_FEEDBACK_BUFFER and GL.UNIFORM_BUFFER could
// be used as direct binding points, they will not affect transform feedback or
// uniform buffer state. Instead indexed bindings need to be made.
if (target === GL.UNIFORM_BUFFER || target === GL.TRANSFORM_FEEDBACK_BUFFER) {
if (size !== undefined) {
this.gl2.bindBufferRange(target, index, this.handle, offset, size);
} else {
assert(offset === 0); // Make sure offset wasn't supplied
this.gl2.bindBufferBase(target, index, this.handle);
}
} else {
this.gl.bindBuffer(target, this.handle);
}
return this;
}
unbind(options?: {target?: any; index?: any}): this {
// @ts-expect-error
const {target = this.target, index = this.accessor && this.accessor.index} = options || {};
const isIndexedBuffer = target === GL.UNIFORM_BUFFER || target === GL.TRANSFORM_FEEDBACK_BUFFER;
if (isIndexedBuffer) {
this.gl2.bindBufferBase(target, index, null);
} else {
this.gl.bindBuffer(target, null);
}
return this;
}
// PROTECTED METHODS (INTENDED FOR USE BY OTHER FRAMEWORK CODE ONLY)
// Returns a short initial data array
getDebugData(): {
data: any;
changed: boolean;
} {
if (!this.debugData) {
this.debugData = this.getData({length: Math.min(DEBUG_DATA_LENGTH, this.byteLength)});
return {data: this.debugData, changed: true};
}
return {data: this.debugData, changed: false};
}
invalidateDebugData() {
this.debugData = null;
}
// PRIVATE METHODS
// Allocate a new buffer and initialize to contents of typed array
_setData(data, offset: number = 0, byteLength: number = data.byteLength + offset): this {
assert(ArrayBuffer.isView(data));
this._trackDeallocatedMemory();
const target = this._getTarget();
this.gl.bindBuffer(target, this.handle);
this.gl.bufferData(target, byteLength, this.usage);
this.gl.bufferSubData(target, offset, data);
this.gl.bindBuffer(target, null);
this.debugData = data.slice(0, DEBUG_DATA_LENGTH);
this.bytesUsed = byteLength;
this._trackAllocatedMemory(byteLength);
// infer GL type from supplied typed array
const type = getGLTypeFromTypedArray(data);
assert(type);
this.setAccessor(new Accessor(this.accessor, {type}));
return this;
}
// Allocate a GPU buffer of specified size.
_setByteLength(byteLength: number, usage = this.usage): this {
assert(byteLength >= 0);
this._trackDeallocatedMemory();
// Workaround needed for Safari (#291):
// gl.bufferData with size equal to 0 crashes. Instead create zero sized array.
let data = byteLength;
if (byteLength === 0) {
// @ts-expect-error
data = new Float32Array(0);
}
const target = this._getTarget();
this.gl.bindBuffer(target, this.handle);
this.gl.bufferData(target, data, usage);
this.gl.bindBuffer(target, null);
this.usage = usage;
this.debugData = null;
this.bytesUsed = byteLength;
this._trackAllocatedMemory(byteLength);
return this;
}
// Binding a buffer for the first time locks the type
// In WebGL2, use GL.COPY_WRITE_BUFFER to avoid locking the type
_getTarget() {
// @ts-expect-error
return this.gl.webgl2 ? GL.COPY_WRITE_BUFFER : this.target;
}
_getAvailableElementCount(srcByteOffset) {
const ArrayType = getTypedArrayFromGLType(this.accessor.type || GL.FLOAT, {clamped: false});
const sourceElementOffset = srcByteOffset / ArrayType.BYTES_PER_ELEMENT;
return this.getElementCount() - sourceElementOffset;
}
// Automatically infers type from typed array passed to setData
// Note: No longer that useful, since type is now autodeduced from the compiled shaders
_inferType(data) {
if (!this.accessor.type) {
this.setAccessor(new Accessor(this.accessor, {type: getGLTypeFromTypedArray(data)}));
}
}
// RESOURCE METHODS
_createHandle() {
return this.gl.createBuffer();
}
_deleteHandle() {
this.gl.deleteBuffer(this.handle);
this._trackDeallocatedMemory();
}
_getParameter(pname) {
this.gl.bindBuffer(this.target, this.handle);
const value = this.gl.getBufferParameter(this.target, pname);
this.gl.bindBuffer(this.target, null);
return value;
}
// DEPRECATIONS - v7.0
/** @deprecated Use Buffer.accessor.type */
get type() {
return this.accessor.type;
}
get bytes() {
log.deprecated('Buffer.bytes', 'Buffer.byteLength')();
return this.byteLength;
}
// DEPRECATIONS - v6.0
// Deprecated in v6.x, but not warnings not properly implemented
setByteLength(byteLength) {
log.deprecated('setByteLength', 'reallocate')();
return this.reallocate(byteLength);
}
// Deprecated in v6.x, but not warnings not properly implemented
updateAccessor(opts) {
log.deprecated('updateAccessor(...)', 'setAccessor(new Accessor(buffer.accessor, ...)')();
this.accessor = new Accessor(this.accessor, opts);
return this;
}
} | the_stack |
import {assert} from 'chai';
import type {ElementHandle, Page} from 'puppeteer';
import {getBrowserAndPages, pressKey, typeText, waitFor, waitForAria, tabForward} from '../../shared/helper.js';
import {describe, it} from '../../shared/mocha-extensions.js';
import {navigateToNetworkTab} from '../helpers/network-helpers.js';
import type * as Protocol from '../../../front_end/generated/protocol.js';
interface MetaData extends Protocol.Emulation.UserAgentMetadata {
getHighEntropyValues: (metaDataKeys: string[]) => Promise<string[]>;
}
interface NavigatorWithUserAgentData extends Navigator {
userAgentData: MetaData;
}
describe('The Network Tab', async function() {
beforeEach(async () => {
await navigateToNetworkTab('empty.html');
});
async function openNetworkConditions(sectionClassName: string) {
const networkConditionsButton = await waitForAria('More network conditions…');
await networkConditionsButton.click();
return await waitFor(sectionClassName);
}
async function assertDisabled(checkbox: ElementHandle<HTMLInputElement>, expected: boolean) {
const disabled = await checkbox.evaluate(el => el.disabled);
assert.strictEqual(disabled, expected);
}
async function assertChecked(checkbox: ElementHandle<HTMLInputElement>, expected: boolean) {
const checked = await checkbox.evaluate(el => el.checked);
assert.strictEqual(checked, expected);
}
async function getUserAgentMetadataFromTarget(target: Page) {
const getUserAgentMetaData = async () => {
const nav = <NavigatorWithUserAgentData>navigator;
return {
brands: nav.userAgentData.brands,
mobile: nav.userAgentData.mobile,
...(await nav.userAgentData.getHighEntropyValues([
'uaFullVersion',
'architecture',
'model',
'platform',
'platformVersion',
])),
};
};
const getUserAgentMetaDataStr = `(${getUserAgentMetaData.toString()})()`;
return await target.evaluate(getUserAgentMetaDataStr);
}
it('can change accepted content encodings', async () => {
const section = await openNetworkConditions('.network-config-accepted-encoding');
const autoCheckbox = await waitForAria('Use browser default', section);
const deflateCheckbox = await waitForAria('deflate', section);
const gzipCheckbox = await waitForAria('gzip', section);
const brotliCheckbox = await waitForAria('br', section);
await brotliCheckbox.evaluate(el => el.scrollIntoView(true));
await assertChecked(autoCheckbox, true);
await assertChecked(deflateCheckbox, true);
await assertChecked(gzipCheckbox, true);
await assertChecked(brotliCheckbox, true);
await assertDisabled(autoCheckbox, false);
await assertDisabled(deflateCheckbox, true);
await assertDisabled(gzipCheckbox, true);
await assertDisabled(brotliCheckbox, true);
await autoCheckbox.click();
await assertChecked(autoCheckbox, false);
await assertChecked(deflateCheckbox, true);
await assertChecked(gzipCheckbox, true);
await assertChecked(brotliCheckbox, true);
await assertDisabled(autoCheckbox, false);
await assertDisabled(deflateCheckbox, false);
await assertDisabled(gzipCheckbox, false);
await assertDisabled(brotliCheckbox, false);
await brotliCheckbox.click();
await assertChecked(autoCheckbox, false);
await assertChecked(deflateCheckbox, true);
await assertChecked(gzipCheckbox, true);
await assertChecked(brotliCheckbox, false);
await assertDisabled(autoCheckbox, false);
await assertDisabled(deflateCheckbox, false);
await assertDisabled(gzipCheckbox, false);
await assertDisabled(brotliCheckbox, false);
await autoCheckbox.click();
await assertChecked(autoCheckbox, true);
await assertChecked(deflateCheckbox, true);
await assertChecked(gzipCheckbox, true);
await assertChecked(brotliCheckbox, false);
await assertDisabled(autoCheckbox, false);
await assertDisabled(deflateCheckbox, true);
await assertDisabled(gzipCheckbox, true);
await assertDisabled(brotliCheckbox, true);
});
it('can override userAgentMetadata', async () => {
const {target, browser} = getBrowserAndPages();
const fullVersion = (await browser.version()).split('/')[1];
const majorVersion = fullVersion.split('.', 1)[0];
const fixedVersionUAValue =
'Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30';
const dynamicVersionUAValue =
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36'.replace(
'%s', fullVersion);
const noMetadataVersionUAValue = 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko';
const fixedVersionUserAgentMetadataExpected = {
'brands': [
{'brand': 'Not A;Brand', 'version': '99'},
{'brand': 'Chromium', 'version': majorVersion},
{'brand': 'Google Chrome', 'version': majorVersion},
],
'uaFullVersion': fullVersion,
'platform': 'Android',
'platformVersion': '4.0.2',
'architecture': '',
'model': 'Galaxy Nexus',
'mobile': true,
};
const dynamicVersionUserAgentMetadataExpected = {
'brands': [
{'brand': 'Not A;Brand', 'version': '99'},
{'brand': 'Chromium', 'version': majorVersion},
{'brand': 'Google Chrome', 'version': majorVersion},
],
'uaFullVersion': fullVersion,
'platform': 'Windows',
'platformVersion': '10.0',
'architecture': 'x86',
'model': '',
'mobile': false,
};
const noMetadataVersionUserAgentMetadataExpected = {
'brands': [],
'mobile': false,
'uaFullVersion': '',
'platform': '',
'platformVersion': '',
'architecture': '',
'model': '',
};
const section = await openNetworkConditions('.network-config-ua');
const autoCheckbox = await waitForAria('Use browser default', section);
const uaDropdown = await waitForAria('User agent', section);
await assertChecked(autoCheckbox, true);
await autoCheckbox.click();
await assertChecked(autoCheckbox, false);
await uaDropdown.click();
await uaDropdown.select(fixedVersionUAValue);
await uaDropdown.click();
const fixedVersionUserAgentMetadata = await getUserAgentMetadataFromTarget(target);
assert.deepEqual(fixedVersionUserAgentMetadata, fixedVersionUserAgentMetadataExpected);
await uaDropdown.click();
await uaDropdown.select(dynamicVersionUAValue);
await uaDropdown.click();
const dynamicVersionUserAgentMetadata = await getUserAgentMetadataFromTarget(target);
assert.deepEqual(dynamicVersionUserAgentMetadata, dynamicVersionUserAgentMetadataExpected);
await uaDropdown.click();
await uaDropdown.select(noMetadataVersionUAValue);
await uaDropdown.click();
const noMetadataVersionUserAgentMetadata = await getUserAgentMetadataFromTarget(target);
assert.deepEqual(noMetadataVersionUserAgentMetadata, noMetadataVersionUserAgentMetadataExpected);
});
it('restores default userAgentMetadata', async () => {
const {target, browser} = getBrowserAndPages();
const fullVersion = (await browser.version()).split('/')[1];
const customUAValue =
`Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${
fullVersion} Mobile Safari/537.36`;
const section = await openNetworkConditions('.network-config-ua');
const autoCheckbox = await waitForAria('Use browser default', section);
const uaDropdown = await waitForAria('User agent', section);
await assertChecked(autoCheckbox, true);
const defaultUserAgentMetadata = await getUserAgentMetadataFromTarget(target);
await autoCheckbox.click();
await assertChecked(autoCheckbox, false);
await uaDropdown.click();
await uaDropdown.select(customUAValue);
await uaDropdown.click();
const customUserAgentMetadata = await getUserAgentMetadataFromTarget(target);
assert.notDeepEqual(defaultUserAgentMetadata, customUserAgentMetadata);
await autoCheckbox.click();
await assertChecked(autoCheckbox, true);
const restoredUserAgentMetadata = await getUserAgentMetadataFromTarget(target);
assert.deepEqual(defaultUserAgentMetadata, restoredUserAgentMetadata);
});
it('can apply customized userAgentMetadata', async () => {
const {target} = getBrowserAndPages();
const section = await openNetworkConditions('.network-config-ua');
const autoCheckbox = await waitForAria('Use browser default', section);
const uaDropdown = await waitForAria('User agent', section);
await assertChecked(autoCheckbox, true);
await autoCheckbox.click();
await assertChecked(autoCheckbox, false);
// Choose "Custom..." UA, Move focus to UA string and enter test value
await uaDropdown.select('custom');
const userAgent = await waitForAria('Enter a custom user agent');
await userAgent.click();
await userAgent.type('Test User Agent String');
await tabForward(); // focus help button
await pressKey('Space'); // open client hints section
await tabForward(); // focus help link
await tabForward(); // focus brand name
await typeText('Test Brand 1');
await tabForward(); // focus brand version
await typeText('99');
await tabForward(); // focus delete brand button
await tabForward(); // focus add brand button
await pressKey('Enter'); // add a second brand
await typeText('Test Brand 2');
await tabForward(); // focus brand version
await typeText('100');
await tabForward(); // focus delete brand button
await tabForward(); // focus add brand button
await pressKey('Enter'); // add a third brand
await typeText('Test Brand 3');
await tabForward(); // focus brand version
await typeText('101');
await tabForward(); // focus delete brand button
await tabForward(); // focus add brand button
await tabForward(); // focus browser full version
await typeText('99.99');
await tabForward(); // focus platform name
await typeText('Test Platform');
await tabForward(); // focus platform version
await typeText('10');
await tabForward(); // focus architecture
await typeText('Test Architecture');
await tabForward(); // focus device model
await typeText('Test Model');
await tabForward(); // focus mobile checkbox
await pressKey('Space');
await tabForward(); // focus update button
await pressKey('Enter');
const userAgentMetadata = await getUserAgentMetadataFromTarget(target);
assert.deepEqual(userAgentMetadata, {
'brands': [
{'brand': 'Test Brand 1', 'version': '99'},
{'brand': 'Test Brand 2', 'version': '100'},
{'brand': 'Test Brand 3', 'version': '101'},
],
'uaFullVersion': '99.99',
'platform': 'Test Platform',
'platformVersion': '10',
'architecture': 'Test Architecture',
'model': 'Test Model',
'mobile': true,
});
// Delete a brand
const brand = await waitForAria('Brand 1', section); // move focus back to first brand
await brand.click();
await tabForward(); // focus brand version
await tabForward(); // focus delete brand button
await pressKey('Enter');
// Edit a value
const platformVersion = await waitForAria('Platform version', section);
await platformVersion.click();
await typeText('11');
// Update
await tabForward(); // focus architecture
await tabForward(); // focus device model
await tabForward(); // focus mobile checkbox
await tabForward(); // focus update button
await pressKey('Enter');
const updatedUserAgentMetadata = await getUserAgentMetadataFromTarget(target);
assert.deepEqual(updatedUserAgentMetadata, {
'brands': [
{'brand': 'Test Brand 2', 'version': '100'},
{'brand': 'Test Brand 3', 'version': '101'},
],
'uaFullVersion': '99.99',
'platform': 'Test Platform',
'platformVersion': '1011',
'architecture': 'Test Architecture',
'model': 'Test Model',
'mobile': true,
});
});
}); | the_stack |
import React, {useRef, useState} from "react";
import {HomeNav, LibRoomPerformBookProp} from "./homeStack";
import {
convertUsageToSegments,
LibRoomBookTimeIndicator,
timeDiff,
} from "../../components/home/libRoomBookTimeIndicator";
import {
Alert,
Button,
Dimensions,
ScrollView,
Text,
TextInput,
TouchableOpacity,
useColorScheme,
View,
} from "react-native";
import {getStr} from "../../utils/i18n";
import Snackbar from "react-native-snackbar";
import {helper} from "../../redux/store";
import {NetworkRetry} from "../../components/easySnackbars";
import {LibFuzzySearchResult} from "thu-info-lib/dist/models/home/library";
import themes from "../../assets/themes/themes";
import FontAwesome from "react-native-vector-icons/FontAwesome";
import ModalDropdown from "react-native-modal-dropdown";
interface Segment {
start: string;
duration: number; // Setting it -1 means we do not care duration
}
const formatTime = (h: number, m: number) =>
`${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
export const LibRoomPerformBookScreen = ({
route: {
params: {res, date},
},
navigation,
}: {
route: LibRoomPerformBookProp;
navigation: HomeNav;
}) => {
const themeName = useColorScheme();
const {colors} = themes(themeName);
const segments = convertUsageToSegments(res);
const validBegs: Segment[] = segments
.filter(([_, duration, occupied]) => duration >= res.minMinute && !occupied)
.flatMap(([start, duration]) => {
const startH = Number(start.substring(0, 2));
const startM = Number(start.substring(3, 5));
return Array.from(
new Array(Math.floor((duration - res.minMinute) / 5) + 1),
(_, k) => {
let m = startM + k * 5;
let h = startH + Math.floor(m / 60);
m -= Math.floor(m / 60) * 60;
return {
start: formatTime(h, m),
duration: duration - k * 5,
} as Segment;
},
);
});
const genValidEnds = (item: Segment, beg: string): Segment[] => {
const result: Segment[] = [];
const {start, duration} = item;
let h = Number(beg.substring(0, 2));
let m = Number(beg.substring(3, 5)) + res.minMinute;
for (
let i = 0;
i < Math.floor((duration - res.minMinute - timeDiff(start, beg)) / 5) + 1;
i++
) {
h += Math.floor(m / 60);
m -= Math.floor(m / 60) * 60;
result.push({start: formatTime(h, m), duration: -1});
m += 5;
}
return result;
};
const getSubtitle = (title: string, color: string) => {
return (
<View
style={{
flex: 1,
flexDirection: "row",
alignItems: "center",
marginVertical: 8,
}}>
<FontAwesome name="chevron-right" color={color} size={18} />
<Text
style={{
fontWeight: "bold",
fontSize: 18,
marginHorizontal: 5,
color: colors.text,
}}>
{title}
</Text>
</View>
);
};
// TODO: Remember delete them when there are better solutions
const containerPadding: number = 16;
// TODO: This function only support 2 pickers in a row. Update later
const getDatePicker = (
defaultValue: string,
items: string[],
isLeft: boolean, // Whether the picker is on the left of the screen
text: string,
onSelect: (value: string) => void,
) => {
return (
<View style={{flex: 1, margin: 4}}>
<Text style={{marginBottom: 4, color: "gray"}}>{text}</Text>
<ModalDropdown
ref={isLeft ? undefined : rightPickerRef}
options={items}
defaultValue={defaultValue}
style={{
padding: 8,
borderWidth: 1,
borderRadius: 4,
borderColor: "gray",
}}
textStyle={{
fontSize: 14,
color: colors.text,
}}
dropdownStyle={{
paddingHorizontal: 20,
}}
dropdownTextStyle={{
color: "black",
fontSize: 14,
}}
showsVerticalScrollIndicator={false}
adjustFrame={(val) => {
return isLeft
? val
: {
...val,
left:
(val.right as number) +
Dimensions.get("window").width / 2 -
containerPadding,
right: undefined,
// eslint-disable-next-line no-mixed-spaces-and-tabs
};
}}
onSelect={(_, value) => onSelect(value)}
/>
</View>
);
};
const validEnds =
validBegs.length > 0 ? genValidEnds(validBegs[0], validBegs[0].start) : [];
const [begValue, setBegValue] = useState<string | null>(
validBegs.length > 0 ? validBegs[0].start ?? null : null,
);
const [endValue, setEndValue] = useState<string | null>(
validEnds.length > 0 ? validEnds[0].start ?? null : null,
);
const [endItems, setEndItems] = useState(validEnds);
const [members, setMembers] = useState<LibFuzzySearchResult[]>([
{id: helper.userId, label: "自己"},
]);
const [userKeyword, setUserKeyword] = useState<string>("");
const [userItems, setUserItems] = useState<LibFuzzySearchResult[]>([]);
const rightPickerRef = useRef<any>();
return (
<ScrollView style={{padding: containerPadding}}>
<Text
style={{
fontSize: 25,
marginVertical: 10,
marginLeft: 10,
lineHeight: 30,
alignSelf: "flex-start",
color: colors.text,
}}
numberOfLines={2}>
{res.roomName}
</Text>
{getSubtitle(getStr("occupation"), "red")}
<View
style={{
flexDirection: "row",
alignItems: "center",
marginLeft: 10,
marginTop: 4,
alignSelf: "flex-start",
}}>
<View
style={{
alignItems: "flex-start",
justifyContent: "center",
}}>
<Text style={{marginHorizontal: 8, color: "gray", fontSize: 16}}>
{getStr("libRoomBookDate")}
</Text>
</View>
<Text
style={{
marginHorizontal: 5,
color: colors.text,
fontSize: 14,
}}>
{date}
</Text>
</View>
<View style={{padding: 20}}>
<LibRoomBookTimeIndicator res={res} />
</View>
{getSubtitle(getStr("libRoomBookInfo"), "green")}
<View
style={{
flexDirection: "row",
marginVertical: 4,
alignItems: "center",
}}>
<Text style={{margin: 4, fontSize: 16, color: colors.text}}>
申请时间
</Text>
</View>
<View
style={{
flexDirection: "row",
justifyContent: "space-around",
alignItems: "center",
marginBottom: 8,
}}>
{getDatePicker(
begValue === null ? "选择时间" : (begValue as string),
validBegs.map((val) => val.start),
true,
"开始时间",
(value) => {
setBegValue(value);
const item = validBegs.find((e) => e.start === value);
if (item === undefined) {
setEndValue(null);
setEndItems([]);
} else {
const newValidEnds = genValidEnds(item, value as string);
setEndValue(newValidEnds[0].start ?? null);
setEndItems(newValidEnds);
}
// Adjust the right picker text to default value
rightPickerRef.current.select(-1);
},
)}
{getDatePicker(
endValue === null ? "选择时间" : (endValue as string),
endItems.map((val) => val.start) as string[],
false,
"结束时间",
(value) => setEndValue(value),
)}
</View>
{res.maxUser > 1 && (
<View>
<View style={{backgroundColor: "lightgray", height: 1}} />
<View
style={{
flexDirection: "row",
marginVertical: 8,
alignItems: "center",
}}>
<Text style={{margin: 4, fontSize: 16, color: colors.text}}>
{getStr("groupMembers")} ({res.minUser}~{res.maxUser})
</Text>
</View>
<Text style={{marginLeft: 4, marginBottom: 8}}>
{getStr("findUser")}
</Text>
<View
style={{
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
marginBottom: 12,
}}>
<TextInput
style={{
backgroundColor: colors.background,
color: colors.text,
textAlign: "left",
borderColor: "lightgrey",
borderWidth: 1,
borderRadius: 5,
padding: 6,
flex: 1,
fontSize: 16,
marginHorizontal: 4,
}}
onChangeText={(text) => {
setUserKeyword(text);
}}
value={userKeyword}
/>
<Button
title={getStr("search")}
onPress={() => {
helper.fuzzySearchLibraryId(userKeyword).then((r) => {
console.log(userKeyword);
console.log(r);
if (r.length === 0) {
Alert.alert("没有搜索到匹配的用户");
setUserItems([]);
setUserKeyword("");
} else if (r.length === 1) {
const id = r[0].id;
const label = r[0].label;
setMembers((prev) => {
if (id === undefined || label === undefined) {
Alert.alert("用户不合法");
return prev;
} else if (prev.find((o) => id === o.id) !== undefined) {
Alert.alert("用户已经成为使用者");
return prev;
} else {
return prev.concat({id: id, label: label});
}
});
setUserItems([]);
setUserKeyword("");
} else {
setUserItems(
r.map(({id, label}) => ({
id: id,
label: label,
})),
);
}
});
}}
/>
</View>
{userItems.length === 0 ? null : (
<View>
<Text style={{marginLeft: 4, marginBottom: 4}}>
有多名用户符合要求,点按以选择用户
</Text>
<View
style={{
marginLeft: 4,
flexWrap: "wrap",
flex: 1,
flexDirection: "row",
marginBottom: 4,
}}>
{[
<TouchableOpacity
style={{
backgroundColor:
colors.text === "#000000" ? "white" : "black",
borderColor: "gray",
borderRadius: 5,
borderWidth: 1,
paddingHorizontal: 4,
margin: 4,
justifyContent: "center",
}}
onPress={() => setUserItems([])}>
<View style={{flexDirection: "row", paddingVertical: 8}}>
<Text style={{color: "red"}}>取消搜索</Text>
</View>
</TouchableOpacity>,
].concat(
userItems.map(({id, label}) => (
<TouchableOpacity
onPress={() =>
Alert.alert(
`${getStr("choose")} ${label} ${getStr("?")}`,
undefined,
[
{text: getStr("cancel")},
{
text: getStr("confirm"),
onPress: () => {
setMembers((prev) => {
if (id === undefined || label === undefined) {
Alert.alert("用户不合法");
return prev;
} else if (
prev.find((o) => id === o.id) !== undefined
) {
Alert.alert("用户已经成为使用者");
return prev;
} else {
return prev.concat({id: id, label: label});
}
});
setUserItems([]);
setUserKeyword("");
},
},
],
{cancelable: true},
)
}
key={id}
style={{
backgroundColor:
colors.text === "#000000" ? "white" : "black",
borderColor: "gray",
borderRadius: 5,
borderWidth: 1,
paddingHorizontal: 4,
margin: 4,
justifyContent: "center",
}}>
<View style={{flexDirection: "row", paddingVertical: 8}}>
<Text style={{color: "gray"}}>{label}</Text>
</View>
</TouchableOpacity>
)),
)}
</View>
</View>
)}
<Text style={{marginLeft: 4, marginBottom: 4}}>
已有研读间使用者(点按可删除)
</Text>
<View
style={{
marginLeft: 4,
flexWrap: "wrap",
flex: 1,
flexDirection: "row",
marginBottom: 4,
}}>
{members.map(({id, label}) => (
<TouchableOpacity
disabled={id === helper.userId}
onPress={() =>
Alert.alert(
`${getStr("delete")} ${label}?`,
undefined,
[
{text: getStr("cancel")},
{
text: getStr("confirm"),
onPress: () =>
setMembers((prev) =>
prev.filter((it) => it.id !== id),
),
},
],
{cancelable: true},
)
}
key={id}
style={{
backgroundColor:
colors.text === "#000000" ? "white" : "black",
borderColor: "gray",
borderRadius: 5,
borderWidth: 1,
paddingHorizontal: 4,
margin: 4,
justifyContent: "center",
}}>
<View style={{flexDirection: "row", paddingVertical: 8}}>
<Text style={{color: "gray"}}>{label}</Text>
</View>
</TouchableOpacity>
))}
</View>
</View>
)}
<View style={{alignSelf: "center"}}>
<Button
title={getStr("confirm")}
onPress={() => {
Snackbar.show({
text: getStr("processing"),
duration: Snackbar.LENGTH_SHORT,
});
helper
.bookLibraryRoom(
res,
`${date} ${begValue}`,
`${date} ${endValue}`,
res.maxUser > 1 ? members.map((it) => it.id) : [],
)
.then(({success, msg}) => {
Snackbar.show({text: msg, duration: Snackbar.LENGTH_LONG});
if (success) {
Alert.alert(getStr("warning"), getStr("libRoomFirstTime"));
navigation.pop();
}
})
.catch(NetworkRetry);
}}
disabled={
begValue === null ||
endValue === null ||
members.length > res.maxUser ||
members.length < res.minUser
}
/>
</View>
</ScrollView>
);
}; | the_stack |
interface Date {
/**
* Gets the microseconds.
*
* Defined globally by the Calendar widget. __Do not use this.__
*
* @deprecated
* @return The microseconds field of this date.
*/
getMicroseconds(): number;
/**
* Set the microseconds.
*
* Defined globally by the Calendar widget. __Do not use this.__
*
* @deprecated
* @param microseconds The microseconds to set.
* @return this for chaining.
*/
setMicroseconds(microseconds: number): this;
}
/**
* Namespace for the timepicker JQueryUI plugin, available as `JQuery.fn.timepicker` and `JQuery.fn.datetimepicker`.
* Contains some additional types and interfaces required for the typings.
*/
declare namespace JQueryUITimepickerAddon {
/**
* Time units for selecting a time in the calendar widget.
*/
export type TimeUnit = "hour" | "minute" | "second" | "millisec" | "microsec";
/**
* Whether to use sliders, select elements or a custom control type for selecting a time (hour / minute / second) in
* the time picker.
*/
export type ControlType = "slider" | "select";
/**
* An offset of a timezone, in minutes relative to UTC. For example, `UTC-4` is represented as `-240`.
*/
export type TimezoneOffset = number;
/**
* How dates are parsed by the Timepicker.
*
* - `loose`: Uses the JavaScript method `new Date(timeString)` to guess the time
* - `strict`: A date text must match the timeFormat exactly.
*/
export type TimeParseType = "loose" | "strict";
/**
* A custom function for parsing a time string.
*/
export type TimeParseFunction =
/**
* @param timeFormat Format according to which to parse the time.
* @param timeString Time string to parse.
* @param optins Current options of the time picker.
* @return The parsed time, or `undefined` if the time string could not be parsed.
*/
(timeFormat: string, timeString: string, options: Partial<DatetimepickerOptions>) => TimeParseResult | undefined;
/**
* Represents the available methods on a JQuery instance for the date and / or time picker.
*/
export type PickerMethod = "datepicker" | "timepicker" | "datetimepicker";
/**
* Represents a timezone of the world.
*/
export interface Timezone {
/**
* Name of the timezone.
*/
label: string;
/**
* Offset of the timezone.
*/
value: TimezoneOffset;
}
/**
* The timepicker for working with times, such as formatting and parsing times.
*/
export interface Timepicker {
/**
* A map with a locale name (`fr`, `de`, etc.) as the key and the locale as the value.
*/
regional: Record<string, Locale>;
/**
* Current version of the DateTimePicker JQueryUI add-on.
*/
version: string;
/**
* Override the default settings for all instances of the time picker.
* @param settings The new settings to use as defaults.
* @return this for chaining.
*/
setDefaults(settings: Partial<DatetimepickerOptions>): this;
/**
* Calls `datetimepicker` on the `startTime` and `endTime` elements, and configures them to enforce the date /
* time range limits.
* @param startTime DOM element of the date/time picker with the start date/time.
* @param endTime DOM element of the date/time picker with the end date/time
* @param options Options for the `$.fn.datetimepicker` call.
*/
datetimeRange(startTime: JQuery, endTime: JQuery, options: Partial<RangeOptions>): void;
/**
* Calls `timepicker` on the `startTime` and `endTime` elements, and configures them to enforce the time range
* limits.
* @param startTime DOM element of the date/time picker with the start date/time.
* @param endTime DOM element of the date/time picker with the end date/time
* @param options Options for the `$.fn.timepicker` call.
*/
timeRange(startTime: JQuery, endTime: JQuery, options: Partial<RangeOptions>): void;
/**
* Calls `datepicker` on the `startTime` and `endTime` elements, and configures them to enforce the date
* range limits.
* @param startTime DOM element of the date/time picker with the start date/time.
* @param endTime DOM element of the date/time picker with the end date/time
* @param options Options for the `$.fn.datepicker` call.
*/
dateRange(startTime: JQuery, endTime: JQuery, options: Partial<RangeOptions>): void;
/**
* Calls the given method on the `startTime` and `endTime` elements, and configures them to enforce the date /
* time range limits.
* @param method Whether to call the `datepicker`, `timepicker`, or `datetimepicker` method on the elements.
* @param startTime DOM element of the date/time picker with the start date/time.
* @param endTime DOM element of the date/time picker with the end date/time
* @param options Options for the `$.fn.datepicker` call.
* @return A JQuery instance containing the given `startTime` and `endTime` elements.
*/
handleRange(method: PickerMethod, startTime: JQuery, endTime: JQuery, options: Partial<RangeOptions>): JQuery;
/**
* Get the timezone offset as string from a timezone offset.
* @param tzMinutes If not a number, less than `-720` (`UTC-12`), or greater than `840` (`UTC+14`),
* this value is returned as-is
* @param iso8601 If `true` formats in accordance to `iso8601` (sucha as `+12:45`).
* @return The timezone offset as a string, such as `+0530` for `UTC+5.5`.
*/
timezoneOffsetString(tzMinutes: TimezoneOffset | string, iso8601: boolean): string;
/**
* Get the number in minutes that represents a timezone string.
* @param tzString A formatted time zone string, such as `+0500`, `-1245`, or `Z`.
* @return The offset in minutes, or the given `tzString` when it does not represent a valid timezone.
*/
timezoneOffsetNumber(tzString: string): TimezoneOffset | string;
/**
* JavaScript `Date`s have not support for timezones, so we must adjust the minutes to compensate.
* @param date Date to adjust.
* @param fromTimezone Timezone of the given date.
* @param toTimezone Timezone to adjust the date to, relative to the `fromTimezone`.
* @return The given date, adjusted from the `fromTimezone` to the `toTimezone`.
*/
timezoneAdjust(date: Date, fromTimezone: string, toTimezone: string): Date;
/**
* Log error or data to the console during error or debugging.
* @param args Data to log.
*/
log(...args: readonly unknown[]): void;
}
/**
* Represents localized messages for a certain locale that are displayed by the datetimepicker.
*/
export interface Locale {
/**
* Default: `["AM", "A"]`, A Localization Setting - Array of strings to try and parse against to determine AM.
*/
amNames: string[];
/**
* Default: `["PM", "P"]`, A Localization Setting - Array of strings to try and parse against to determine PM.
*/
pmNames: string[];
/**
* Default: `HH:mm`, A Localization Setting - String of format tokens to be replaced with the time.
*/
timeFormat: string;
/**
* Default: Empty string, A Localization Setting - String to place after the formatted time.
*/
timeSuffix: string;
/**
* Default: `Choose Time`, A Localization Setting - Title of the wigit when using only timepicker.
*/
timeOnlyTitle: string;
/**
* Default: `Time`, A Localization Setting - Label used within timepicker for the formatted time.
*/
timeText: string;
/**
* Default: `Hour`, A Localization Setting - Label used to identify the hour slider.
*/
hourText: string;
/**
* Default: `Minute`, A Localization Setting - Label used to identify the minute slider.
*/
minuteText: string;
/**
* Default: `Second`, A Localization Setting - Label used to identify the second slider.
*/
secondText: string;
/**
* Default: `Millisecond`, A Localization Setting - Label used to identify the millisecond slider.
*/
millisecText: string;
/**
* Default: `Microsecond`, A Localization Setting - Label used to identify the microsecond slider.
*/
microsecText: string;
/**
* Default: `Timezone`, A Localization Setting - Label used to identify the timezone slider.
*/
timezoneText: string;
}
/**
* Represents the result of parsing a time string.
*/
export interface TimeParseResult {
/**
* Hour of the time, starting at `0`.
*/
hour: number;
/**
* Minute of the time, starting at `0`.
*/
minute: number;
/**
* Seconds of the time, starting at `0`.
*/
seconds: number;
/**
* Milliseconds of the time, starting at `0`.
*/
millisec: number;
/**
* Microseconds of the time, starting at `0`.
*/
microsec: number;
/**
* Timezone of the time.
*/
timezone?: TimezoneOffset;
}
/**
* Options for the date time picker that lets the user select a time.
*/
export interface DatetimepickerOptions extends JQueryUI.DatepickerOptions, Locale {
/**
* Default: `true` - When `altField` is used from datepicker, `altField` will only receive the formatted time
* and the original field only receives date.
*/
altFieldTimeOnly: boolean;
/**
* Default: (separator option) - String placed between formatted date and formatted time in the altField.
*/
altSeparator: string;
/**
* Default: (timeSuffix option) - String always placed after the formatted time in the altField.
*/
altTimeSuffix: string;
/**
* Default: (timeFormat option) - The time format to use with the altField.
*/
altTimeFormat: string;
/**
* Default: true - Whether to immediately focus the main field whenever the altField receives focus. Effective
* at construction time only, changing it later has no effect.
*/
altRedirectFocus: boolean;
/**
* Default: [generated timezones] - An array of timezones used to populate the timezone select.
*/
timezoneList: Timezone[] | Record<string, TimezoneOffset>;
/**
* Default: `slider` - How to select a time (hour / minute / second). If `slider` is unavailable through
* jQueryUI, `select` will be used. For advanced usage you may set this to a custom control to use controls
* other than sliders or selects.
*/
controlType: ControlType | CustomControl;
/**
* Default: `null` - Whether to show the hour control. The default of `null` will use detection from timeFormat.
*/
showHour: boolean | null;
/**
* Default: `null` - Whether to show the minute control. The default of `null` will use detection from
* timeFormat.
*/
showMinute: boolean | null;
/**
* Default: `null` - Whether to show the second control. The default of `null` will use detection from
* timeFormat.
*/
showSecond: boolean | null;
/**
* Default: `null` - Whether to show the millisecond control. The default of `null` will use detection from
* timeFormat.
*/
showMillisec: boolean | null;
/**
* Default: `null` - Whether to show the microsecond control. The default of `null` will use detection from
* timeFormat.
*/
showMicrosec: boolean | null;
/**
* Default: `null` - Whether to show the timezone select.
*/
showTimezone: boolean | null;
/**
* Default: true - Whether to show the time selected within the datetimepicker.
*/
showTime: boolean;
/**
* Default: `1` - Hours per step the slider makes.
*/
stepHour: number;
/**
* Default: `1` - Minutes per step the slider makes.
*/
stepMinute: number;
/**
* Default: `1` - Seconds per step the slider makes.
*/
stepSecond: number;
/**
* Default: `1` - Milliseconds per step the slider makes.
*/
stepMillisec: number;
/**
* Default: `1` - Microseconds per step the slider makes.
*/
stepMicrosec: number;
/**
* Default: `0` - Initial hour set.
*/
hour: number;
/**
* Default: `0` - Initial minute set.
*/
minute: number;
/**
* Default: `0` - Initial second set.
*/
second: number;
/**
* Default: `0` - Initial millisecond set.
*/
millisec: number;
/**
* Default: `0` - Initial microsecond set. Note: Javascript's native `Date` object does not natively support
* microseconds. Timepicker extends the Date object with `Date.prototype.setMicroseconds(m)` and
* `Date.prototype.getMicroseconds()`. Date comparisons will not acknowledge microseconds. Use this only for
* display purposes.
*/
microsec: number;
/**
* Default: `null` - Initial timezone set. If `null`, the browser's local timezone will be used.
*/
timezone: TimezoneOffset | null;
/**
* Default: `0` - The minimum hour allowed for all dates.
*/
hourMin: number;
/**
* Default: `0` - The minimum minute allowed for all dates.
*/
minuteMin: number;
/**
* Default: `0` - The minimum second allowed for all dates.
*/
secondMin: number;
/**
* Default: `0` - The minimum millisecond allowed for all dates.
*/
millisecMin: number;
/**
* Default: `0` - The minimum microsecond allowed for all dates.
*/
microsecMin: number;
/**
* Default: `23` - The maximum hour allowed for all dates.
*/
hourMax: number;
/**
* Default: `59` - The maximum minute allowed for all dates.
*/
minuteMax: number;
/**
* Default: `59` - The maximum second allowed for all dates.
*/
secondMax: number;
/**
* Default: `999` - The maximum millisecond allowed for all dates.
*/
millisecMax: number;
/**
* Default: `999` - The maximum microsecond allowed for all dates.
*/
microsecMax: number;
/**
* Default: `0` - When greater than `0` a label grid will be generated under the slider. This number represents
* the units (in hours) between labels.
*/
hourGrid: number;
/**
* Default: `0` - When greater than `0` a label grid will be generated under the slider. This number represents
* the units (in minutes) between labels.
*/
minuteGrid: number;
/**
* Default: `0` - When greater than `0` a label grid will be genereated under the slider. This number represents
* the units (in seconds) between labels.
*/
secondGrid: number;
/**
* Default: `0` - When greater than `0` a label grid will be genereated under the slider. This number represents
* the units (in milliseconds) between labels.
*/
millisecGrid: number;
/**
* Default: `0` - When greater than `0` a label grid will be genereated under the slider. This number represents
* the units (in microseconds) between labels.
*/
microsecGrid: number;
/**
* Default: `true` - Whether to show the button panel at the bottom. This is generally needed.
*/
showButtonPanel: boolean;
/**
* Default: `false` - Allows direct input in time field
*/
timeInput: boolean;
/**
* Default: `false` - Hide the datepicker and only provide a time interface.
*/
timeOnly: boolean;
/**
* Default: `false` - Show the date and time in the input, but only allow the timepicker.
*/
timeOnlyShowDate: boolean;
/**
* Default: unset - Function to be called when the timepicker or selection control is injected or re-rendered.
*/
afterInject(this: Timepicker): void;
/**
* Default: unset - Function to be called when a date is chosen or time has changed.
* @param datetimeText Currently selected date as text.
* @param timepicker The current timepicker instance.
*/
onSelect(this: HTMLElement | null, datetimeText: string, timepicker: Timepicker): void;
/**
* Default: `true` - Always have a time set internally, even before user has chosen one.
*/
alwaysSetTime: boolean;
/**
* Default: space (` `) - When formatting the time this string is placed between the formatted date and
* formatted time.
*/
separator: string;
/**
* Default: (timeFormat option) - How to format the time displayed within the timepicker.
*/
pickerTimeFormat: string;
/**
* Default: (timeSuffix option) - String to place after the formatted time within the timepicker.
*/
pickerTimeSuffix: string;
/**
* Default: `true` - Whether to show the timepicker within the datepicker.
*/
showTimepicker: boolean;
/**
* Default: `false` - Try to show the time dropdowns all on one line. This should be used with `controlType`
* `select` and as few units as possible.
*/
oneLine: boolean;
/**
* Default: `null` - String of the default time value placed in the input on focus when the input is empty.
*/
defaultValue: string | null;
/**
* Default: `null` - Date object of the minimum datetime allowed. Also available as minDate.
*/
minDateTime: Date | null;
/**
* Default: `null` - Date object of the maximum datetime allowed. Also Available as maxDate.
*/
maxDateTime: Date | null;
/**
* Default: `null` - String of the minimum time allowed. '8:00 am' will restrict to times after 8am
*/
minTime: string | null;
/**
* Default: `null` - String of the maximum time allowed. '8:00 pm' will restrict to times before 8pm
*/
maxTime: string | null;
/**
* Default: `strict` - How to parse the time string. You may also set this to a function to handle the parsing
* yourself.
*/
parse: TimeParseType | TimeParseFunction;
}
/**
* Optionts for the various methods of the `Timepicker` for working time date / time ranges.
*/
export interface RangeOptions extends DatetimepickerOptions {
/**
* Min allowed interval in milliseconds
*/
minInterval: number;
/**
* Max allowed interval in milliseconds
*/
maxInterval: number;
/**
* Options that are applied only to the date / time picker for the start date / time.
*/
start: Partial<DatetimepickerOptions>;
/**
* Options that are applied only to the date / time picker for the end date / time.
*/
end: Partial<DatetimepickerOptions>;
}
/**
* Options for a custom control for selecting an hour, minute, or seconds. The control should behave in such a way
* that the user may select a number in the set `{ min, min+step, min+2*step, ..., max }`.
*/
export interface ControlOptions {
/**
* Maximum allowed value for the time unit the user may select.
*/
max: number;
/**
* Minumum allowed value for the time unit the user may select.
*/
min: number;
/**
* Desired step size for selecting a value.
*/
step: number;
}
/**
* For advanced usage of the Calendar, you may pass an object of this type to use controls other than sliders and
* selects for selecting an hour, minute, or second.
*/
export interface CustomControl {
/**
* Creates the control for the given time unit and appends it to the given `container` element.
* @param instance The current date time picker instance.
* @param container The container element to which the created control must be appended.
* @param unit The type of control for which to set the value.
* @param val Initial value for the control
* @param min Minumum allowed value for the time unit the user may select.
* @param max Maximum allowed value for the time unit the user may select.
* @param step Desired step size for selecting a value.
* @return The `container` element as passed to this method.
*/
create(instance: Timepicker, container: JQuery, unit: TimeUnit, val: number, min: number, max: number, step: number): JQuery;
/**
* Sets the given ooptions on the control for the given time unit.
* @param instance The current date time picker instance.
* @param container The container element of the control, as passed to `create`.
* @param unit The type of control for which to apply the options.
* @param opts Options to apply on the control
* @return The `container` element as passed to this method.
*/
options(instance: Timepicker, container: JQuery, unit: TimeUnit, opts: Partial<ControlOptions>): JQuery;
/**
* Sets the value of control for the given time uit.
* @param instance The current date time picker instance.
* @param container The container element of the control, as passed to `create`.
* @param unit The type of control for which to set the value.
* @param val Value to set on this control.
* @return The `container` element as passed to this method.
*/
value(instance: Timepicker, container: JQuery, unit: TimeUnit, val: number): JQuery;
/**
* Gets the current value of the control for the given time unit.
* @param instance The current date time picker instance.
* @param container The container element of the control, as passed to `create`.
* @param unit The type of control for which to get the value.
* @return The current value of the control.
*/
value(instance: Timepicker, container: JQuery, unit: TimeUnit): number;
}
}
interface JQuery {
/**
* Initializes the datetimepicker on this element. It lets the user select both a date and a time (hour and
* minute).
* @param cfg Options for the datetimepicker.
* @return this for chaining.
*/
datetimepicker(cfg?: Partial<JQueryUITimepickerAddon.DatetimepickerOptions>): this;
/**
* Sets and selects the given date.
* @param methodName Name of the method to invoke.
* @param date The new date to select. When not given, unselects the date.
* @return this for chaining.
*/
datetimepicker(methodName: "setDate", date?: Date): this;
/**
* Finds the currently selected date of the datetimepicker.
* @param methodName Name of the method to invoke.
* @return The currently selected date, or `null` if no date is selected.
*/
datetimepicker(methodName: "getDate"): Date | null;
/**
* Enables the datetimepicker so that the user can now select a date.
* @param methodName Name of the method to invoke.
* @return this for chaining.
*/
datetimepicker(methodName: "enable"): this;
/**
* Disables the datetimepicker so that the user cannot select a date anymore.
* @param methodName Name of the method to invoke.
* @return this for chaining.
*/
datetimepicker(methodName: "disable"): this;
/**
* Sets the minimum allowed date the user may select.
* @param methodName Name of the method to invoke.
* @param optionName Name of the option to set.
* @param date New value for the option.
* @return this for chaining.
*/
datetimepicker(methodName: "option", optionName: "minDate", date: Date): this;
/**
* Sets the maximum allowed date the user may select.
* @param methodName Name of the method to invoke.
* @param optionName Name of the option to set.
* @param date New value for the option.
* @return this for chaining.
*/
datetimepicker(methodName: "option", optionName: "maxDate", date: Date): this;
/**
* Initializes the timepicker on this element. It lets the user select a time (hour and minute).
* @param cfg Options for the datetimepicker.
* @return this for chaining.
*/
timepicker(cfg?: Partial<JQueryUITimepickerAddon.DatetimepickerOptions>): this;
}
interface JQueryStatic {
/**
* The global instance of the timepicker utility class for working with times.
*/
timepicker: JQueryUITimepickerAddon.Timepicker;
} | the_stack |
import { Component } from '@angular/core';
import { downgradeComponent } from '@angular/upgrade/static';
import { TopicCreationService } from 'components/entity-creation-services/topic-creation.service';
import { SkillSummary } from 'domain/skill/skill-summary.model';
import { CreatorTopicSummary } from 'domain/topic/creator-topic-summary.model';
import { CategorizedSkills, TopicsAndSkillsDashboardBackendApiService } from 'domain/topics_and_skills_dashboard/topics-and-skills-dashboard-backend-api.service';
import { TopicsAndSkillsDashboardFilter } from 'domain/topics_and_skills_dashboard/topics-and-skills-dashboard-filter.model';
import debounce from 'lodash/debounce';
import { CreateNewSkillModalService } from 'pages/topic-editor-page/services/create-new-skill-modal.service';
import { Subscription } from 'rxjs';
import { WindowDimensionsService } from 'services/contextual/window-dimensions.service';
import { FocusManagerService } from 'services/stateful/focus-manager.service';
import { ETopicPublishedOptions, TopicsAndSkillsDashboardPageConstants } from './topics-and-skills-dashboard-page.constants';
import { TopicsAndSkillsDashboardPageService } from './topics-and-skills-dashboard-page.service';
@Component({
selector: 'oppia-topics-and-skills-dashboard-page',
templateUrl: './topics-and-skills-dashboard-page.component.html'
})
export class TopicsAndSkillsDashboardPageComponent {
directiveSubscriptions: Subscription = new Subscription();
TOPIC_CLASSROOM_UNASSIGNED: string = 'UNASSIGNED';
totalTopicSummaries: CreatorTopicSummary[] = [];
topicSummaries: CreatorTopicSummary[] = [];
totalEntityCountToDisplay: number;
currentCount: number;
totalSkillCount: number;
skillsCategorizedByTopics: CategorizedSkills;
editableTopicSummaries: CreatorTopicSummary[] = [];
untriagedSkillSummaries: SkillSummary[] = [];
totalUntriagedSkillSummaries: SkillSummary[] = [];
mergeableSkillSummaries: SkillSummary[] = [];
skillSummaries: SkillSummary[] = [];
userCanCreateTopic: boolean;
userCanCreateSkill: boolean;
userCanDeleteTopic: boolean;
userCanDeleteSkill: boolean;
TAB_NAME_TOPICS: string = 'topics';
activeTab: string;
MOVE_TO_NEXT_PAGE: string = 'next_page';
MOVE_TO_PREV_PAGE: string = 'prev_page';
TAB_NAME_SKILLS: string = 'skills';
pageNumber: number = 0;
topicPageNumber: number = 0;
itemsPerPage: number = 10;
skillPageNumber: number = 0;
lastSkillPage: number = 0;
itemsPerPageChoice: number[] = [10, 15, 20];
filterBoxIsShown: boolean;
filterObject: TopicsAndSkillsDashboardFilter;
classrooms: string[] = [];
sortOptions: string[] = [];
statusOptions: ETopicPublishedOptions[] = [];
fetchSkillsDebounced;
lastPage: number;
moreSkillsPresent: boolean;
nextCursor: string;
firstTimeFetchingSkills: boolean;
displayedTopicSummaries: CreatorTopicSummary[] = [];
displayedSkillSummaries: SkillSummary[] = [];
skillStatusOptions: string[] = [];
constructor(
private focusManagerService: FocusManagerService,
private createNewSkillModalService: CreateNewSkillModalService,
private topicCreationService: TopicCreationService,
private topicsAndSkillsDashboardBackendApiService:
TopicsAndSkillsDashboardBackendApiService,
private topicsAndSkillsDashboardPageService:
TopicsAndSkillsDashboardPageService,
private windowDimensionsService: WindowDimensionsService
) {}
ngOnInit(): void {
this.activeTab = this.TAB_NAME_TOPICS;
this.filterBoxIsShown = !this.windowDimensionsService.isWindowNarrow();
this.filterObject = TopicsAndSkillsDashboardFilter.createDefault();
for (let key in TopicsAndSkillsDashboardPageConstants.TOPIC_SORT_OPTIONS) {
this.sortOptions.push(
TopicsAndSkillsDashboardPageConstants.TOPIC_SORT_OPTIONS[key]);
}
for (let key in TopicsAndSkillsDashboardPageConstants
.TOPIC_PUBLISHED_OPTIONS) {
this.statusOptions.push(
TopicsAndSkillsDashboardPageConstants.TOPIC_PUBLISHED_OPTIONS[key]);
}
this.fetchSkillsDebounced = debounce(this.fetchSkills, 300);
this.directiveSubscriptions.add(
this.topicsAndSkillsDashboardBackendApiService.
onTopicsAndSkillsDashboardReinitialized.subscribe(
(stayInSameTab: boolean) => {
this._initDashboard(stayInSameTab);
}
)
);
this._initDashboard(false);
}
ngOnDestroy(): void {
this.directiveSubscriptions.unsubscribe();
}
generateNumbersTillRange(range: number): number[] {
let arr: number[] = [];
for (let i = 0; i < range; i++) {
arr.push(i);
}
return arr;
}
/**
* Tells whether the next skill page is present in memory or not.
* This case occurs when the next page is fetched from the backend
* and then we move back one page, but the next page is still in
* memory. So instead of making the backend call for the next page,
* we first check if the next page is present in memory.
* @returns {Boolean} - Whether the next page is present or not.
*/
isNextSkillPagePresent(): boolean {
let totalSkillsPresent: number = this.skillSummaries.length;
// Here +1 is used since we are checking the next page and
// another +1 because page numbers start from 0.
let numberOfSkillsRequired: number = (
(this.skillPageNumber + 2) * this.itemsPerPage);
return totalSkillsPresent >= numberOfSkillsRequired;
}
/**
* Sets the active tab to topics or skills.
* @param {String} tabName - name of the tab to set.
*/
setActiveTab(tabName: string): void {
this.activeTab = tabName;
this.filterObject.reset();
if (this.activeTab === this.TAB_NAME_TOPICS) {
this.goToPageNumber(this.topicPageNumber);
this.focusManagerService.setFocus('createTopicBtn');
} else if (this.activeTab === this.TAB_NAME_SKILLS) {
this.initSkillDashboard();
this.focusManagerService.setFocus('createSkillBtn');
}
}
initSkillDashboard(): void {
this.skillStatusOptions = [];
this.moreSkillsPresent = true;
this.firstTimeFetchingSkills = true;
for (let key in TopicsAndSkillsDashboardPageConstants
.SKILL_STATUS_OPTIONS) {
this.skillStatusOptions
.push(TopicsAndSkillsDashboardPageConstants.SKILL_STATUS_OPTIONS[key]);
}
this.applyFilters();
}
createTopic(): void {
this.topicCreationService.createNewTopic();
}
createSkill(): void {
this.createNewSkillModalService.createNewSkill();
}
/**
* @param {Number} pageNumber - Page number to navigate to.
*/
goToPageNumber(pageNumber: number): void {
if (this.activeTab === this.TAB_NAME_TOPICS) {
this.topicPageNumber = pageNumber;
this.pageNumber = this.topicPageNumber;
this.currentCount = this.topicSummaries.length;
this.displayedTopicSummaries =
this.topicSummaries.slice(
pageNumber * this.itemsPerPage,
(pageNumber + 1) * this.itemsPerPage);
} else if (this.activeTab === this.TAB_NAME_SKILLS) {
this.skillPageNumber = pageNumber;
this.pageNumber = this.skillPageNumber;
this.displayedSkillSummaries = this.skillSummaries.slice(
pageNumber * this.itemsPerPage,
(pageNumber + 1) * this.itemsPerPage);
}
}
fetchSkills(): void {
if (this.moreSkillsPresent) {
this.topicsAndSkillsDashboardBackendApiService
.fetchSkillsDashboardDataAsync(
this.filterObject, this.itemsPerPage, this.nextCursor).then(
(response) => {
this.moreSkillsPresent = response.more;
this.nextCursor = response.nextCursor;
this.skillSummaries.push(...response.skillSummaries);
this.currentCount = this.skillSummaries.length;
if (this.firstTimeFetchingSkills) {
this.goToPageNumber(0);
this.firstTimeFetchingSkills = false;
} else {
this.goToPageNumber(this.pageNumber + 1);
}
});
} else if (this.skillSummaries.length >
((this.skillPageNumber + 1) * this.itemsPerPage)) {
this.goToPageNumber(this.pageNumber + 1);
}
}
navigateSkillPage(direction: string): void {
if (direction === this.MOVE_TO_NEXT_PAGE) {
if (this.isNextSkillPagePresent()) {
this.goToPageNumber(this.pageNumber + 1);
} else {
this.fetchSkillsDebounced();
}
} else if (this.pageNumber >= 1) {
this.goToPageNumber(this.pageNumber - 1);
}
}
/**
* @param {String} direction - Direction, whether to change the
* page to left or right by 1.
*/
changePageByOne(direction: string): void {
this.lastPage = parseInt(
String(this.currentCount / this.itemsPerPage));
if (direction === this.MOVE_TO_PREV_PAGE && this.pageNumber >= 1) {
this.goToPageNumber(this.pageNumber - 1);
} else if (direction === this.MOVE_TO_NEXT_PAGE &&
this.pageNumber < this.lastPage - 1) {
this.goToPageNumber(this.pageNumber + 1);
}
}
applyFilters(): void {
if (this.activeTab === this.TAB_NAME_SKILLS) {
this.moreSkillsPresent = true;
this.firstTimeFetchingSkills = true;
this.skillSummaries = [];
this.nextCursor = null;
this.fetchSkills();
return;
}
this.topicSummaries = (
this.topicsAndSkillsDashboardPageService.getFilteredTopics(
this.totalTopicSummaries, this.filterObject));
this.displayedTopicSummaries =
this.topicSummaries.slice(0, this.itemsPerPage);
this.currentCount = this.topicSummaries.length;
this.goToPageNumber(0);
}
resetFilters(): void {
this.getUpperLimitValueForPagination();
this.topicSummaries = this.totalTopicSummaries;
this.currentCount = this.totalEntityCountToDisplay;
this.filterObject.reset();
this.applyFilters();
}
toggleFilterBox(): void {
this.filterBoxIsShown = !this.filterBoxIsShown;
}
getUpperLimitValueForPagination(): number {
return (
Math.min((
(this.pageNumber * this.itemsPerPage) +
this.itemsPerPage), this.currentCount));
}
getTotalCountValueForSkills(): number | string {
if (this.skillSummaries.length > this.itemsPerPage) {
return 'many';
}
return this.skillSummaries.length;
}
refreshPagination(): void {
this.goToPageNumber(0);
}
/**
* Calls the TopicsAndSkillsDashboardBackendApiService and fetches
* the topics and skills dashboard data.
* @param {Boolean} stayInSameTab - To stay in the same tab or not.
*/
_initDashboard(stayInSameTab: boolean): void {
this.topicsAndSkillsDashboardBackendApiService.fetchDashboardDataAsync()
.then((response) => {
this.totalTopicSummaries = response.topicSummaries;
this.topicSummaries = this.totalTopicSummaries;
this.totalEntityCountToDisplay = this.topicSummaries.length;
this.currentCount = this.totalEntityCountToDisplay;
this.applyFilters();
this.editableTopicSummaries = this.topicSummaries
.filter((summary) => summary.canEditTopic === true);
this.focusManagerService.setFocus('createTopicBtn');
this.totalSkillCount = response.totalSkillCount;
this.skillsCategorizedByTopics = response.categorizedSkillsDict;
this.untriagedSkillSummaries = response.untriagedSkillSummaries;
this.totalUntriagedSkillSummaries = this.untriagedSkillSummaries;
this.mergeableSkillSummaries = response.mergeableSkillSummaries;
if (!stayInSameTab || !this.activeTab) {
this.activeTab = this.TAB_NAME_TOPICS;
}
this.userCanCreateSkill = response.canCreateSkill;
this.userCanCreateTopic = response.canCreateTopic;
this.userCanDeleteSkill = response.canDeleteSkill;
this.userCanDeleteTopic = response.canDeleteTopic;
if (this.topicSummaries.length === 0 &&
this.untriagedSkillSummaries.length !== 0) {
this.activeTab = this.TAB_NAME_SKILLS;
this.initSkillDashboard();
this.focusManagerService.setFocus('createSkillBtn');
}
this.classrooms = response.allClassroomNames;
});
}
}
angular.module('oppia').directive('oppiaTopicsAndSkillsDashboardPage',
downgradeComponent({ component: TopicsAndSkillsDashboardPageComponent })); | the_stack |
/**
* @license Copyright © 2013 onwards, Andrew Whewell
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @fileoverview A jQueryUI plugin that displays a single aircraft's location and attitude on a map.
*/
namespace VRS
{
/*
* Global options
*/
export var globalOptions: GlobalOptions = VRS.globalOptions || {};
VRS.globalOptions.aircraftPositionMapClass = VRS.globalOptions.aircraftPositionMapClass || 'aircraftPosnMap'; // The class to use for the aircraft position map widget container.
/**
* The state carried by an aircraft position map widget.
*/
class AircraftPositionMapPlugin_State
{
/**
* The jQuery container element for the map.
*/
mapContainer: JQuery = null;
/**
* The direct reference to the map in the map container. This will be null until after the map has completed
* loading, which could be some time after _create has finished.
*/
mapPlugin: IMap = null;
/**
* The collection of aircraft to plot on the map.
*/
aircraftCollection = new VRS.AircraftCollection();
/**
* The aircraft to show in the selected state.
*/
selectedAircraft: Aircraft = null;
/**
* The aircraft plotter that will plot the aircraft for us.
*/
aircraftPlotter: AircraftPlotter = null;
/**
* The direct reference to the map whose settings are being mirrored.
*/
mirrorMapPlugin: IMap = null;
/**
* True if the plugin has never rendered an aircraft before, false if it has.
*/
firstRender = true;
/**
* The hook result for our map's map type changed event.
*/
mapTypeChangedHookResult: IEventHandleJQueryUI = null;
/**
* The hook result for the mirror map's map type changed event.
*/
mirrorMapTypeChangedHookResult: IEventHandleJQueryUI = null;
}
/*
* jQueryUIHelper
*/
export var jQueryUIHelper: JQueryUIHelper = VRS.jQueryUIHelper || {};
VRS.jQueryUIHelper.getAircraftPositionMapPlugin = function(jQueryElement: JQuery) : AircraftPositionMapPlugin
{
return <AircraftPositionMapPlugin>jQueryElement.data('vrsVrsAircraftPositonMap');
}
VRS.jQueryUIHelper.getAircraftPositionMapOptions = function(overrides: AircraftPositionMapPlugin_Options) : AircraftPositionMapPlugin_Options
{
return $.extend({
plotterOptions: null,
mirrorMapJQ: null,
stateName: null,
mapOptionOverrides: {},
unitDisplayPreferences: undefined,
autoHideNoPosition: true,
reflectMapTypeBackToMirror: true
}, overrides);
}
/**
* The options supported by instances of AircraftPositionMapPlugin.
*/
export interface AircraftPositionMapPlugin_Options
{
/**
* The mandatory plotter options to use when plotting aircraft.
*/
plotterOptions: AircraftPlotterOptions;
/**
* The map whose settings are going to be mirrored on this map.
*/
mirrorMapJQ: JQuery;
/**
* If supplied then the map state is saved between sessions against this name. If not supplied then state is not saved.
*/
stateName?: string;
/**
* Settings to apply to the map that override those already set on the mirror map.
*/
mapOptionOverrides?: IMapOptions;
/**
* The unit display preferences to use when displaying the marker.
*/
unitDisplayPreferences?: UnitDisplayPreferences;
/**
* True if the element should be hidden when asked to render a position for aircraft that have no position. If false then the marker is just removed from the map.
*/
autoHideNoPosition: boolean;
/**
* True if changes to the map type on the plugin's map should be reflected on the mirror map.
*/
reflectMapTypeBackToMirror?: boolean;
}
/**
* A jQuery widget that can display a single aircraft's location on a map.
*/
/*
* The intention is that is displayed on aircraft detail panels and that it borrows many settings from the main map
* display. So for instance, if the user changes the map style of the main map then this map follows suit.
*
* Because this is intended for use as a property render item it is not auto-updating - you need to call renderAircraft
* with a VRS.Aircraft in order for it to display the aircraft's position, it won't hook an aircraft list and render
* the aircraft automatically.
*/
export class AircraftPositionMapPlugin extends JQueryUICustomWidget
{
options: AircraftPositionMapPlugin_Options;
constructor()
{
super();
this.options = VRS.jQueryUIHelper.getAircraftPositionMapOptions();
}
private _getState() : AircraftPositionMapPlugin_State
{
var result = this.element.data('aircraftPositionMapState');
if(result === undefined) {
result = new AircraftPositionMapPlugin_State();
this.element.data('aircraftPositionMapState', result);
}
return result;
}
_create()
{
var state = this._getState();
var options = this.options;
this.element.addClass(VRS.globalOptions.aircraftPositionMapClass);
if(options.mirrorMapJQ) {
state.mirrorMapPlugin = VRS.jQueryUIHelper.getMapPlugin(options.mirrorMapJQ);
}
// This method can return before the map has finished loading. Further construction of the object is completed
// by a callback to _mapCreated, don't put any construction that relies on the map having been loaded after
// this call.
this._createMap(state);
}
/**
* Creates the map container and populates it with a map.
*/
private _createMap(state: AircraftPositionMapPlugin_State)
{
var options = this.options;
var mapOptions: IMapOptions = {};
if(state.mirrorMapPlugin && state.mirrorMapPlugin.isOpen()) {
mapOptions.zoom = state.mirrorMapPlugin.getZoom();
mapOptions.center = state.mirrorMapPlugin.getCenter();
mapOptions.mapTypeId = state.mirrorMapPlugin.getMapType();
mapOptions.streetViewControl = state.mirrorMapPlugin.getStreetView();
mapOptions.scrollwheel = state.mirrorMapPlugin.getScrollWheel();
mapOptions.draggable = state.mirrorMapPlugin.getDraggable();
mapOptions.controlStyle = VRS.MapControlStyle.DropdownMenu;
mapOptions.useServerDefaults = false;
}
$.extend(mapOptions, options.mapOptionOverrides);
if(!options.stateName) {
mapOptions.autoSaveState = false;
} else {
mapOptions.autoSaveState = true;
mapOptions.name = options.stateName;
mapOptions.useStateOnOpen = true;
}
mapOptions.afterOpen = $.proxy(this._mapCreated, this);
state.mapContainer = $('<div/>')
.appendTo(this.element);
state.mapContainer.vrsMap(VRS.jQueryUIHelper.getMapOptions(mapOptions));
}
/**
* Called once the map has been opened. Completes the construction of the UI.
*/
_mapCreated()
{
var state = this._getState();
var options = this.options;
// Guard against the possible call to this on a plugin that is destroyed before the map finishes loading. In
// this case the mapContainer will have been destroyed.
if(state.mapContainer) {
state.mapPlugin = VRS.jQueryUIHelper.getMapPlugin(state.mapContainer);
if(state.mapPlugin && state.mapPlugin.isOpen()) {
state.aircraftPlotter = new VRS.AircraftPlotter({
plotterOptions: options.plotterOptions,
map: state.mapContainer,
unitDisplayPreferences: options.unitDisplayPreferences,
getAircraft: $.proxy(this._getAircraft, this),
getSelectedAircraft: $.proxy(this._getSelectedAircraft, this),
suppressMarkerClustering: true
});
}
state.mapTypeChangedHookResult = state.mapPlugin.hookMapTypeChanged(this._mapTypeChanged, this);
if(state.mirrorMapPlugin) {
state.mirrorMapTypeChangedHookResult = state.mirrorMapPlugin.hookMapTypeChanged(this._mirrorMapTypeChanged, this);
}
}
}
_destroy()
{
var state = this._getState();
if(state.mapTypeChangedHookResult) state.mapPlugin.unhook(state.mapTypeChangedHookResult);
state.mapTypeChangedHookResult = null;
if(state.mirrorMapTypeChangedHookResult) state.mirrorMapPlugin.unhook(state.mirrorMapTypeChangedHookResult);
state.mirrorMapTypeChangedHookResult = null;
state.mirrorMapPlugin = null;
if(state.mapPlugin) {
state.mapPlugin.destroy();
state.mapPlugin = null;
}
state.mapContainer = null;
if(state.aircraftPlotter) state.aircraftPlotter.dispose();
state.aircraftPlotter = null;
state.aircraftCollection = null;
this.element.removeClass(VRS.globalOptions.aircraftPositionMapClass);
this.element.empty();
}
/**
* Renders the aircraft on the map.
*/
renderAircraft(aircraft: Aircraft, showAsSelected: boolean)
{
var state = this._getState();
var options = this.options;
if(state.aircraftPlotter) {
if(aircraft && !aircraft.hasPosition()) aircraft = null;
var existingAircraft = state.aircraftCollection.toList();
if(!aircraft) {
if(existingAircraft.length > 0) state.aircraftCollection = new VRS.AircraftCollection();
} else {
if(existingAircraft.length !== 1 || existingAircraft[aircraft.id] !== aircraft) {
state.aircraftCollection = new VRS.AircraftCollection();
state.aircraftCollection[aircraft.id] = aircraft;
}
}
state.selectedAircraft = showAsSelected ? aircraft : null;
if(!aircraft) {
if(options.autoHideNoPosition) {
$(this.element, ':visible').hide();
} else {
state.aircraftPlotter.plot();
}
} else {
var refreshMap = state.firstRender || (options.autoHideNoPosition && this.element.is(':hidden'));
if(refreshMap) {
this.element.show();
state.mapPlugin.refreshMap();
}
state.mapPlugin.panTo(aircraft.getPosition());
state.aircraftPlotter.plot();
state.firstRender = false;
}
}
}
/**
* Suspends or resumes updates.
*/
suspend(onOff: boolean)
{
var state = this._getState();
if(state.aircraftPlotter) {
state.aircraftPlotter.suspend(onOff);
}
}
/**
* Called when our map's map type has changed.
*/
private _mapTypeChanged()
{
var state = this._getState();
var options = this.options;
if(state.mirrorMapPlugin && state.mapPlugin && options.reflectMapTypeBackToMirror) {
state.mirrorMapPlugin.setMapType(state.mapPlugin.getMapType());
}
}
/**
* Called when the map that we're mirroring has changed map type.
*/
private _mirrorMapTypeChanged()
{
var state = this._getState();
if(state.mirrorMapPlugin && state.mapPlugin) {
state.mapPlugin.setMapType(state.mirrorMapPlugin.getMapType());
}
}
/**
* Called when the plotter wants to know the list of aircraft to plot.
*/
private _getAircraft()
{
var state = this._getState();
return state.aircraftCollection;
}
/**
* Called when the plotter wants to know which aircraft has been selected.
*/
_getSelectedAircraft() : Aircraft
{
var state = this._getState();
return state.selectedAircraft;
}
}
$.widget('vrs.vrsAircraftPositonMap', new AircraftPositionMapPlugin());
}
declare interface JQuery
{
vrsAircraftPositonMap();
vrsAircraftPositonMap(options: VRS.AircraftPositionMapPlugin_Options);
vrsAircraftPositonMap(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any);
} | the_stack |
import puppeteer from 'puppeteer'
import http from 'http'
import { getPortPromise as getPort } from 'portfinder'
import Rize from 'rize'
test(
'go to a specified url',
async () => {
expect.assertions(1)
const instance = new Rize({
afterLaunched() {
jest
.spyOn(instance.page, 'goto')
.mockImplementation(() => Promise.resolve(null))
}
})
await instance
.goto('url')
.execute(() => {
expect(instance.page.goto).toBeCalledWith('url')
})
.end()
},
process.env.CI ? 8000 : 5000
)
test('open a new page', async () => {
expect.assertions(7)
const port = await getPort()
const server = http.createServer((_, res) => res.end('')).listen(port)
const instance = new Rize()
await instance
.newPage()
.execute(
async browser => await expect(browser.pages()).resolves.toHaveLength(3)
)
.goto(`http://localhost:${port}/`)
.newPage()
.execute((browser, page) =>
expect(page.url()).toBe(`http://localhost:${port}/`)
)
.execute(
async browser => await expect(browser.pages()).resolves.toHaveLength(3)
)
.newPage('', { force: true })
.execute(async (browser, page) => {
await expect(browser.pages()).resolves.toHaveLength(3)
expect(page.url()).toBe('about:blank')
})
.goto(`http://localhost:${port}/`)
.newPage('another page', { stayCurrent: true })
.execute(async (browser, page) => {
await expect(browser.pages()).resolves.toHaveLength(4)
expect(page.url()).toBe(`http://localhost:${port}/`)
server.close()
})
.end()
})
test('switch page', async () => {
expect.assertions(2)
const port = await getPort()
const server = http.createServer((req, res) => res.end('')).listen(port)
const instance = new Rize()
await instance
.newPage('page1')
.goto(`http://localhost:${port}/page1`)
.switchPage(0)
.execute((browser, page) => expect(page.url()).toBe('about:blank'))
.switchPage('page1')
.execute((browser, page) => {
expect(page.url()).toBe(`http://localhost:${port}/page1`)
server.close()
})
.end()
})
test('close page', async () => {
expect.assertions(2)
const instance = new Rize()
await instance
.closePage()
.execute(async () => {
await expect(instance.browser.pages()).resolves.toHaveLength(1)
})
.newPage('page1')
.closePage('nope') // Should not throw any errors
.closePage('page1')
.execute(async () => {
await expect(instance.browser.pages()).resolves.toHaveLength(1)
})
.newPage('page2')
.newPage('page3')
.closePage('page2')
.end()
})
test('count pages', async () => {
const instance = new Rize()
instance.newPage()
await expect(instance.pagesCount()).resolves.toBe(2)
await instance.end()
})
test('go forward', async () => {
expect.assertions(2)
const instance = new Rize({
afterLaunched() {
jest
.spyOn(instance.page, 'goForward')
.mockImplementation(() => Promise.resolve(null))
}
})
await instance
.forward()
.execute(() => {
expect(instance.page.goForward).toBeCalled()
})
.forward({ timeout: 1 })
.execute(() => {
expect(
(instance.page.goForward as ((
options?: puppeteer.NavigationOptions
) => Promise<puppeteer.Response>) &
jest.MockInstance<any, any[]>).mock.calls[1][0]
).toEqual({ timeout: 1 })
})
.end()
})
test('go back', async () => {
expect.assertions(2)
const instance = new Rize({
afterLaunched() {
jest
.spyOn(instance.page, 'goBack')
.mockImplementation(() => Promise.resolve(null))
}
})
await instance
.back()
.execute(() => {
expect(instance.page.goBack).toBeCalled()
})
.back({ timeout: 1 })
.execute(() => {
expect(
(instance.page.goBack as ((
options?: puppeteer.NavigationOptions
) => Promise<puppeteer.Response>) &
jest.MockInstance<any, any[]>).mock.calls[1][0]
).toEqual({ timeout: 1 })
})
.end()
})
test('refresh page', async () => {
expect.assertions(2)
const instance = new Rize({
afterLaunched() {
jest
.spyOn(instance.page, 'reload')
.mockImplementation(() => Promise.resolve({} as puppeteer.Response))
}
})
await instance
.refresh()
.execute(() => {
expect(instance.page.reload).toBeCalled()
})
.refresh({ timeout: 1 })
.execute(() => {
expect(
(instance.page.reload as ((
options?: puppeteer.NavigationOptions
) => Promise<puppeteer.Response>) &
jest.MockInstance<any, any[]>).mock.calls[1][0]
).toEqual({ timeout: 1 })
})
.end()
})
test('evaluate a function', async () => {
expect.assertions(3)
const instance = new Rize()
await instance
.evaluate(text => document.write(`<div>${text}</div>`), 'rize')
.execute(async (browser, page) => {
const text = await page.$eval('div', element => element.textContent)
expect(text).toBe('rize')
})
.evaluate(
() => {
const element = document.querySelector('div')
if (element) {
element.textContent = 'syaro'
}
},
// @ts-ignore
undefined // Don't remove it. It is for test coverage.
)
.execute(async (browser, page) => {
const text = await page.$eval('div', element => element.textContent)
expect(text).toBe('syaro')
})
.evaluate('document.querySelector("div").textContent = "maya"')
.execute(async (browser, page) => {
const text = await page.$eval('div', element => element.textContent)
expect(text).toBe('maya')
})
.end()
})
test('evaluate a funtion and retrieve return value', async () => {
const port = await getPort()
const server = http
.createServer((req, res) =>
res.end(`
<html><head><title>rize</title></head></html>
`)
)
.listen(port)
const instance = new Rize()
instance.goto(`http://localhost:${port}/`)
await expect(instance.evaluateWithReturn(() => document.title)).resolves.toBe(
'rize'
)
await expect(instance.evaluateWithReturn('document.title')).resolves.toBe(
'rize'
)
await instance.execute(() => server.close()).end()
})
test('use user agent', async () => {
expect.assertions(1)
const instance = new Rize()
await instance
.withUserAgent('Chrome')
.execute(async () => {
const ua = await instance.page.evaluate(() => navigator.userAgent)
expect(ua).toBe('Chrome')
})
.end()
})
test('generate a screenshot', async () => {
expect.assertions(2)
const instance = new Rize({
afterLaunched() {
jest
.spyOn(instance.page, 'screenshot')
.mockImplementation(() => Promise.resolve(''))
}
})
await instance
.saveScreenshot('file1')
.execute(() => {
expect(instance.page.screenshot).toBeCalledWith({ path: 'file1' })
})
.saveScreenshot('file2', { type: 'jpeg' })
.execute(() => {
expect(
instance.page.screenshot as typeof instance.page.screenshot &
jest.MockInstance<any, any[]>
).toBeCalledWith({ path: 'file2', type: 'jpeg' })
})
.end()
})
test('generate a PDF', async () => {
expect.assertions(2)
const instance = new Rize({
afterLaunched() {
jest
.spyOn(instance.page, 'pdf')
.mockImplementation(() => Promise.resolve({} as Buffer))
}
})
await instance
.savePDF('file1')
.execute(() => {
expect(instance.page.pdf).toBeCalledWith({ path: 'file1' })
})
.savePDF('file2', { format: 'Letter' })
.execute(() => {
expect(
instance.page.pdf as typeof instance.page.pdf &
jest.MockInstance<any, any[]>
).toBeCalledWith({
path: 'file2',
format: 'Letter'
})
})
.end()
})
test('wait for navigation', async () => {
expect.assertions(1)
const port1 = 2333
const port2 = 23333
const server1 = http
.createServer((req, res) =>
res.end(`
<a href="http://localhost:${port2}"></a>
`)
)
.listen(port1)
const server2 = http.createServer((req, res) => res.end('')).listen(port2)
const instance = new Rize()
await instance
.goto(`http://localhost:${port1}`)
.execute(async (browser, page) => {
// Please use `!` operator. Do not use `page.$eval` or `page.click`.
await page.evaluate(() => document.querySelector('a')!.click())
})
.waitForNavigation()
.execute((browser, page) => {
expect(page.url()).toBe(`http://localhost:${port2}/`)
server1.close()
server2.close()
})
.end()
})
test('wait for an element', async () => {
const port = await getPort()
const server = http
.createServer((req, res) =>
res.end(`
<div></div>
`)
)
.listen(port)
const instance = new Rize()
await instance
.goto(`http://localhost:${port}`)
.waitForElement('div')
.execute(() => {
server.close()
})
.end()
})
test('wait for a function and an expression', async () => {
const instance = new Rize()
await instance
.waitForEvaluation(() => true)
.waitForEvaluation('true')
.end()
})
test('authentication', async () => {
expect.assertions(1)
const instance = new Rize({
afterLaunched() {
this.page.authenticate = jest.fn()
}
})
await instance
.withAuth('Tedeza Rize', 'Komichi Aya')
.execute((browser, page) => {
expect(page.authenticate).toBeCalledWith({
username: 'Tedeza Rize',
password: 'Komichi Aya'
})
})
.end()
})
test('set headers', async () => {
expect.assertions(1)
const instance = new Rize()
await instance
.execute(() => {
jest.spyOn(instance.page, 'setExtraHTTPHeaders')
})
.withHeaders({ 'X-Requested-With': 'XMLHttpRequest' })
.execute(() => {
expect(instance.page.setExtraHTTPHeaders).toBeCalledWith({
'X-Requested-With': 'XMLHttpRequest'
})
})
.end()
})
test('add script tag', async () => {
expect.assertions(2)
const instance = new Rize()
await instance
.addScriptTag('content', 'document.body.textContent = "rize"')
.execute(async (browser, page) => {
const text = await page.evaluate('document.body.textContent')
expect(text).toBe('rize')
})
.addScriptTag('content', '', { esModule: true })
.execute(async (browser, page) => {
const hasTag: boolean = await page.$$eval('script', tags =>
Array.from(tags).some(tag => tag.getAttribute('type') === 'module')
)
expect(hasTag).toBe(true)
})
.end()
})
test('add style tag', async () => {
expect.assertions(1)
const instance = new Rize()
await instance
.addStyleTag('content', 'div { font-size: 5px; }')
.execute(async (browser, page) => {
const search = await page.evaluate(() => {
const elements = Array.from(document.children)
return elements.some(el => el.textContent === 'div { font-size: 5px; }')
})
expect(search).toBe(true)
})
.end()
}) | the_stack |
import {
absVal,
constOf,
max,
ops,
sub,
mul,
min,
ifCond,
eq,
add,
div,
neg,
squared,
gt,
sqrt,
} from "engine/Autodiff";
import * as BBox from "engine/BBox";
import { randFloat } from "utils/Util";
import { Properties, Shape } from "types/shape";
import { Value } from "types/value";
import { IFloatV, IVectorV, IColorV } from "types/value";
import { Path } from "types/style";
import { isPt2, Pt2, VarAD } from "types/ad";
//#region shapedef helpers and samplers
/** @ignore */
type PropContents = Value<number>["contents"];
/** @ignore */
type ConstSampler = (type: PropType, value: PropContents) => Sampler;
type Range = [number, number];
// NOTE: I moved `canvasSize` here from Canvas.tsx, which re-exports it, to avoid a circular import in `Style`.
// export const canvasSize: [number, number] = [800, 700];
// export const canvasXRange: Range = [-canvasSize[0] / 2, canvasSize[0] / 2];
// export const canvasYRange: Range = [-canvasSize[1] / 2, canvasSize[1] / 2];
interface ICanvas {
width: number;
height: number;
size: [number, number];
xRange: Range;
yRange: Range;
}
export type Canvas = ICanvas;
/** Generate a single string based on a path to a shape */
export const getShapeName = (p: Path): string => {
if (p.tag === "FieldPath" || p.tag === "PropertyPath") {
const { name, field } = p;
return `${name.contents.value}.${field.value}`;
} else {
throw new Error("Can only derive shape name from field or property path.");
}
};
/**
* Sort shapes given a list of ordered shape names.
*
* @param shapes unsorted shapes
* @param ordering global ordering of shapes
*/
export const sortShapes = (shapes: Shape[], ordering: string[]): Shape[] => {
return ordering.map(
(name) =>
// COMBAK: Deal with nonexistent shapes
shapes.find(
({ properties }) => properties.name.contents === name
) as Shape
); // assumes that all names are unique
};
/**
* Checks if a `Text` shape has non-empty content
*
* @param shape a `Text` shape
*/
export const notEmptyLabel = (shape: Shape): boolean => {
const { shapeType, properties } = shape;
return shapeType === "Text" ? !(properties.string.contents === "") : true;
};
const sampleFloatIn = (min: number, max: number): IFloatV<number> => ({
tag: "FloatV",
contents: randFloat(min, max),
});
const vectorSampler: Sampler = (canvas): IVectorV<number> => ({
tag: "VectorV",
contents: [randFloat(...canvas.xRange), randFloat(...canvas.yRange)],
});
const widthSampler: Sampler = (canvas): IFloatV<number> => ({
tag: "FloatV",
contents: randFloat(3, canvas.width / 6),
});
const zeroFloat: Sampler = (_canvas): IFloatV<number> => ({
tag: "FloatV",
contents: 0.0,
});
const pathLengthSampler: Sampler = (_canvas): IFloatV<number> => ({
tag: "FloatV",
contents: 1.0,
});
const heightSampler: Sampler = (canvas): IFloatV<number> => ({
tag: "FloatV",
contents: randFloat(3, canvas.height / 6),
});
const strokeSampler: Sampler = (_canvas): IFloatV<number> => ({
tag: "FloatV",
contents: randFloat(0.5, 3),
});
const colorSampler: Sampler = (_canvas): IColorV<number> => {
const [min, max] = [0.1, 0.9];
return {
tag: "ColorV",
contents: {
tag: "RGBA",
contents: [
randFloat(min, max),
randFloat(min, max),
randFloat(min, max),
0.5,
],
},
};
};
export const constValue: ConstSampler = (
tag: PropType,
contents: PropContents
) => (_canvas) =>
({
tag,
contents,
} as Value<number>);
const black: IColorV<number> = {
tag: "ColorV",
contents: {
tag: "RGBA",
contents: [0, 0, 0, 1.0],
},
};
const noPaint: IColorV<number> = {
tag: "ColorV",
contents: {
tag: "NONE",
},
};
//#endregion
//#region shapedefs
export type ShapeDef = IShapeDef;
// type HasTag<T, N> = T extends { tag: N } ? T : never;
export type PropType = Value<number>["tag"];
export type IPropModel = { [k: string]: [PropType, Sampler] };
export interface IShapeDef {
shapeType: string;
properties: IPropModel;
positionalProps?: string[];
bbox: (s: Properties<VarAD>) => BBox.BBox;
}
export type Sampler = (canvas: Canvas) => Value<number>;
const bboxFromPoints = (points: Pt2[]): BBox.BBox => {
const minCorner = points.reduce((corner: Pt2, point: Pt2) => [
min(corner[0], point[0]),
min(corner[1], point[1]),
]);
const maxCorner = points.reduce((corner: Pt2, point: Pt2) => [
max(corner[0], point[0]),
max(corner[1], point[1]),
]);
const w = sub(maxCorner[0], minCorner[0]);
const h = sub(maxCorner[1], minCorner[1]);
const center = ops.vdiv(ops.vadd(minCorner, maxCorner), constOf(2));
if (!isPt2(center)) {
throw new Error("ops.vadd and ops.vdiv did not preserve dimension");
}
return BBox.bbox(w, h, center);
};
const bboxFromRotatedRect = (
center: Pt2,
w: VarAD,
h: VarAD,
clockwise: VarAD
): BBox.BBox => {
const counterclockwise = neg(clockwise);
const top = ops.vrot([w, constOf(0)], counterclockwise);
const left = ops.vrot([constOf(0), neg(h)], counterclockwise);
const topLeft: Pt2 = [
sub(center[0], div(w, constOf(2))),
add(center[1], div(h, constOf(2))),
];
const topRight = ops.vadd(topLeft, top);
const botLeft = ops.vadd(topLeft, left);
const botRight = ops.vadd(topRight, left);
if (!(isPt2(topRight) && isPt2(botLeft) && isPt2(botRight))) {
throw new Error("ops.vadd did not preserve dimension");
}
return bboxFromPoints([topLeft, topRight, botLeft, botRight]);
};
const bboxFromCircle = ({ r, center }: Properties<VarAD>): BBox.BBox => {
// https://github.com/penrose/penrose/issues/701
if (r.tag !== "FloatV") {
throw new Error(`bboxFromCircle expected r to be FloatV, but got ${r.tag}`);
}
if (center.tag !== "VectorV") {
throw new Error(
`bboxFromCircle expected center to be VectorV, but got ${center.tag}`
);
}
if (!isPt2(center.contents)) {
throw new Error(
`bboxFromCircle expected center to be Pt2, but got length ${center.contents.length}`
);
}
const diameter = mul(constOf(2), r.contents);
return BBox.bbox(diameter, diameter, center.contents);
};
export const circleDef: ShapeDef = {
shapeType: "Circle",
properties: {
center: ["VectorV", vectorSampler],
r: ["FloatV", widthSampler],
pathLength: ["FloatV", pathLengthSampler], // part of svg spec
strokeWidth: ["FloatV", strokeSampler],
style: ["StrV", constValue("StrV", "filled")],
strokeStyle: ["StrV", constValue("StrV", "solid")],
strokeColor: ["ColorV", () => noPaint],
color: ["ColorV", colorSampler],
name: ["StrV", constValue("StrV", "defaultCircle")],
},
positionalProps: ["center"],
bbox: bboxFromCircle,
};
const bboxFromEllipse = ({ rx, ry, center }: Properties<VarAD>): BBox.BBox => {
// https://github.com/penrose/penrose/issues/701
if (rx.tag !== "FloatV") {
throw new Error(
`bboxFromEllipse expected rx to be FloatV, but got ${rx.tag}`
);
}
if (ry.tag !== "FloatV") {
throw new Error(
`bboxFromEllipse expected ry to be FloatV, but got ${ry.tag}`
);
}
if (center.tag !== "VectorV") {
throw new Error(
`bboxFromEllipse expected center to be VectorV, but got ${center.tag}`
);
}
if (!isPt2(center.contents)) {
throw new Error(
`bboxFromEllipse expected center to be Pt2, but got length ${center.contents.length}`
);
}
const dx = mul(constOf(2), rx.contents);
const dy = mul(constOf(2), ry.contents);
return BBox.bbox(dx, dy, center.contents);
};
export const ellipseDef: ShapeDef = {
shapeType: "Ellipse",
properties: {
center: ["VectorV", vectorSampler],
rx: ["FloatV", widthSampler],
ry: ["FloatV", heightSampler],
pathLength: ["FloatV", pathLengthSampler], // part of svg spec
strokeWidth: ["FloatV", strokeSampler],
style: ["StrV", constValue("StrV", "filled")],
strokeStyle: ["StrV", constValue("StrV", "solid")],
strokeColor: ["ColorV", () => noPaint],
strokeDashArray: ["StrV", constValue("StrV", "")],
color: ["ColorV", colorSampler],
name: ["StrV", constValue("StrV", "defaultCircle")],
},
positionalProps: ["center"],
bbox: bboxFromEllipse,
};
const bboxFromRect = ({ w, h, center }: Properties<VarAD>): BBox.BBox => {
// https://github.com/penrose/penrose/issues/701
if (w.tag !== "FloatV") {
throw new Error(`bboxFromRect expected w to be FloatV, but got ${w.tag}`);
}
if (h.tag !== "FloatV") {
throw new Error(`bboxFromRect expected h to be FloatV, but got ${h.tag}`);
}
if (center.tag !== "VectorV") {
throw new Error(
`bboxFromRect expected center to be VectorV, but got ${center.tag}`
);
}
if (!isPt2(center.contents)) {
throw new Error(
`bboxFromRect expected center to be Pt2, but got length ${center.contents.length}`
);
}
// rx just rounds the corners, doesn't change the bbox
return BBox.bbox(w.contents, h.contents, center.contents);
};
export const rectDef: ShapeDef = {
shapeType: "Rectangle",
properties: {
center: ["VectorV", vectorSampler],
w: ["FloatV", widthSampler],
h: ["FloatV", heightSampler],
rx: ["FloatV", zeroFloat],
strokeWidth: ["FloatV", strokeSampler],
style: ["StrV", constValue("StrV", "filled")],
strokeStyle: ["StrV", constValue("StrV", "solid")],
strokeColor: ["ColorV", () => noPaint],
strokeDashArray: ["StrV", constValue("StrV", "")],
color: ["ColorV", colorSampler],
name: ["StrV", constValue("StrV", "defaultRect")],
},
positionalProps: ["center"],
bbox: bboxFromRect,
};
const bboxFromCallout = ({
anchor,
center,
w,
h,
padding,
}: Properties<VarAD>): BBox.BBox => {
// https://github.com/penrose/penrose/issues/701
if (anchor.tag !== "VectorV") {
throw new Error(
`bboxFromCallout expected anchor to be VectorV, but got ${anchor.tag}`
);
}
if (!isPt2(anchor.contents)) {
throw new Error(
`bboxFromCallout expected anchor to be Pt2, but got length ${anchor.contents.length}`
);
}
if (center.tag !== "VectorV") {
throw new Error(
`bboxFromCallout expected center to be VectorV, but got ${center.tag}`
);
}
if (!isPt2(center.contents)) {
throw new Error(
`bboxFromCallout expected center to be Pt2, but got length ${center.contents.length}`
);
}
if (w.tag !== "FloatV") {
throw new Error(
`bboxFromCallout expected w to be FloatV, but got ${w.tag}`
);
}
if (h.tag !== "FloatV") {
throw new Error(
`bboxFromCallout expected h to be FloatV, but got ${h.tag}`
);
}
if (padding.tag !== "FloatV") {
throw new Error(
`bboxFromCallout expected padding to be FloatV, but got ${padding.tag}`
);
}
// below adapted from makeCallout function in renderer/Callout.ts
const pad = ifCond(
eq(padding.contents, constOf(0)),
constOf(30),
padding.contents
);
const dx = div(add(w.contents, pad), constOf(2));
const dy = div(add(h.contents, pad), constOf(2));
const [x, y] = center.contents;
const [anchorX, anchorY] = anchor.contents;
const minX = min(sub(x, dx), anchorX);
const maxX = max(add(x, dx), anchorX);
const minY = min(sub(y, dy), anchorY);
const maxY = max(add(y, dy), anchorY);
const width = sub(maxX, minX);
const height = sub(maxY, minY);
const cx = div(add(minX, maxX), constOf(2));
const cy = div(add(minY, maxY), constOf(2));
return BBox.bbox(width, height, [cx, cy]);
};
export const calloutDef: ShapeDef = {
shapeType: "Callout",
properties: {
anchor: ["VectorV", vectorSampler],
center: ["VectorV", vectorSampler],
w: ["FloatV", widthSampler],
h: ["FloatV", heightSampler],
padding: ["FloatV", zeroFloat], // padding around the contents of the callout box
rx: ["FloatV", zeroFloat], // currently unused
strokeWidth: ["FloatV", strokeSampler],
style: ["StrV", constValue("StrV", "filled")],
strokeStyle: ["StrV", constValue("StrV", "solid")],
strokeColor: ["ColorV", () => noPaint],
strokeDashArray: ["StrV", constValue("StrV", "")],
color: ["ColorV", colorSampler],
name: ["StrV", constValue("StrV", "defaultCallout")],
},
bbox: bboxFromCallout,
};
const bboxFromPolygon = ({ points, scale }: Properties<VarAD>): BBox.BBox => {
// https://github.com/penrose/penrose/issues/701
// seems like this should be PtListV but apparently it isn't
if (points.tag !== "LListV") {
throw new Error(
`bboxFromPolygon expected points to be LListV, but got ${points.tag}`
);
}
if (scale.tag !== "FloatV") {
throw new Error(
`bboxFromPolygon expected scale to be FloatV, but got ${scale.tag}`
);
}
return bboxFromPoints(
points.contents.map((point) => {
const pt = ops.vmul(scale.contents, point);
if (isPt2(pt)) {
return pt;
} else {
throw new Error(
`bboxFromPolygon expected each point to be Pt2, but got length ${point.length}`
);
}
})
);
};
export const polygonDef: ShapeDef = {
shapeType: "Polygon",
properties: {
strokeWidth: ["FloatV", strokeSampler],
style: ["StrV", constValue("StrV", "filled")],
strokeStyle: ["StrV", constValue("StrV", "solid")],
strokeColor: ["ColorV", () => noPaint],
color: ["ColorV", colorSampler],
center: ["VectorV", vectorSampler],
scale: ["FloatV", constValue("FloatV", 1)],
name: ["StrV", constValue("StrV", "defaultPolygon")],
points: [
"PtListV",
constValue("PtListV", [
[0, 0],
[0, 10],
[10, 0],
]),
],
},
positionalProps: ["center"],
bbox: bboxFromPolygon, // https://github.com/penrose/penrose/issues/709
};
export const freeformPolygonDef: ShapeDef = {
shapeType: "FreeformPolygon",
properties: {
strokeWidth: ["FloatV", strokeSampler],
style: ["StrV", constValue("StrV", "filled")],
strokeStyle: ["StrV", constValue("StrV", "solid")],
strokeColor: ["ColorV", () => noPaint],
color: ["ColorV", colorSampler],
name: ["StrV", constValue("StrV", "defaultFreeformPolygon")],
scale: ["FloatV", constValue("FloatV", 1)],
points: [
"PtListV",
constValue("PtListV", [
[0, 0],
[0, 10],
[10, 0],
]),
],
},
positionalProps: [],
bbox: bboxFromPolygon,
};
const DEFAULT_PATHSTR = `M 10,30
A 20,20 0,0,1 50,30
A 20,20 0,0,1 90,30
Q 90,60 50,90
Q 10,60 10,30 z`;
const bboxFromRectlike = ({
center,
w,
h,
rotation,
}: Properties<VarAD>): BBox.BBox => {
// https://github.com/penrose/penrose/issues/701
if (center.tag !== "VectorV") {
throw new Error(
`bboxFromRectlike expected center to be VectorV, but got ${center.tag}`
);
}
if (!isPt2(center.contents)) {
throw new Error(
`bboxFromRectlike expected center to be Pt2, but got length ${center.contents.length}`
);
}
if (w.tag !== "FloatV") {
throw new Error(
`bboxFromRectlike expected w to be FloatV, but got ${w.tag}`
);
}
if (h.tag !== "FloatV") {
throw new Error(
`bboxFromRectlike expected h to be FloatV, but got ${h.tag}`
);
}
if (rotation.tag !== "FloatV") {
throw new Error(
`bboxFromRectlike expected rotation to be FloatV, but got ${rotation.tag}`
);
}
return bboxFromRotatedRect(
center.contents,
w.contents,
h.contents,
rotation.contents
);
};
export const pathStringDef: ShapeDef = {
shapeType: "PathString",
properties: {
center: ["VectorV", vectorSampler],
w: ["FloatV", widthSampler],
h: ["FloatV", heightSampler],
rotation: ["FloatV", constValue("FloatV", 0)],
opacity: ["FloatV", constValue("FloatV", 1.0)],
strokeWidth: ["FloatV", strokeSampler],
strokeStyle: ["StrV", constValue("StrV", "solid")],
strokeColor: ["ColorV", colorSampler],
color: ["ColorV", () => noPaint],
name: ["StrV", constValue("StrV", "defaultPolygon")],
data: ["StrV", constValue("StrV", DEFAULT_PATHSTR)],
viewBox: ["StrV", constValue("StrV", "0 0 100 100")],
},
positionalProps: ["center"],
bbox: bboxFromRectlike,
};
export const polylineDef: ShapeDef = {
shapeType: "Polyline",
properties: {
strokeWidth: ["FloatV", strokeSampler],
center: ["VectorV", vectorSampler],
scale: ["FloatV", constValue("FloatV", 1)],
style: ["StrV", constValue("StrV", "filled")],
strokeStyle: ["StrV", constValue("StrV", "solid")],
strokeColor: ["ColorV", colorSampler],
color: ["ColorV", colorSampler],
name: ["StrV", constValue("StrV", "defaultPolygon")],
points: [
"PtListV",
constValue("PtListV", [
[0, 0],
[0, 10],
[10, 0],
]),
],
},
positionalProps: ["center"],
bbox: bboxFromPolygon, // https://github.com/penrose/penrose/issues/709
};
export const imageDef: ShapeDef = {
shapeType: "Image",
properties: {
center: ["VectorV", vectorSampler],
w: ["FloatV", widthSampler],
h: ["FloatV", heightSampler],
rotation: ["FloatV", constValue("FloatV", 0)],
opacity: ["FloatV", constValue("FloatV", 1.0)],
style: ["StrV", constValue("StrV", "filled")],
stroke: ["StrV", constValue("StrV", "none")],
path: ["StrV", constValue("StrV", "missing image path")],
name: ["StrV", constValue("StrV", "defaultImage")],
},
positionalProps: ["center"],
bbox: bboxFromRectlike, // https://github.com/penrose/penrose/issues/712
};
const bboxFromSquare = ({
center,
side,
rotation,
}: Properties<VarAD>): BBox.BBox => {
// https://github.com/penrose/penrose/issues/701
if (center.tag !== "VectorV") {
throw new Error(
`bboxFromSquare expected center to be VectorV, but got ${center.tag}`
);
}
if (!isPt2(center.contents)) {
throw new Error(
`bboxFromSquare expected center to be Pt2, but got length ${center.contents.length}`
);
}
if (side.tag !== "FloatV") {
throw new Error(
`bboxFromSquare expected side to be FloatV, but got ${side.tag}`
);
}
if (rotation.tag !== "FloatV") {
throw new Error(
`bboxFromSquare expected rotation to be FloatV, but got ${rotation.tag}`
);
}
// rx rounds the corners, so we could use it to give a smaller bbox if both
// that and rotation are nonzero, but we don't account for that here
return bboxFromRotatedRect(
center.contents,
side.contents,
side.contents,
rotation.contents
);
};
export const squareDef: ShapeDef = {
shapeType: "Square",
properties: {
center: ["VectorV", vectorSampler],
side: ["FloatV", widthSampler],
rotation: ["FloatV", constValue("FloatV", 0)],
style: ["StrV", constValue("StrV", "none")],
rx: ["FloatV", zeroFloat],
strokeWidth: ["FloatV", strokeSampler],
strokeStyle: ["StrV", constValue("StrV", "solid")],
strokeColor: ["ColorV", () => noPaint],
strokeDashArray: ["StrV", constValue("StrV", "")],
color: ["ColorV", colorSampler],
name: ["StrV", constValue("StrV", "defaultSquare")],
},
positionalProps: ["center"],
bbox: bboxFromSquare,
};
export const textDef: ShapeDef = {
shapeType: "Text",
properties: {
center: ["VectorV", vectorSampler],
w: ["FloatV", constValue("FloatV", 0)],
h: ["FloatV", constValue("FloatV", 0)],
fontSize: ["StrV", constValue("StrV", "12pt")],
rotation: ["FloatV", constValue("FloatV", 0)],
style: ["StrV", constValue("StrV", "none")],
stroke: ["StrV", constValue("StrV", "none")],
color: ["ColorV", () => black],
name: ["StrV", constValue("StrV", "defaultText")],
string: ["StrV", constValue("StrV", "defaultLabelText")],
// HACK: typechecking is not passing due to Value mismatch. Not sure why
},
positionalProps: ["center"],
bbox: bboxFromRectlike, // assumes w and h correspond to string
};
const bboxFromLinelike = ({
start,
end,
thickness,
}: Properties<VarAD>): BBox.BBox => {
// https://github.com/penrose/penrose/issues/701
if (start.tag !== "VectorV") {
throw new Error(
`bboxFromLinelike expected start to be VectorV, but got ${start.tag}`
);
}
if (!isPt2(start.contents)) {
throw new Error(
`bboxFromLinelike expected start to be Pt2, but got length ${start.contents.length}`
);
}
if (end.tag !== "VectorV") {
throw new Error(
`bboxFromLinelike expected end to be VectorV, but got ${end.tag}`
);
}
if (!isPt2(end.contents)) {
throw new Error(
`bboxFromLinelike expected end to be Pt2, but got length ${end.contents.length}`
);
}
if (thickness.tag !== "FloatV") {
throw new Error(
`bboxFromLinelike expected thickness to be FloatV, but got ${thickness.tag}`
);
}
const d = ops.vmul(
div(thickness.contents, constOf(2)),
ops.rot90(ops.vnormalize(ops.vsub(end.contents, start.contents)))
);
return bboxFromPoints(
[
ops.vadd(start.contents, d),
ops.vsub(start.contents, d),
ops.vadd(end.contents, d),
ops.vsub(end.contents, d),
].map((point) => {
if (isPt2(point)) {
return point;
} else {
throw new Error("ops did not preserve dimension");
}
})
);
};
export const lineDef: ShapeDef = {
shapeType: "Line",
properties: {
start: ["VectorV", vectorSampler],
end: ["VectorV", vectorSampler],
thickness: ["FloatV", () => sampleFloatIn(5, 15)],
leftArrowhead: ["BoolV", constValue("BoolV", false)],
rightArrowhead: ["BoolV", constValue("BoolV", false)],
arrowheadStyle: ["StrV", constValue("StrV", "arrowhead-2")],
arrowheadSize: ["FloatV", constValue("FloatV", 1.0)],
color: ["ColorV", colorSampler],
style: ["StrV", constValue("StrV", "solid")],
stroke: ["StrV", constValue("StrV", "none")],
strokeDashArray: ["StrV", constValue("StrV", "")],
name: ["StrV", constValue("StrV", "defaultLine")],
},
positionalProps: ["start", "end"],
bbox: bboxFromLinelike,
};
export const arrowDef: ShapeDef = {
shapeType: "Arrow",
properties: {
start: ["VectorV", vectorSampler],
end: ["VectorV", vectorSampler],
thickness: ["FloatV", () => sampleFloatIn(5, 15)],
arrowheadStyle: ["StrV", constValue("StrV", "arrowhead-2")],
arrowheadSize: ["FloatV", constValue("FloatV", 1.0)],
style: ["StrV", constValue("StrV", "solid")],
color: ["ColorV", colorSampler],
name: ["StrV", constValue("StrV", "defaultArrow")],
strokeDashArray: ["StrV", constValue("StrV", "")],
},
positionalProps: ["start", "end"],
bbox: bboxFromLinelike,
};
const bboxFromPath = ({ pathData }: Properties<VarAD>): BBox.BBox => {
// https://github.com/penrose/penrose/issues/701
if (pathData.tag !== "PathDataV") {
throw new Error(
`bboxFromPath expected pathData to be PathDataV, but got ${pathData.tag}`
);
}
// assuming path and polyline properties are not used
const p = pathData.contents;
if (p.length < 1) {
throw new Error("bboxFromPath expected pathData to be nonempty");
}
if (p[0].cmd !== "M") {
throw new Error(
`bboxFromPath expected first command to be M, but got ${p[0].cmd}`
);
}
const first = p[0].contents[0];
if (first.tag !== "CoordV") {
throw new Error(
`bboxFromPath expected first command subpath to be CoordV, but got ${first.tag}`
);
}
if (!isPt2(first.contents)) {
throw new Error(
`bboxFromPath expected cursor to be Pt2, but got length ${first.contents.length}`
);
}
let cursor: Pt2 = first.contents;
let control: Pt2 = cursor; // used by T and S
const points: Pt2[] = [];
for (const { cmd, contents } of p) {
const next = cmd === "Z" ? first : contents[contents.length - 1];
if (next.tag !== "CoordV") {
throw new Error("bboxFromPath expected next cursor to be CoordV");
}
if (!isPt2(next.contents)) {
throw new Error("bboxFromPath expected next cursor to be Pt2");
}
let nextControl = next.contents;
if (cmd === "M") {
// cursor is set after this if/else sequence; nothing to do here
} else if (cmd === "Z" || cmd === "L") {
points.push(cursor, next.contents);
} else if (cmd === "Q") {
const cp = contents[0].contents;
if (!isPt2(cp)) {
throw new Error("bboxFromPath expected Q cp to be Pt2");
}
points.push(cursor, cp, next.contents);
nextControl = cp;
} else if (cmd === "C") {
const cp1 = contents[0].contents;
const cp2 = contents[1].contents;
if (!isPt2(cp1)) {
throw new Error("bboxFromPath expected C cp1 to be Pt2");
}
if (!isPt2(cp2)) {
throw new Error("bboxFromPath expected C cp2 to be Pt2");
}
points.push(cursor, cp1, cp2, next.contents);
nextControl = cp2;
} else if (cmd === "T") {
const cp = ops.vadd(cursor, ops.vsub(cursor, control));
if (!isPt2(cp)) {
throw new Error("ops did not preserve dimension");
}
points.push(cursor, cp, next.contents);
nextControl = cp;
} else if (cmd === "S") {
const cp1 = ops.vadd(cursor, ops.vsub(cursor, control));
const cp2 = contents[0].contents;
if (!isPt2(cp1)) {
throw new Error("ops did not preserve dimension");
}
if (!isPt2(cp2)) {
throw new Error("bboxFromPath expected S cp2 to be Pt2");
}
points.push(cursor, cp1, cp2, next.contents);
nextControl = cp2;
} else if (cmd === "A") {
const [rxRaw, ryRaw, rotation, largeArc, sweep] = contents[0].contents;
const phi = neg(rotation); // phi is counterclockwise
// https://www.w3.org/TR/SVG/implnote.html#ArcCorrectionOutOfRangeRadii
// note: we assume neither rxRaw nor ryRaw are zero; technically in that
// case we should just points.push(cursor, next.contents) and then not do
// any of these other calculations
// eq. 6.1
const rxPos = absVal(rxRaw);
const ryPos = absVal(ryRaw);
// https://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
// eq. 5.1
const [x1Prime, y1Prime] = ops.vrot(
ops.vdiv(ops.vsub(cursor, next.contents), constOf(2)),
neg(phi)
);
// eq. 6.2
const lambda = add(
squared(div(x1Prime, rxPos)),
squared(div(y1Prime, ryPos))
);
// eq. 6.3
const replace = gt(lambda, constOf(1));
const rx = ifCond(replace, mul(sqrt(lambda), rxPos), rxPos);
const ry = ifCond(replace, mul(sqrt(lambda), ryPos), ryPos);
// eq. 5.2
const cPrime = ops.vmul(
mul(
// according to the linked doc it seems like this should be the other
// way around, but Penrose seems to do it this way instead
ifCond(eq(largeArc, sweep), constOf(1), constOf(-1)),
sqrt(
// mathematically this radicand can never be negative, but when
// Lambda is greater than 1, the radicand becomes very close to 0
// and sometimes negative, so we manually clamp it to a very small
// positive value in that case, because sqrt internally calls div on
// the radicand, and some testing shows that passing values smaller
// than this magic number to sqrt causes that internal call to div
// to throw an error
max(
constOf(1e-18),
div(
sub(
sub(squared(mul(rx, ry)), squared(mul(rx, y1Prime))),
squared(mul(ry, x1Prime))
),
add(squared(mul(rx, y1Prime)), squared(mul(ry, x1Prime)))
)
)
)
),
[div(mul(rx, y1Prime), ry), neg(div(mul(ry, x1Prime), rx))]
);
// eq. 5.3
const [cx, cy] = ops.vadd(
ops.vrot(cPrime, phi),
ops.vdiv(ops.vadd(cursor, next.contents), constOf(2))
);
// very crude approach: we know that the ellipse is contained within a
// concentric circle whose diameter is the major axis, so just use the
// bounding box of that circle
const r = max(rx, ry);
points.push([sub(cx, r), sub(cy, r)], [add(cx, r), add(cy, r)]);
// ideally we would instead do something more sophisticated, like this:
// https://stackoverflow.com/a/65441277
} else {
// only commands used in render/PathBuilder.ts are supported; in
// particular, H and V are not supported, nor are any lowercase commands
throw new Error(`bboxFromPath got unsupported cmd ${cmd}`);
}
cursor = next.contents;
control = nextControl;
}
return bboxFromPoints(points);
};
export const curveDef: ShapeDef = {
shapeType: "Path",
properties: {
path: ["PtListV", constValue("PtListV", [])],
polyline: ["PtListV", constValue("PtListV", [])],
pathData: ["PathDataV", constValue("PathDataV", [])],
strokeWidth: ["FloatV", strokeSampler],
style: ["StrV", constValue("StrV", "solid")],
strokeDashArray: ["StrV", constValue("StrV", "")],
effect: ["StrV", constValue("StrV", "none")],
color: ["ColorV", colorSampler], // should be "strokeColor"
fill: ["ColorV", () => noPaint], // should be "color"
leftArrowhead: ["BoolV", constValue("BoolV", false)],
rightArrowhead: ["BoolV", constValue("BoolV", false)],
arrowheadStyle: ["StrV", constValue("StrV", "arrowhead-2")],
arrowheadSize: ["FloatV", constValue("FloatV", 1.0)],
name: ["StrV", constValue("StrV", "defaultCurve")],
},
bbox: bboxFromPath,
};
/**
* A registry of all types of shape definitions in the Penrose system.
*/
export const shapedefs: ShapeDef[] = [
circleDef,
ellipseDef,
textDef,
rectDef,
calloutDef,
polygonDef,
freeformPolygonDef,
polylineDef,
pathStringDef,
squareDef,
curveDef,
imageDef,
lineDef,
arrowDef,
];
export const positionalProps = (type: string): string[] | undefined => {
const res = shapedefs.find(({ shapeType }: ShapeDef) => shapeType === type);
if (!res) return undefined;
return res.positionalProps;
};
export const findDef = (type: string): ShapeDef => {
const res = shapedefs.find(({ shapeType }: ShapeDef) => shapeType === type);
if (res) return res;
else throw new Error(`${type} is not a valid shape definition.`);
};
//#endregion
//#region Shape kind queries
// Kinds of shapes
/**
* Takes a `shapeType`, returns whether it's rectlike. (excluding squares)
*/
export const isRectlike = (shapeType: string): boolean => {
return (
shapeType == "Rectangle" ||
shapeType == "Square" ||
shapeType == "Image" ||
shapeType == "Text"
);
};
/**
* Takes a `shapeType`, returns whether it's linelike.
*/
export const isLinelike = (shapeType: string): boolean => {
return shapeType == "Line" || shapeType == "Arrow";
};
//#endregion | the_stack |
import Modification from "../../modification";
import * as Shift from 'shift-ast';
import { traverse } from '../../helpers/traverse';
import TraversalHelper from "../../helpers/traversalHelper";
import Scope from "./scope";
import ProxyFunction from "./proxyFunction";
import Graph from '../../graph/graph';
import Node from '../../graph/node';
import Edge from '../../graph/edge';
export default class ProxyRemover extends Modification {
private readonly scopeTypes = new Set(['Block', 'FunctionBody']);
private readonly proxyExpressionTypes = new Set(['CallExpression', 'BinaryExpression', 'UnaryExpression', 'ComputedMemberExpression', 'IdentifierExpression']);
private shouldRemoveProxyFunctions: boolean;
private globalScope: Scope;
private proxyFunctions: ProxyFunction[];
private proxyFunctionNames: Set<string>;
private cyclicProxyFunctionIds: Set<string>;
private graph: Graph;
/**
* Creates a new modification.
* @param ast The AST.
* @param removeProxyFunctions Whether the functions should be removed.
*/
constructor(ast: Shift.Script, removeProxyFunctions: boolean) {
super('Remove Proxy Functions', ast);
this.shouldRemoveProxyFunctions = removeProxyFunctions;
this.globalScope = new Scope(this.ast);
this.proxyFunctions = [];
this.proxyFunctionNames = new Set<string>();
this.cyclicProxyFunctionIds = new Set<string>();
this.graph = new Graph();
}
/**
* Executes the modification.
*/
execute(): void {
this.findProxyFunctions();
this.findAliases();
this.findCycles();
this.replaceProxyFunctionUsages(this.ast, this.globalScope);
if (this.shouldRemoveProxyFunctions) {
this.removeProxyFunctions(this.globalScope);
}
}
/**
* Finds all proxy functions and records them in the according scope.
*/
private findProxyFunctions(): void {
const self = this;
let scope = this.globalScope;
traverse(this.ast, {
enter(node: Shift.Node, parent: Shift.Node) {
if (self.scopeTypes.has(node.type)) {
scope = new Scope(node, scope);
}
let proxyFunction: ProxyFunction;
if (self.isProxyFunctionDeclaration(node)) {
const name = (node as any).name.name;
const params = (node as any).params.items;
const expression = (node as any).body.statements[0].expression;
proxyFunction = new ProxyFunction(node, parent, scope, name, params, expression);
}
else if (self.isProxyFunctionExpressionDeclaration(node)) {
const name = (node as any).binding.name;
const params = (node as any).init.params.items;
const expression = (node as any).init.body.statements[0].expression;
proxyFunction = new ProxyFunction(node, parent, scope, name, params, expression);
} else {
return;
}
scope.addProxyFunction(proxyFunction);
self.proxyFunctions.push(proxyFunction);
self.graph.addNode(new Node(proxyFunction.id));
if (!self.proxyFunctionNames.has(proxyFunction.name)) {
self.proxyFunctionNames.add(proxyFunction.name);
}
},
leave(node: Shift.Node) {
if (node == scope.node && scope.parent) {
scope = scope.parent;
}
}
});
}
/**
* Finds aliases for proxy functions.
*/
private findAliases(): void {
const self = this;
let scope = this.globalScope;
traverse(this.ast, {
enter(node: Shift.Node, parent: Shift.Node) {
if (self.scopeTypes.has(node.type)) {
scope = scope.children.get(node) as Scope;
}
if (self.isVariableReassignment(node)) {
const name = (node as any).init.name;
if (self.proxyFunctionNames.has(name)) {
const newName = (node as any).binding.name;
const proxyFunction = scope.findProxyFunction(name);
if (proxyFunction) {
scope.addAlias(proxyFunction, newName);
TraversalHelper.removeNode(parent, node);
if (!self.proxyFunctionNames.has(newName)) {
self.proxyFunctionNames.add(newName);
}
}
}
}
},
leave(node: Shift.Node) {
if (node == scope.node && scope.parent) {
scope = scope.parent;
}
}
});
}
/**
* Finds cycles in the proxy function graph and excludes those
* proxy functions from replacing.
*/
private findCycles(): void {
const self = this;
for (const proxyFunction of this.proxyFunctions) {
const thisNode = this.graph.findNode(proxyFunction.id) as Node;
let scope = proxyFunction.scope;
traverse(proxyFunction.expression, {
enter(node: Shift.Node) {
if (self.scopeTypes.has(node.type)) {
scope = scope.children.get(node) as Scope;
}
if (self.isFunctionCall(node)) {
const calleeName = (node as any).callee.name;
if (self.proxyFunctionNames.has(calleeName)) {
const otherProxyFunction = scope.findProxyFunction(calleeName);
if (otherProxyFunction) {
const otherNode = self.graph.findNode(otherProxyFunction.id) as Node;
if (!self.graph.hasEdge(`${thisNode.id} -> ${otherNode.id}`)) {
self.graph.addEdge(new Edge(thisNode, otherNode));
}
}
}
}
},
leave(node: Shift.Node) {
if (node == scope.node && scope.parent) {
scope = scope.parent;
}
}
});
}
const seenNodes = new Set<Node>();
for (const node of this.graph.nodes) {
this.searchBranch(node, seenNodes);
}
}
/**
* Searches for cycles within a branch.
* @param node The current node.
* @param seenNodes The set of all previously seen nodes.
* @param branch The nodes in the current branch.
*/
private searchBranch(node: Node, seenNodes: Set<Node>, branch?: Set<Node>): void {
if (seenNodes.has(node)) {
return;
}
seenNodes.add(node);
branch ??= new Set<Node>();
branch.add(node);
for (const edge of node.outgoingEdges) {
const target = edge.target;
if (branch.has(target)) { // cycle found
this.cyclicProxyFunctionIds.add(target.id);
for (const node of branch) {
this.cyclicProxyFunctionIds.add(node.id);
}
} else {
this.searchBranch(target, seenNodes, branch);
}
}
}
/**
* Replaces all usages of proxy functions in a given node.
* @param node The node to replace usages in.
* @param startScope The scope of the node.
*/
private replaceProxyFunctionUsages(node: Shift.Node, scope: Scope): Shift.Node {
const self = this;
let replacedNode = node;
traverse(node, {
enter(node: Shift.Node, parent: Shift.Node) {
if (self.scopeTypes.has(node.type)) {
const sc = scope.children.get(node);
if (!sc) {
throw new Error(`Failed to find scope for node ${node.type}`);
}
scope = sc;
}
else if (self.isFunctionCall(node)) {
const name = (node as any).callee.name;
if (self.proxyFunctionNames.has(name)) {
const proxyFunction = scope.findProxyFunction(name);
if (proxyFunction && !self.cyclicProxyFunctionIds.has(proxyFunction.id)) {
const args = (node as any).arguments;
let replacement: Shift.Node = proxyFunction.getReplacement(args);
replacement = self.replaceProxyFunctionUsages(replacement, scope);
if (parent) {
TraversalHelper.replaceNode(parent, node, replacement);
} else {
replacedNode = replacement;
}
}
}
}
},
leave(node: Shift.Node) {
if (node == scope.node && scope.parent) {
scope = scope.parent;
}
}
});
return replacedNode;
}
/**
* Removes all proxy functions from a scope and its children.
* @param scope The scope to remove proxy functions from.
*/
private removeProxyFunctions(scope: Scope): void {
for (const [_, proxyFunction] of scope.proxyFunctions) {
if (!this.cyclicProxyFunctionIds.has(proxyFunction.id)) {
TraversalHelper.removeNode(proxyFunction.parentNode, proxyFunction.node);
}
}
for (const [_, child] of scope.children) {
this.removeProxyFunctions(child);
}
}
/**
* Returns whether a node is a proxy function declaration.
* @param node The AST node.
*/
private isProxyFunctionDeclaration(node: Shift.Node): boolean {
if (node.type == 'FunctionDeclaration' && node.body.statements.length == 1
&& node.body.statements[0].type == 'ReturnStatement' && node.body.statements[0].expression != null
&& (this.proxyExpressionTypes.has(node.body.statements[0].expression.type) || node.body.statements[0].expression.type.startsWith('Literal'))
&& node.params.items.find(p => p.type != 'BindingIdentifier') == undefined) {
const self = this;
let hasScopeNode = false;
traverse(node.body.statements[0].expression, {
enter(node: Shift.Node) {
if (self.scopeTypes.has(node.type)) {
hasScopeNode = true;
}
}
});
return !hasScopeNode;
} else {
return false;
}
}
/**
* Returns whether a node is a proxy function expression variable
* declaration.
* @param node The AST node.
*/
private isProxyFunctionExpressionDeclaration(node: Shift.Node): boolean {
if (node.type == 'VariableDeclarator' && node.binding.type == 'BindingIdentifier'
&& node.init != null && node.init.type == 'FunctionExpression'
&& node.init.body.statements.length == 1 && node.init.body.statements[0].type == 'ReturnStatement'
&& node.init.body.statements[0].expression != null
&& (this.proxyExpressionTypes.has(node.init.body.statements[0].expression.type) || node.init.body.statements[0].expression.type.startsWith('Literal'))) {
const self = this;
let hasScopeNode = false;
traverse(node.init.body.statements[0].expression, {
enter(node: Shift.Node) {
if (self.scopeTypes.has(node.type)) {
hasScopeNode = true;
}
}
});
return !hasScopeNode;
} else {
return false;
}
}
/**
* Returns whether a node is a variable reassignment.
* @param node The AST node.
* @returns Whether.
*/
private isVariableReassignment(node: Shift.Node): boolean {
return node.type == 'VariableDeclarator' && node.binding.type == 'BindingIdentifier'
&& node.init != null && node.init.type == 'IdentifierExpression';
}
/**
* Returns whether a node is a function call.
* @param node The AST node.
*/
private isFunctionCall(node: Shift.Node): boolean {
return node.type == 'CallExpression' && node.callee.type == 'IdentifierExpression';
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/instructionsMappers";
import * as Parameters from "../models/parameters";
import { BillingManagementClientContext } from "../billingManagementClientContext";
/** Class representing a Instructions. */
export class Instructions {
private readonly client: BillingManagementClientContext;
/**
* Create a Instructions.
* @param {BillingManagementClientContext} client Reference to the service client.
*/
constructor(client: BillingManagementClientContext) {
this.client = client;
}
/**
* Lists the instructions by billing profile id.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param [options] The optional parameters
* @returns Promise<Models.InstructionsListByBillingProfileResponse>
*/
listByBillingProfile(billingAccountName: string, billingProfileName: string, options?: msRest.RequestOptionsBase): Promise<Models.InstructionsListByBillingProfileResponse>;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param callback The callback
*/
listByBillingProfile(billingAccountName: string, billingProfileName: string, callback: msRest.ServiceCallback<Models.InstructionListResult>): void;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param options The optional parameters
* @param callback The callback
*/
listByBillingProfile(billingAccountName: string, billingProfileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.InstructionListResult>): void;
listByBillingProfile(billingAccountName: string, billingProfileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.InstructionListResult>, callback?: msRest.ServiceCallback<Models.InstructionListResult>): Promise<Models.InstructionsListByBillingProfileResponse> {
return this.client.sendOperationRequest(
{
billingAccountName,
billingProfileName,
options
},
listByBillingProfileOperationSpec,
callback) as Promise<Models.InstructionsListByBillingProfileResponse>;
}
/**
* Get the instruction by name. These are custom billing instructions and are only applicable for
* certain customers.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param instructionName Instruction Name.
* @param [options] The optional parameters
* @returns Promise<Models.InstructionsGetResponse>
*/
get(billingAccountName: string, billingProfileName: string, instructionName: string, options?: msRest.RequestOptionsBase): Promise<Models.InstructionsGetResponse>;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param instructionName Instruction Name.
* @param callback The callback
*/
get(billingAccountName: string, billingProfileName: string, instructionName: string, callback: msRest.ServiceCallback<Models.Instruction>): void;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param instructionName Instruction Name.
* @param options The optional parameters
* @param callback The callback
*/
get(billingAccountName: string, billingProfileName: string, instructionName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Instruction>): void;
get(billingAccountName: string, billingProfileName: string, instructionName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Instruction>, callback?: msRest.ServiceCallback<Models.Instruction>): Promise<Models.InstructionsGetResponse> {
return this.client.sendOperationRequest(
{
billingAccountName,
billingProfileName,
instructionName,
options
},
getOperationSpec,
callback) as Promise<Models.InstructionsGetResponse>;
}
/**
* Creates or updates an instruction. These are custom billing instructions and are only applicable
* for certain customers.
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param instructionName Instruction Name.
* @param parameters The new instruction.
* @param [options] The optional parameters
* @returns Promise<Models.InstructionsPutResponse>
*/
put(billingAccountName: string, billingProfileName: string, instructionName: string, parameters: Models.Instruction, options?: msRest.RequestOptionsBase): Promise<Models.InstructionsPutResponse>;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param instructionName Instruction Name.
* @param parameters The new instruction.
* @param callback The callback
*/
put(billingAccountName: string, billingProfileName: string, instructionName: string, parameters: Models.Instruction, callback: msRest.ServiceCallback<Models.Instruction>): void;
/**
* @param billingAccountName The ID that uniquely identifies a billing account.
* @param billingProfileName The ID that uniquely identifies a billing profile.
* @param instructionName Instruction Name.
* @param parameters The new instruction.
* @param options The optional parameters
* @param callback The callback
*/
put(billingAccountName: string, billingProfileName: string, instructionName: string, parameters: Models.Instruction, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Instruction>): void;
put(billingAccountName: string, billingProfileName: string, instructionName: string, parameters: Models.Instruction, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Instruction>, callback?: msRest.ServiceCallback<Models.Instruction>): Promise<Models.InstructionsPutResponse> {
return this.client.sendOperationRequest(
{
billingAccountName,
billingProfileName,
instructionName,
parameters,
options
},
putOperationSpec,
callback) as Promise<Models.InstructionsPutResponse>;
}
/**
* Lists the instructions by billing profile id.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.InstructionsListByBillingProfileNextResponse>
*/
listByBillingProfileNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.InstructionsListByBillingProfileNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByBillingProfileNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.InstructionListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByBillingProfileNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.InstructionListResult>): void;
listByBillingProfileNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.InstructionListResult>, callback?: msRest.ServiceCallback<Models.InstructionListResult>): Promise<Models.InstructionsListByBillingProfileNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByBillingProfileNextOperationSpec,
callback) as Promise<Models.InstructionsListByBillingProfileNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listByBillingProfileOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions",
urlParameters: [
Parameters.billingAccountName,
Parameters.billingProfileName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.InstructionListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}",
urlParameters: [
Parameters.billingAccountName,
Parameters.billingProfileName,
Parameters.instructionName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.Instruction
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const putOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/instructions/{instructionName}",
urlParameters: [
Parameters.billingAccountName,
Parameters.billingProfileName,
Parameters.instructionName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.Instruction,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.Instruction
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listByBillingProfileNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.InstructionListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
export abstract class SyntheticFile {
/**
*
* @param name the file name
* @param size the file size
* @param type the file type
* @returns
*/
static createFile = (name: string, size: number, type: string) => {
const file = new File([], name, { type });
Object.defineProperty(file, "size", {
get() {
return size;
},
});
return file;
};
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_aac = (size?: number): File => {
return SyntheticFile.createFile("acc_audio-file-with-large-name.aac", size ? size : 3516516, "audio/aac");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_abw = (size?: number): File => {
return SyntheticFile.createFile("abiword-file-with-large-name.abw", size ? size : 3516516, "application/x-abiword");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_freearc = (size?: number): File => {
return SyntheticFile.createFile("freearc-file-with-large-name.arc", size ? size : 3516516, "application/x-freearc");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_avi = (size?: number): File => {
return SyntheticFile.createFile("avi-file-with-large-name.avi", size ? size : 3516516, "video/x-msvideo");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_azw = (size?: number): File => {
return SyntheticFile.createFile("amazon_kindle_ebook-file-with-large-name.azw", size ? size : 3516516, "application/vnd.amazon.ebook");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_octet = (size?: number): File => {
return SyntheticFile.createFile("binary_octet_stream-file-with-large-name.bin", size ? size : 3516516, "application/octet-stream");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_bmp = (size?: number): File => {
return SyntheticFile.createFile("bit_map-file-with-large-name.bmp", size ? size : 3516516, "image/bmp");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_bz = (size?: number): File => {
return SyntheticFile.createFile("x_bzip-file-with-large-name.bz", size ? size : 3516516, "application/x-bzip");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_bz2 = (size?: number): File => {
return SyntheticFile.createFile("x_bzip_2-file-with-large-name.bz2", size ? size : 3516516, "application/x-bzip2");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_cda = (size?: number): File => {
return SyntheticFile.createFile("cd_audio-file-with-large-name.cda", size ? size : 3516516, "application/x-cdf");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_csh = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.csh", size ? size : 3516516, "application/x-csh");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_css = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.css", size ? size : 3516516, "text/css");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_csv = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.csv", size ? size : 3516516, "text/csv");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_doc = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.doc", size ? size : 3516516, "application/msword");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_docx = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.docx", size ? size : 3516516, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_eot = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.eot", size ? size : 3516516, "application/vnd.ms-fontobject");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_epub = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.epub", size ? size : 3516516, "application/epub+zip");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_gzip = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.gz", size ? size : 3516516, "application/gzip");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_gif = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.gif", size ? size : 3516516, "image/gif");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_htm = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.htm", size ? size : 3516516, "text/html");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_html = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.html", size ? size : 3516516, "text/html");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_ico = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.ico", size ? size : 3516516, "image/vnd.microsoft.icon");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_icalendar = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.ics", size ? size : 3516516, "text/calendar");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_jar = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.jar", size ? size : 3516516, "application/java-archive");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_jpeg = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.jpeg", size ? size : 3516516, "image/jpeg");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_jpg = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.jpg", size ? size : 3516516, "image/jpeg");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_js = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.js", size ? size : 3516516, "text/javascript");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_json = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.json", size ? size : 3516516, "application/json");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_jsonld = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.jsonld", size ? size : 3516516, "application/ld+json");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_mid = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.mid", size ? size : 3516516, "audio/midi");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_x_mid = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.mid", size ? size : 3516516, "audio/x-midi");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_midi = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.midi", size ? size : 3516516, "audio/x-midi");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_x_midi = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.midi", size ? size : 3516516, "audio/x-midi");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_mjs = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.mjs", size ? size : 3516516, "text/javascript");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_mp3 = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.mp3", size ? size : 3516516, "audio/mpeg");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_mp4 = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.mp4", size ? size : 3516516, "video/mp4");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_mpeg = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.mpeg", size ? size : 3516516, "video/mpeg");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_mpkg = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.mpkg", size ? size : 3516516, "application/vnd.apple.installer+xml");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_odp = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.odp", size ? size : 3516516, "application/vnd.oasis.opendocument.presentation");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_ods = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.ods", size ? size : 3516516, "application/vnd.oasis.opendocument.spreadsheet");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_odt = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.odt", size ? size : 3516516, "application/vnd.oasis.opendocument.text");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_oga = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.oga", size ? size : 3516516, "audio/ogg");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_ogv = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.ogv", size ? size : 3516516, "video/ogg");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_ogx = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.ogx", size ? size : 3516516, "application/ogg");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_opus = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.opus", size ? size : 3516516, "audio/opus");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_otf = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.otf", size ? size : 3516516, "font/otf");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_png = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.png", size ? size : 3516516, "image/png");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_pdf = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.pdf", size ? size : 3516516, "application/pdf");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_php = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.php", size ? size : 3516516, "application/x-httpd-php");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_ppt = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.ppt", size ? size : 3516516, "application/vnd.ms-powerpoint");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_pptx = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.pptx", size ? size : 3516516, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_rar = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.rar", size ? size : 3516516, "application/vnd.rar");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_rtf = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.rtf", size ? size : 3516516, "application/rtf");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_sh = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.sh", size ? size : 3516516, "application/x-sh");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_svg = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.svg", size ? size : 3516516, "image/svg+xml");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_swf = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.swf", size ? size : 3516516, "application/x-shockwave-flash");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_tar = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.tar", size ? size : 3516516, "application/x-tar");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_tif = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.tif", size ? size : 3516516, "image/tiff");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_tiff = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.tiff", size ? size : 3516516, "image/tiff");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_ts = (size?: number): File => {
return SyntheticFile.createFile("mp2t_video-file-with-large-name.ts", size ? size : 3516516, "video/mp2t");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_ttf = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.ttf", size ? size : 3516516, "font/ttf");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_text = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.txt", size ? size : 3516516, "text/plain");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_typescript = (size?: number): File => {
return SyntheticFile.createFile("typescript-file-with-large-name.ts", size ? size : 3516516, "text/plain");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_vsd = (size?: number): File => {
return SyntheticFile.createFile("ms_visio-file-with-large-name.vsd", size ? size : 3516516, "application/vnd.visio");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_wav = (size?: number): File => {
return SyntheticFile.createFile("wav_audio-file-with-large-name.wav", size ? size : 3516516, "audio/wav");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_weba = (size?: number): File => {
return SyntheticFile.createFile("web_audio-file-with-large-name.weba", size ? size : 3516516, "audio/webm");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_webm = (size?: number): File => {
return SyntheticFile.createFile("web_video-file-with-large-name.webm", size ? size : 3516516, "video/webm");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_webp = (size?: number): File => {
return SyntheticFile.createFile("web_image-file-with-large-name.webp", size ? size : 3516516, "image/webp");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_woff = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.woff", size ? size : 3516516, "font/woff");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_woff2 = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.woff2", size ? size : 3516516, "font/woff2");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_xhtml = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.xhtml", size ? size : 3516516, "application/xhtml+xml");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_xlsx = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.xls", size ? size : 3516516, "application/vnd.ms-excel");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_xls = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.xlsx", size ? size : 3516516, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_xml = (size?: number): File => {
return SyntheticFile.createFile("xml-file-with-large-name.xml", size ? size : 3516516, "application/xml");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_xml_txt = (size?: number): File => {
return SyntheticFile.createFile("xml_plain_text-file-with-large-name.xml", size ? size : 3516516, "application/xml");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_xul = (size?: number): File => {
return SyntheticFile.createFile("test-file-with-large-name.xul", size ? size : 3516516, "application/vnd.mozilla.xul+xml");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_zip = (size?: number): File => {
return SyntheticFile.createFile("zip-file-with-large-name.zip", size ? size : 3516516, "application/zip");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_3gp = (size?: number): File => {
return SyntheticFile.createFile("3gp_video-file-with-large-name.3gp", size ? size : 3516516, "video/3gpp");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_3gp2 = (size?: number): File => {
return SyntheticFile.createFile("3gp2_video-file-with-large-name.3g2", size ? size : 3516516, "video/3gpp2");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_3gp_a = (size?: number): File => {
return SyntheticFile.createFile("3gp_audio-file-with-large-name.3gp", size ? size : 3516516, "audio/3gpp");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_3gp_v = (size?: number): File => {
return SyntheticFile.createFile("3gp_audio-file-with-large-name.3gp2", size ? size : 3516516, "audio/3gpp2");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_7z = (size?: number): File => {
return SyntheticFile.createFile("seven_zip-file-with-large-name.7z", size ? size : 3516516, "application/x-7z-compressed");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_python = (size?: number): File => {
return SyntheticFile.createFile("python-file-with-large-name.py", size ? size : 3516516, "text/plain");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_java = (size?: number): File => {
return SyntheticFile.createFile("java-file-with-large-name.java", size ? size : 3516516, "text/plain");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_react = (size?: number): File => {
return SyntheticFile.createFile("react_jsx-file-with-large-name.jsx", size ? size : 3516516, "text/plain");
}
/**
*
* @param size the file size
* @returns a syntetic File object instance
*/
static create_vue = (size?: number): File => {
return SyntheticFile.createFile("vue-file-with-large-name.vue", size ? size : 3516516, "text/plain");
}
/**
* Creates an array of fake (synthetic) files
* @param size the file size for all synthetic files
* @returns an array of all file icon preview supported files
*/
static createFileListMiscelanious = (size?: number): File[] => {
let listFile: File[] = [];
listFile.push(SyntheticFile.create_aac(size));
listFile.push(SyntheticFile.create_abw(size));
listFile.push(SyntheticFile.create_freearc(size));
listFile.push(SyntheticFile.create_avi(size));
listFile.push(SyntheticFile.create_azw(size));
listFile.push(SyntheticFile.create_octet(size));
listFile.push(SyntheticFile.create_bmp(size));
listFile.push(SyntheticFile.create_bz(size));
listFile.push(SyntheticFile.create_bz2(size));
listFile.push(SyntheticFile.create_cda(size));
listFile.push(SyntheticFile.create_csh(size));
listFile.push(SyntheticFile.create_css(size));
listFile.push(SyntheticFile.create_csv(size));
listFile.push(SyntheticFile.create_doc(size));
listFile.push(SyntheticFile.create_docx(size));
listFile.push(SyntheticFile.create_eot(size));
listFile.push(SyntheticFile.create_epub(size));
listFile.push(SyntheticFile.create_gzip(size));
listFile.push(SyntheticFile.create_gif(size));
listFile.push(SyntheticFile.create_htm(size));
listFile.push(SyntheticFile.create_html(size));
listFile.push(SyntheticFile.create_ico(size));
listFile.push(SyntheticFile.create_icalendar(size));
listFile.push(SyntheticFile.create_jar(size));
listFile.push(SyntheticFile.create_jpeg(size));
listFile.push(SyntheticFile.create_jpg(size));
listFile.push(SyntheticFile.create_js(size));
listFile.push(SyntheticFile.create_json(size));
listFile.push(SyntheticFile.create_jsonld(size));
listFile.push(SyntheticFile.create_mid(size));
listFile.push(SyntheticFile.create_midi(size));
listFile.push(SyntheticFile.create_x_mid(size));
listFile.push(SyntheticFile.create_x_midi(size));
listFile.push(SyntheticFile.create_mjs(size));
listFile.push(SyntheticFile.create_mp3(size));
listFile.push(SyntheticFile.create_mp4(size));
listFile.push(SyntheticFile.create_mpeg(size));
listFile.push(SyntheticFile.create_mpkg(size));
listFile.push(SyntheticFile.create_odp(size));
listFile.push(SyntheticFile.create_ods(size));
listFile.push(SyntheticFile.create_odt(size));
listFile.push(SyntheticFile.create_oga(size));
listFile.push(SyntheticFile.create_ogv(size));
listFile.push(SyntheticFile.create_ogx(size));
listFile.push(SyntheticFile.create_opus(size));
listFile.push(SyntheticFile.create_otf(size));
listFile.push(SyntheticFile.create_png(size));
listFile.push(SyntheticFile.create_pdf(size));
listFile.push(SyntheticFile.create_php(size));
listFile.push(SyntheticFile.create_ppt(size));
listFile.push(SyntheticFile.create_pptx(size));
listFile.push(SyntheticFile.create_rar(size));
listFile.push(SyntheticFile.create_rtf(size));
listFile.push(SyntheticFile.create_sh(size));
listFile.push(SyntheticFile.create_svg(size));
listFile.push(SyntheticFile.create_swf(size));
listFile.push(SyntheticFile.create_tar(size));
listFile.push(SyntheticFile.create_tif(size));
listFile.push(SyntheticFile.create_tiff(size));
listFile.push(SyntheticFile.create_ts(size));
listFile.push(SyntheticFile.create_ttf(size));
listFile.push(SyntheticFile.create_text(size));
listFile.push(SyntheticFile.create_typescript(size));
listFile.push(SyntheticFile.create_vsd(size));
listFile.push(SyntheticFile.create_wav(size));
listFile.push(SyntheticFile.create_weba(size));
listFile.push(SyntheticFile.create_webm(size));
listFile.push(SyntheticFile.create_webp(size));
listFile.push(SyntheticFile.create_woff(size));
listFile.push(SyntheticFile.create_woff2(size));
listFile.push(SyntheticFile.create_xhtml(size));
listFile.push(SyntheticFile.create_xlsx(size));
listFile.push(SyntheticFile.create_xls(size));
listFile.push(SyntheticFile.create_xml(size));
listFile.push(SyntheticFile.create_xml_txt(size));
listFile.push(SyntheticFile.create_xul(size));
listFile.push(SyntheticFile.create_zip(size));
//listFile.push(SyntheticFile.create_3gp(size));
//listFile.push(SyntheticFile.create_3gp2(size));
//listFile.push(SyntheticFile.create_3gp_a(size));
//listFile.push(SyntheticFile.create_3gp_v(size));
//listFile.push(SyntheticFile.create_7z(size));
listFile.push(SyntheticFile.create_python(size));
listFile.push(SyntheticFile.create_java(size));
listFile.push(SyntheticFile.create_react(size));
listFile.push(SyntheticFile.create_vue(size));
return listFile;
}
} | the_stack |
import {
DirectionCode, DelayCode, IterationCountCode, FillModeCode,
EasingCode, PlaySpeedCode, NumberCode, UnitCode, StringCode,
ColorCode, ArrayCode, ObjectCode, TimelineCode, KeyframerCode,
ProgressCode, LineDrawingCode, MorphingCode, PlayMethodCode, BlinkCode, FadeInCode, FadeOutCode,
WipeInCode, WipeOutCode, ZoomInCode, ZoomOutCode, ShakeCode, ShakeXCode,
ShakeYCode, FlipCode, FlipXCode, FlipYCode, TransitionCode, ExportCode, TypingCode,
} from "./page";
/* tslint:disable:max-line-length */
export const datas = [
{
title: "Options",
features: [
{
id: "direction",
title: "direction",
description: "The direction property defines whether an animation should be played forwards, backwards or in alternate cycles.",
code: DirectionCode,
html: `<div class="rects"><div class="rect rect1"></div><div class="rect rect2"></div><div class="rect rect3"></div><div class="rect rect4"></div></div>`,
examples: [
{
value: "normal",
title: `direction: normal (default)`,
},
{
value: "reverse",
title: `direction: reverse`,
},
{
value: "alternate",
title: `direction: alternate`,
},
{
value: "alternate-reverse",
title: `direction: alternate-reverse`,
},
],
},
{
id: "delay",
title: "delay",
description: "The delay property specifies a delay for the start of an animation.",
code: DelayCode,
html: `
<div class="circles">
<div class="circle circle1"></div>
<div class="circle circle2"></div>
</div>
`,
examples: [
{
title: "",
value: "",
},
],
},
{
id: "iterationcount",
title: "iterationCount",
description: "The iterationCount property specifies the number of times an animation should be played.",
code: IterationCountCode,
html: `
<div class="circles">
<div class="circle circle1"></div>
<div class="circle circle2"></div>
<div class="circle circle3"></div>
</div>`,
examples: [
{
title: "iterationCount: 1 (default)",
value: 1,
},
{
title: "iterationCount: 2",
value: 2,
},
{
title: "iterationCount: infinite",
value: "infinite",
},
],
},
{
id: "fillmode",
title: "fillMode",
description: "The fillMode property specifies a style for the element when the animation is not playing (before it starts, after it ends, or both).",
code: FillModeCode,
html: `
<div class="pie fill">
<div class="half left">
<div class="semicircle"></div>
</div>
<div class="half right">
<div class="semicircle"></div>
</div>
</div>
`,
examples: [
{
title: "fillMode: forwards (default)",
value: "forwards",
},
{
title: "fillMode: backwards",
value: "backwards",
},
{
title: "fillMode: both",
value: "both",
},
],
},
{
id: "easing",
title: "easing",
description: "The easing(timing-function) specifies the speed curve of an animation.",
code: EasingCode,
html: `<div class="rects"><div class="rect rect1"></div><div class="rect rect2"></div><div class="rect rect3"></div><div class="rect rect4"></div></div>`,
examples: [
{
title: "easing: linear (default)",
value: "linear",
},
{
title: "easing: ease",
value: "ease",
},
{
title: "easing: ease-in",
value: "ease-in",
},
{
title: "easing: ease-out",
value: "ease-out",
},
{
title: "easing: ease-in-out",
value: "ease-in-out",
},
{
title: "easing: steps(6, end)",
value: "steps(6, end)",
},
{
title: "easing: cubic-bezier(0.74, 0, 0.42, 1.47)",
value: "cubic-bezier(0.74, 0, 0.42, 1.47)",
},
],
},
{
id: "playspeed",
title: "playSpeed",
description: "The playspeed define the speed at which the play is performed.",
html: `
<div class="chase">
<svg viewBox="0 0 100 100">
<ellipse fill="transparent" cx="50" cy="50" rx="49.5" ry="49.5" stroke-linejoin="round" stroke-width="1" stroke-linecap="round" stroke="#999"></ellipse></svg>
<div class="dot"></div>
</div>
`,
code: PlaySpeedCode,
examples: [
{
title: "playSpeed: 1 (default)",
value: 1,
},
{
title: "playSpeed: 2",
value: 2,
},
],
},
],
},
{
title: "Values",
features: [
{
id: "number",
title: "Number",
description: "In order to interpolate, it must be a number by default.",
html: `
<div class="squares">
<div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div>
<div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div>
<div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div><div class="square"></div>
</div>`,
code: NumberCode,
examples: [
{
title: "opacity: 0 to 1",
value: [0, 1],
},
],
},
{
id: "unit",
title: "Unit",
description: "10px, 10%, 10em, etc. is a string that represents a number but has a unit. In this case, number and unit are divided and only numbers are interpolated.",
html: `
<div class="overflow">
<div class="text"><span>Scene.js</span></div>
</div>
<div class="overflow">
<div class="text"><span>CSS</span></div>
</div>
<div class="overflow">
<div class="text"><span>Animation</span></div>
</div>
`,
code: UnitCode,
examples: [
{
title: "100% to 0%",
value: "unit",
},
],
},
{
id: "string",
title: "String",
description: "string indicates the first value before the time of 1, and then the second value when it is 1 because it determines that it cannot be interpolated.",
html: `<div class="text center"></div>`,
code: StringCode,
examples: [
{
title: "Typing",
value: "string",
},
],
},
{
id: "colors",
title: "Colors",
description: "It supports color models such as hex, rgb(a), and hsl(a).",
html: `<div class="target center"></div>`,
code: ColorCode,
examples: [
{
title: "#000 to #ff5555",
value: ["#000", "#ff5555"],
},
{
title: "#000 to rgba(255, 100, 100, 1)",
value: ["#000", "rgba(255, 100, 100, 1)"],
},
{
title: "#000 to hsla(0, 100%, 67%, 1)",
value: ["#000", "hsla(0, 100%, 67%, 1)"],
},
],
},
{
id: "array",
title: "Array",
description: "Interpolates the value of the array.",
html: `<div class="text center"></div>`,
code: ArrayCode,
examples: [
{
title: "[0, 0, 0] to [200, 100, 50]",
value: [0, 0, 0],
},
],
},
{
id: "object",
title: "Object",
description: "Interpolates the value of the object.",
html: `<div class="loading">
<div class="circle left top"></div>
<div class="circle left bottom"></div>
<div class="circle right bottom"></div>
<div class="circle right top"></div>
</div>`,
code: ObjectCode,
examples: [
{
title: "transform",
value: "transform",
},
],
},
],
},
{
title: "Timeline",
description: "", // Scene.js is timeline-based animation library like CSS keyframes. That's why you can control time with your own hands.
features: [
{
id: "timeline",
title: "Timeline",
description: `<a href="https://github.com/daybrush/scenejs-timeline" target="_blank">@scenejs/timeline</a> is a library that represents the timeline of Scene.js. You can control time, properties, and items.`,
html: `
<div class="clapper">
<div class="clapper-container">
<div class="clapper-body">
<div class="top">
<div class="stick stick1">
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
</div>
<div class="stick stick2">
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
</div>
</div>
<div class="bottom"></div>
</div>
<div class="circle"></div>
<div class="play">
<svg class="__shape-svg" viewBox="0 0 70 77.73502691896255">
<path d="M 60 38.86751345948127 L 10.000000000000021 67.73502691896255 L 10 10 L 60 38.86751345948127 Z" fill="#333" stroke-linejoin="round" stroke-width="10" stroke="#333"></path></svg>
</div>
</div>
</div>
`,
code: TimelineCode,
examples: [
{
title: "",
value: "",
},
],
},
{
id: "keyframer",
title: "Keyframer",
description: `<a href="https://github.com/daybrush/keyframer" target="_blank">keyframer</a> is a library that ake the CSS Keyframes the keyframes object. play CSS keyframes.`,
html: `
<style>
@keyframes keyframer_keyframes {
7.69% {
border-width:35px;
transform: translate(-50%, -50%) scale(0);
}
84.61% {
border-width: 0px;
transform: translate(-50%, -50%) scale(1);
}
100% {
border-width: 0px;
transform: translate(-50%, -50%) scale(1);
}
}
</style>
<div class="rects"><div class="rect"></div></div>
`,
code: KeyframerCode,
examples: [{ value: "" }],
},
{
id: "progress",
title: "Progress",
description: "You can create a player that can tell progress from 0% to 100% over time and control the scene.",
html: `
<div class="circles">
<div class="circle circle1"></div>
<div class="circle circle2"></div>
<div class="circle circle3"></div>
</div>
<div class="player">
<div class="play"></div>
<input class="progress" type="range" value="0" min="0" max="100"/>
</div>`,
code: ProgressCode,
examples: [
{
title: "",
value: "",
},
],
},
],
},
{
title: "SVG Animation",
features: [
{
id: "linedrawing",
title: "Line Drawing",
description: "You can create handwriting-like effects with the css property called <strong>stroke-dasharray</strong>.",
code: LineDrawingCode,
html: `
<svg class="svg" width="100%" height="100%" viewBox="0 0 500 200" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/">
<g transform="matrix(0.5,0,0,0.5,0,0)">
<g id="Artboard1" transform="matrix(0.966957,0,0,0.675155,-748.037,-365.425)">
<rect x="773.599" y="541.246" width="1034.17" height="592.456" style="fill:none;"/>
<g id="Layer1" transform="matrix(1.03417,0,0,1.48114,773.599,520.51)">
<path stroke="#333" stroke-width="20" stroke-linecap="round" fill="transparent" d="M14.072,282.172C62.055,287.178 211.405,258.288 232.093,106.803C245.183,10.95 175.634,38.769 175.274,121.466C174.696,254.303 345.708,276.667 261.505,364.848C223.868,404.264 162.843,365.295 135.844,332.678C44.912,222.821 174.741,290.734 226.944,314.06C305.751,349.274 394.038,317.424 421.116,157.12C440.884,40.084 426.007,37.332 405.238,178.8C374.39,388.93 525.241,428.727 604.056,135.659C631.833,32.372 590.153,120.492 700.477,128.771C765.675,133.664 906.434,99.5 899.092,83.529C888.047,59.504 651.522,134.399 689.798,210.4C715.743,261.917 824.613,253.598 880.128,185.618C925.485,130.077 888.739,57.951 897.887,113.597C922.461,263.076 786.919,398.343 713.414,373.936C695.57,368.011 688.743,349.213 700.318,334.202C754.291,264.208 948.931,261.515 988.492,282.759" style="fill:none;"/>
</g>
</g>
</g>
</svg>`,
examples: [{
title: "",
value: "",
}],
},
{
id: "morph",
title: "Morph Shape",
description: "In <strong>path</strong> SVGElement, you can transform the shape through the attribute <strong>d</strong>.",
code: MorphingCode,
html: `
<svg class="svg" viewBox="0 0 120 120">
<path stroke="#333" stroke-width="5" stroke-linejoin="round" stroke-linecap="round" fill="transparent"/>
</svg>`,
examples: [{
title: "",
value: "",
}],
},
],
},
{
title: "Controls",
features: [
{
id: "jscss",
title: "Play JavaScript & Play CSS",
description: "Scene.js supports both JavaScript and CSS play methods.",
html: `
<div class="play-method play-method-js">
<h5>Play JavaScript</h5>
<div class="clapper">
<div class="clapper-container">
<div class="clapper-body">
<div class="top">
<div class="stick stick1">
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
</div>
<div class="stick stick2">
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
</div>
</div>
<div class="bottom"></div>
</div>
<div class="circle"></div>
<div class="play">
<svg class="__shape-svg" viewBox="0 0 70 77.73502691896255">
<path d="M 60 38.86751345948127 L 10.000000000000021 67.73502691896255 L 10 10 L 60 38.86751345948127 Z" fill="#333" stroke-linejoin="round" stroke-width="10" stroke="#333"></path>
</svg>
</div>
</div>
</div>
</div>
<div class="play-method play-method-css">
<h5>Play CSS</h5>
<div class="clapper">
<div class="clapper-container">
<div class="clapper-body">
<div class="top">
<div class="stick stick1">
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
</div>
<div class="stick stick2">
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
<div class="rect"></div>
</div>
</div>
<div class="bottom"></div>
</div>
<div class="circle"></div>
<div class="play">
<svg class="__shape-svg" viewBox="0 0 70 77.73502691896255">
<path d="M 60 38.86751345948127 L 10.000000000000021 67.73502691896255 L 10 10 L 60 38.86751345948127 Z" fill="#333" stroke-linejoin="round" stroke-width="10" stroke="#333"></path>
</svg>
</div>
</div>
</div>
</div>`,
code: PlayMethodCode,
examples: [{
title: "",
value: "",
}],
},
// {
// id: "media",
// title: "Play media (video, audio)",
// description: `<a href="https://github.com/daybrush/scenejs-media" target="_blank">@scenejs/media</a> is a library for playing or controlling media with Scene.js`,
// html: "1",
// code: () => "",
// examples: [{value: ""}],
// },
// {
// id: "iframe",
// title: "Play animation in iframe",
// description: `<a href="https://github.com/daybrush/scenejs-iframe" target="_blank">@scenejs/iframe</a> is A library that control the animation of iframe with Scene.js`,
// html: "1",
// code: () => "",
// examples: [{value: ""}],
// },
],
},
{
title: "Effects",
description: `<a href="https://github.com/daybrush/scenejs-effects" target="_blank">@scenejs/effects</a> is a library that can create various animation effects in <a href="https://github.com/daybrush/scenejs" target="_blank">scenejs</a>.`,
features: [
{
id: "typing",
title: "typing",
description: "Make a typing effect that is typed one character at a time like a typewriter. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.typing\" target=\"_blank\">.typing</a>)",
html: `<div class="text center"><span></span><div class="cursor"></div></div>`,
code: TypingCode,
examples: [{ value: "" }],
},
{
id: "fadein",
title: "fadeIn",
description: "Make a fade in effect. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.fadeIn\" target=\"_blank\">.fadeIn</a>)",
html: `<div class="target center">1</div>`,
code: FadeInCode,
examples: [{ value: "" }],
},
{
id: "fadeout",
title: "fadeOut",
description: "Make a fade out effect. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.fadeIn\" target=\"_blank\">.fadeIn</a>)",
html: `<div class="target center">1</div>`,
code: FadeOutCode,
examples: [{ value: "" }],
},
{
id: "blink",
title: "blink",
description: "Make a blinking effect. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.blink\" target=\"_blank\">.blink</a>)",
html: `<div class="target center">1</div>`,
code: BlinkCode,
examples: [{ value: "" }],
},
{
id: "wipein",
title: "wipeIn",
description: "Make a wipe in effect. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.wipeIn\" target=\"_blank\">.wipeIn</a>)",
html: `<div class="target center">1</div>`,
code: WipeInCode,
examples: [{ value: "" }],
},
{
id: "wipeout",
title: "wipeOut",
description: "Make a wipe out effect. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.wipeOut\" target=\"_blank\">.wipeOut</a>)",
html: `<div class="target center">1</div>`,
code: WipeOutCode,
examples: [{ value: "" }],
},
{
id: "zoomin",
title: "zoomIn",
description: "Make a zoom in effect. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.zoomIn\" target=\"_blank\">.zoomIn</a>)",
html: `<div class="target center">1</div>`,
code: ZoomInCode,
examples: [{ value: "" }],
},
{
id: "zoomout",
title: "zoomOut",
description: "Make a zoom out effect. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.zoomOut\" target=\"_blank\">.zoomOut</a>)",
html: `<div class="target center">1</div>`,
code: ZoomOutCode,
examples: [{ value: "" }],
},
{
id: "shake",
title: "shake",
description: "Make a shake effect. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.shake\" target=\"_blank\">.shake</a>)",
html: `<div class="target center">1</div><div class="target2 center">2</div>`,
code: ShakeCode,
examples: [{ value: "" }],
},
{
id: "shakex",
title: "shakeX",
description: "Make a horizontal shake effect. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.shakeX\" target=\"_blank\">.shakeX</a>)",
html: `<div class="target center">1</div>`,
code: ShakeXCode,
examples: [{ value: "" }],
},
{
id: "shakey",
title: "shakeY",
description: "Make a vertical shake effect. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.shakeY\" target=\"_blank\">.shakeY</a>)",
html: `<div class="target center">1</div>`,
code: ShakeYCode,
examples: [{ value: "" }],
},
{
id: "flip",
title: "flip",
description: "You can create a flip effect horizontally, vertically, or diagonally. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.flip\" target=\"_blank\">.flip</a>)",
html: `<div class="flip target center">1</div><div class="flip target2 center">2</div>`,
code: FlipCode,
examples: [{ value: "" }],
},
{
id: "flipx",
title: "flipX",
description: "You can create an effect that flips vertically around the x-axis. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.flipX\" target=\"_blank\">.flipX</a>)",
html: `<div class="flip target center">1</div><div class="flip target2 center">2</div>`,
code: FlipXCode,
examples: [{ value: "" }],
},
{
id: "flipy",
title: "flipY",
description: "You can create an effect that flips horizontally around the y-axis. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.flipY\" target=\"_blank\">.flipY</a>)",
html: `<div class="flip target center">1</div><div class="flip target2 center">2</div>`,
code: FlipYCode,
examples: [{ value: "" }],
},
{
id: "transition",
title: "transition",
description: "Switch the scene from `item1` to `item2`. (see: <a href=\"https://daybrush.com/scenejs-effects/release/latest/doc/effects.html#.transition\" target=\"_blank\">.transition</a>)",
html: `<div class="flip target center">1</div><div class="flip target2 center">2</div>`,
code: TransitionCode,
examples: [{ value: "" }],
},
],
},
{
title: "Rendering",
features: [
{
id: "mp4",
title: "Export MP4",
description: `You can export CSS Animation to a video file with simple commands using <a href="https://ffmpeg.org/" target="_blank">ffmpeg</a> and <a href="https://github.com/daybrush/scenejs-render" target="_blank">@scenejs/render</a>. <br/><br/> <a href="https://daybrush.com/scenejs/release/latest/examples/clapper.html" target="_blank">Original Source</a>`,
html: `<iframe width="560" height="315" src="https://www.youtube.com/embed/rb-5xBKyCeE" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`,
code: ExportCode,
examples: [{ value: "" }],
},
],
},
]; | the_stack |
import {OpenYoloCredential as OpenYoloCredential, OpenYoloCredentialRequestOptions as OpenYoloCredentialRequestOptions} from '../protocol/data';
import {AUTHENTICATION_METHODS} from '../protocol/data';
import {InternalErrorCode, OpenYoloErrorType, OpenYoloInternalError} from '../protocol/errors';
import {OpenYoloApi} from './api';
import {NavigatorCredentials, NoOpNavigatorCredentials} from './navigator_credentials';
describe('NavigatorCredentials', () => {
if (!navigator.credentials) {
// Only test browsers with navigator.credentials implemented (Chrome).
return;
}
let cmApi = navigator.credentials!;
let navigatorCredentials: OpenYoloApi;
beforeEach(() => {
navigatorCredentials = new NavigatorCredentials(cmApi);
});
describe('disableAutoSignIn', () => {
it('resolves when success', (done) => {
spyOn(cmApi, 'preventSilentAccess').and.returnValue(Promise.resolve());
navigatorCredentials.disableAutoSignIn().then(done);
});
it('resolves when insecure origin error', (done) => {
spyOn(cmApi, 'preventSilentAccess')
.and.returnValue(Promise.reject(new Error('Insecure origin!')));
navigatorCredentials.disableAutoSignIn().then(done);
});
});
describe('retrieve', () => {
it('returns the federated credential', done => {
const options: OpenYoloCredentialRequestOptions = {
supportedAuthMethods: [AUTHENTICATION_METHODS.GOOGLE]
};
const federatedCredential = new FederatedCredential({
provider: AUTHENTICATION_METHODS.GOOGLE,
protocol: 'openidconnect',
name: 'Name',
iconURL: 'https://www.example.com/icon.jpg',
id: 'user@example.com'
});
spyOn(cmApi, 'get').and.returnValue(Promise.resolve(federatedCredential));
navigatorCredentials.retrieve(options).then(credential => {
expect(cmApi.get).toHaveBeenCalledWith(jasmine.objectContaining({
password: false,
federated:
{providers: [AUTHENTICATION_METHODS.GOOGLE], protocols: []},
unmediated: false
}));
expect(credential).toEqual({
id: 'user@example.com',
authMethod: AUTHENTICATION_METHODS.GOOGLE,
displayName: 'Name',
profilePicture: 'https://www.example.com/icon.jpg',
proxiedAuthRequired: false
});
done();
});
});
it('returns the password credential', done => {
const options: OpenYoloCredentialRequestOptions = {
supportedAuthMethods: [AUTHENTICATION_METHODS.ID_AND_PASSWORD]
};
const passwordCredential = new PasswordCredential({
name: 'Name',
iconURL: 'https://www.example.com/icon.jpg',
type: 'password',
id: 'user@example.com',
idName: 'username',
passwordName: 'password',
password: 'password',
additionalData: null
});
spyOn(cmApi, 'get').and.returnValue(Promise.resolve(passwordCredential));
navigatorCredentials.retrieve(options).then(credential => {
expect(cmApi.get).toHaveBeenCalledWith(jasmine.objectContaining({
password: true,
federated: {providers: [], protocols: []},
unmediated: false
}));
expect(credential).toEqual(jasmine.objectContaining({
id: 'user@example.com',
authMethod: AUTHENTICATION_METHODS.ID_AND_PASSWORD,
displayName: 'Name',
profilePicture: 'https://www.example.com/icon.jpg',
proxiedAuthRequired: false,
password: 'password'
}));
done();
});
});
it('rejects when no credential', done => {
const options: OpenYoloCredentialRequestOptions = {
supportedAuthMethods: [AUTHENTICATION_METHODS.GOOGLE]
};
spyOn(cmApi, 'get').and.returnValue(Promise.resolve());
navigatorCredentials.retrieve(options).then(
credential => {
done.fail('Should not resolve!');
},
(error) => {
expect(OpenYoloInternalError.errorIs(
error, InternalErrorCode.noCredentialsAvailable));
done();
});
});
it('fails', done => {
const options: OpenYoloCredentialRequestOptions = {
supportedAuthMethods: [AUTHENTICATION_METHODS.GOOGLE]
};
const expectedError = new Error('ERROR!');
spyOn(cmApi, 'get').and.returnValue(Promise.reject(expectedError));
navigatorCredentials.retrieve(options).then(
() => {
done.fail('Unexpected success!');
},
error => {
expect(error.type).toEqual(OpenYoloErrorType.requestFailed);
done();
});
});
});
describe('cancelLastOperation', () => {
it('always resolves', done => {
navigatorCredentials.cancelLastOperation().then(done);
});
});
describe('save', () => {
it('saves the password credential', done => {
const credential: OpenYoloCredential = {
id: 'user@example.com',
authMethod: AUTHENTICATION_METHODS.ID_AND_PASSWORD,
displayName: 'Name',
profilePicture: 'http://www.example.com/icon.jpg',
proxiedAuthRequired: false, // Does not matter but required.
password: 'password'
};
const fakeSavedCred = {};
spyOn(cmApi, 'store').and.callFake((cred: any) => {
expect(cred instanceof PasswordCredential).toBe(true);
expect(cred.id).toEqual('user@example.com');
expect(cred.name).toEqual('Name');
expect(cred.iconURL).toEqual('http://www.example.com/icon.jpg');
return Promise.resolve(fakeSavedCred);
});
navigatorCredentials.save(credential).then(done);
});
it('saves the federated credential', done => {
const credential: OpenYoloCredential = {
id: 'user@example.com',
authMethod: AUTHENTICATION_METHODS.GOOGLE,
displayName: 'Name',
profilePicture: 'http://www.example.com/icon.jpg',
proxiedAuthRequired: false // Does not matter but required.
};
const fakeSavedCred = {};
spyOn(cmApi, 'store').and.callFake((cred: any) => {
expect(cred instanceof FederatedCredential).toBe(true);
expect(cred.id).toEqual('user@example.com');
expect(cred.provider).toEqual(AUTHENTICATION_METHODS.GOOGLE);
expect(cred.name).toEqual('Name');
expect(cred.iconURL).toEqual('http://www.example.com/icon.jpg');
return Promise.resolve(fakeSavedCred);
});
navigatorCredentials.save(credential).then(done);
});
it('fails', done => {
const expectedError = new Error('ERROR!');
spyOn(cmApi, 'store').and.returnValue(Promise.reject(expectedError));
const credential: OpenYoloCredential = {
id: 'user@example.com',
authMethod: AUTHENTICATION_METHODS.GOOGLE,
displayName: 'Name',
profilePicture: 'http://www.example.com/icon.jpg',
proxiedAuthRequired: false // Does not matter but required.
};
navigatorCredentials.save(credential)
.then(
() => {
done.fail('Unexpected success!');
},
error => {
expect(error.type).toEqual(OpenYoloErrorType.requestFailed);
done();
});
});
});
describe('proxyLogin', () => {
const options: OpenYoloCredentialRequestOptions = {
supportedAuthMethods: [AUTHENTICATION_METHODS.ID_AND_PASSWORD]
};
let credential: PasswordCredential;
beforeEach(() => {
credential = {
name: 'Name',
iconURL: 'icon.jpg',
type: 'password',
id: 'user@example.com',
idName: 'username',
passwordName: 'password',
additionalData: null
};
});
it('fetches with the correct credential', done => {
const otherCredential: PasswordCredential = {
name: 'Name 2',
iconURL: 'icon.jpg',
type: 'password',
id: 'user2@example.com',
idName: 'username',
passwordName: 'password',
additionalData: null
};
const expectedResponse = {
status: 200,
text: () => {
return Promise.resolve('Signed in!');
}
};
const getSpy = spyOn(cmApi, 'get');
getSpy.and.returnValue(Promise.resolve(otherCredential));
// We cannot test for the value of credentials passed to fetch method, as
// once the Request object is created (with the `credentials` param), its
// `credentials` property is set to "password". Any idea to properly test
// is welcome.
spyOn(window, 'fetch').and.returnValue(Promise.resolve(expectedResponse));
navigatorCredentials.retrieve(options)
.then((cred) => {
// Second call is the credential to use.
getSpy.and.returnValue(Promise.resolve(credential));
return navigatorCredentials.retrieve(options);
})
.then((cred) => {
return navigatorCredentials.proxyLogin(cred);
})
.then((response) => {
expect(response).toEqual(jasmine.objectContaining(
{statusCode: 200, responseText: 'Signed in!'}));
done();
});
});
it('fetches return status different than 200 reject the promise', done => {
const expectedResponse = {status: 400};
spyOn(cmApi, 'get').and.returnValue(Promise.resolve(credential));
spyOn(window, 'fetch').and.returnValue(Promise.resolve(expectedResponse));
navigatorCredentials.retrieve(options).then((cred) => {
navigatorCredentials.proxyLogin(cred).then(
(response) => {
done.fail('Unexpected success!');
},
(error) => {
expect(error.type).toEqual(OpenYoloErrorType.requestFailed);
expect(error.message)
.toContain(
'The API request failed to resolve: Status code 400');
done();
});
});
});
it('requires the credential to be fetched first', done => {
const cred = {
id: 'user@example.com',
authMethod: AUTHENTICATION_METHODS.ID_AND_PASSWORD,
displayName: 'Name',
profilePicture: 'photo.jpg',
isProxyLoginRequired: true
};
navigatorCredentials.proxyLogin(cred).then(
(response) => {
done.fail('Unexpected success!');
},
(error) => {
expect(error.type).toEqual(OpenYoloErrorType.requestFailed);
expect(error.message).toContain('Invalid credential.');
done();
});
});
});
describe('NoOp implementation', () => {
beforeEach(() => {
navigatorCredentials = new NoOpNavigatorCredentials();
});
it('retrieve', (done) => {
navigatorCredentials.retrieve({supportedAuthMethods: []})
.then(
() => {
done.fail('Should not resolve!');
},
(error) => {
expect(error.type)
.toEqual(OpenYoloErrorType.noCredentialsAvailable);
done();
});
});
it('hint', (done) => {
navigatorCredentials.hint({supportedAuthMethods: []})
.then(
() => {
done.fail('Should not resolve!');
},
(error) => {
expect(error.type)
.toEqual(OpenYoloErrorType.noCredentialsAvailable);
done();
});
});
it('hintsAvaialble', (done) => {
navigatorCredentials.hintsAvailable({supportedAuthMethods: []})
.then(done);
});
it('save', (done) => {
const cred = {
id: 'user@example.com',
authMethod: AUTHENTICATION_METHODS.ID_AND_PASSWORD,
displayName: 'Name',
profilePicture: 'photo.jpg',
isProxyLoginRequired: true
};
navigatorCredentials.save(cred).then(done);
});
it('proxyLogin', (done) => {
const cred = {
id: 'user@example.com',
authMethod: AUTHENTICATION_METHODS.ID_AND_PASSWORD,
displayName: 'Name',
profilePicture: 'photo.jpg',
isProxyLoginRequired: true
};
navigatorCredentials.proxyLogin(cred).then(
() => {
done.fail('Should not resolve!');
},
(error) => {
expect(error.type).toEqual(OpenYoloErrorType.requestFailed);
done();
});
});
it('disableAutoSignIn', (done) => {
navigatorCredentials.disableAutoSignIn().then(done);
});
it('disableAutcancelLastOperationoSignIn', (done) => {
navigatorCredentials.cancelLastOperation().then(done);
});
});
}); | the_stack |
import {
Answer,
ChatMessageSource,
IChatOptions,
IRule,
IRuleOption,
} from '../types';
import * as utils from './utils';
export class ChatUI {
public isMobile: boolean;
public chat: HTMLDivElement;
public form: HTMLFormElement;
public textArea: HTMLTextAreaElement;
public inputText: HTMLInputElement;
public input: HTMLInputElement | HTMLTextAreaElement;
public submit: HTMLButtonElement;
public typing: HTMLLIElement;
public conversation: HTMLUListElement;
private options: IChatOptions;
private inputValue: string;
constructor(isMobile: boolean, options: IChatOptions) {
this.isMobile = isMobile;
this.options = options;
this.chat = this.createChat();
this.typing = this.createTyping();
this.conversation = this.createConversation();
this.textArea = this.createTextarea();
this.inputText = this.createInput();
this.input = this.textArea;
this.submit = this.createSubmit();
this.form = this.createForm();
this.conversation.appendChild(this.typing);
this.chat.appendChild(this.conversation);
this.chat.appendChild(this.form);
this.inputValue = '';
}
public createSingleChoiceMessage(
rule: IRule,
onSelected: (label: string, value: string) => void
) {
if (rule.options.length) {
this.disableForm(this.options.inputPlaceholderSingleChoice);
return this.createBubbleMessage(rule, (btn, list) => {
list.remove();
this.enableForm();
onSelected(
btn.getAttribute('data-label'),
btn.getAttribute('data-value')
);
});
}
return document.createElement('div') as HTMLDivElement;
}
public createBubbleButton(
option: IRuleOption,
onClick: (btn: HTMLButtonElement) => void,
opts?: { className?: string }
) {
const btn = document.createElement('button') as HTMLButtonElement;
btn.className = 'yvebot-message-bubbleBtn';
if (opts && opts.className) {
btn.classList.add(opts.className);
}
btn.onclick = () => onClick(btn);
const { value, label } = option;
btn.setAttribute(
'data-value',
String((value === undefined ? label : value) || '')
);
btn.setAttribute(
'data-label',
String((label === undefined ? value : label) || '')
);
btn.textContent = btn.getAttribute('data-label');
return btn;
}
public disableForm(placeholder: string) {
this.submit.disabled = true;
this.input.disabled = true;
this.input.placeholder = placeholder;
this.inputValue = this.input.value;
this.input.value = '';
}
public enableForm() {
this.submit.disabled = false;
this.input.disabled = false;
this.input.placeholder = this.options.inputPlaceholder;
this.input.value = this.inputValue;
this.inputValue = '';
if (this.options.autoFocus) {
this.input.focus();
if (this.isMobile) {
// avoid losing scroll position on toggle form
setTimeout(() => this.scrollDown(0, null, true), 500);
}
}
}
public createBubbleMessage(
rule: IRule,
onClick: (btn: HTMLButtonElement, list: HTMLDivElement) => void
) {
const { maxOptions = 0 } = rule;
const { moreOptionsLabel: label } = this.options;
const bubbles = document.createElement('div') as HTMLDivElement;
bubbles.className = `yvebot-message-bubbles yvebot-ruleType-${rule.type}`;
const createButtonsPaginator = (options: IRuleOption[], start = 0) => {
const end = !!maxOptions ? start + maxOptions - 1 : options.length;
options.slice(start, end).forEach((opt, idx) => {
const bubble = this.createBubbleButton(opt, btn => {
onClick(btn, bubbles);
if (rule.type !== 'MultipleChoice') {
this.scrollDown(0, null, true);
}
});
bubbles.appendChild(bubble);
if (end < options.length && idx === maxOptions - 2) {
const moreBtn = this.createBubbleButton(
{ label },
() => {
createButtonsPaginator(options, end);
moreBtn.remove();
},
{ className: 'yvebot-message-bubbleMoreOptions' }
);
bubbles.appendChild(moreBtn);
}
});
};
createButtonsPaginator(rule.options);
return bubbles;
}
public createMultipleChoiceMessage(
rule: IRule,
onDone: (label: string[], value: string[]) => void
) {
const message = document.createElement('div') as HTMLDivElement;
if (rule.options.length) {
const done = document.createElement('button') as HTMLButtonElement;
done.textContent = this.options.doneMultipleChoiceLabel;
done.className = 'yvebot-message-bubbleDone';
done.style.display = 'none';
const self = this;
done.onclick = () => {
const bubbles = done.previousElementSibling;
const selected = bubbles.querySelectorAll(
'.yvebot-message-bubbleBtn.selected'
);
const label = utils
.nodeListToArray(selected)
.map(b => b.getAttribute('data-label'));
const value = utils
.nodeListToArray(selected)
.map(b => b.getAttribute('data-value'));
onDone(label, value);
bubbles.remove();
done.remove();
self.enableForm();
self.scrollDown(0, null, true);
};
const bubbleMsg = this.createBubbleMessage(rule, btn => {
btn.classList.toggle('selected');
if (
bubbleMsg.querySelectorAll('.yvebot-message-bubbleBtn.selected')
.length
) {
done.style.display = 'inline-block';
} else {
done.style.display = 'none';
}
});
this.disableForm(this.options.inputPlaceholderMultipleChoice);
message.appendChild(bubbleMsg);
message.appendChild(done);
}
return message;
}
public createChat() {
const chat = document.createElement('div') as HTMLDivElement;
chat.className = 'yvebot-chat';
return chat;
}
public createConversation() {
const conversation = document.createElement('ul') as HTMLUListElement;
conversation.className = 'yvebot-conversation';
return conversation;
}
public createTyping() {
const typing = document.createElement('div') as HTMLDivElement;
typing.className = 'yvebot-typing';
[1, 2, 3].forEach(() => {
const dot = document.createElement('span') as HTMLSpanElement;
dot.className = 'yvebot-typing-dot';
typing.appendChild(dot);
});
return this.createThread('BOT', typing, 'yvebot-thread-typing');
}
public createForm() {
const form = document.createElement('form') as HTMLFormElement;
form.className = 'yvebot-form';
form.appendChild(this.input);
form.appendChild(this.submit);
return form;
}
public createSubmit() {
const submit = document.createElement('button') as HTMLButtonElement;
submit.className = 'yvebot-form-submit';
submit.type = 'submit';
submit.textContent = this.options.submitLabel;
return submit;
}
public createInput() {
const input = document.createElement('input') as HTMLInputElement;
input.className = 'yvebot-form-input';
input.type = 'text';
input.placeholder = this.options.inputPlaceholder;
input.autocomplete = 'off';
return input;
}
public createTextarea() {
const textarea = document.createElement('textarea') as HTMLTextAreaElement;
textarea.className = 'yvebot-form-input';
textarea.placeholder = this.options.inputPlaceholder;
textarea.rows = 1;
// shift + enter
textarea.addEventListener('keydown', e => {
const code = e.key || e.keyCode || e.code;
const isEnter = ['Enter', 13].indexOf(code) >= 0;
if (isEnter && !e.shiftKey) {
e.preventDefault();
this.form.dispatchEvent(new Event('submit', { cancelable: true }));
}
});
// autosize
textarea.addEventListener('input', e => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = `${target.scrollHeight}px`;
});
return textarea;
}
public createThread(
source: ChatMessageSource,
content: HTMLElement,
customClass?: string
) {
const thread = document.createElement('li') as HTMLLIElement;
thread.className = `yvebot-thread yvebot-thread-${source.toLowerCase()}`;
if (customClass) {
thread.classList.add(customClass);
}
thread.appendChild(content);
return thread;
}
public setInputType(inputType: 'inputText' | 'textarea') {
const element = {
inputText: this.inputText,
textarea: this.textArea,
}[inputType];
if (this.input !== element) {
this.form.replaceChild(element, this.input);
this.input = element;
}
if (this.options.autoFocus) {
this.input.focus();
}
}
public appendThread(
source: ChatMessageSource,
conversation: HTMLUListElement,
thread: HTMLLIElement
) {
this.scrollDown(
thread.offsetHeight,
() => conversation.insertBefore(thread, this.typing),
source === 'USER'
);
}
public scrollDown(
offset: number,
callback: () => void | null,
force = false
) {
/*
* Avoid breakdown of reading when user changes the scroll and a new thread is appended
*/
const isBottom =
this.conversation.scrollHeight -
this.conversation.scrollTop -
this.conversation.offsetHeight -
offset <=
0;
if (callback) {
callback();
}
/* istanbul ignore next */
if (isBottom || force) {
this.conversation.scrollTop = this.conversation.scrollHeight;
}
}
public createTextMessage(answer: Answer | Answer[], senderName?: string) {
const { timestampable, timestampFormatter } = this.options;
let text: string;
if (answer instanceof Array) {
const answers = (answer as string[]).map(String);
text = utils.arrayToString(answers, this.options.andSeparatorText);
} else {
text = String(answer);
}
const bubble = document.createElement('div') as HTMLDivElement;
bubble.className = 'yvebot-bubble';
if (senderName) {
const name = document.createElement('div') as HTMLDivElement;
name.className = 'yvebot-sender';
name.innerHTML = senderName;
bubble.appendChild(name);
}
const message = document.createElement('div') as HTMLDivElement;
message.className = 'yvebot-message';
message.innerHTML = text;
bubble.appendChild(message);
if (timestampable) {
const timestamp = document.createElement('div') as HTMLDivElement;
timestamp.className = 'yvebot-timestamp';
timestamp.innerHTML = timestampFormatter(Date.now());
bubble.appendChild(timestamp);
}
return bubble;
}
} | the_stack |
import * as assert from 'assert';
import { parse, parsePlain } from '../src/mfm/parse';
import { toHtml } from '../src/mfm/toHtml';
import { createTree as tree, createLeaf as leaf, MfmTree } from '../src/mfm/prelude';
import { removeOrphanedBrackets } from '../src/mfm/language';
function text(text: string): MfmTree {
return leaf('text', { text });
}
describe('createLeaf', () => {
it('creates leaf', () => {
assert.deepStrictEqual(leaf('text', { text: 'abc' }), {
node: {
type: 'text',
props: {
text: 'abc'
}
},
children: [],
});
});
});
describe('createTree', () => {
it('creates tree', () => {
const t = tree('tree', [
leaf('left', { a: 2 }),
leaf('right', { b: 'hi' })
], {
c: 4
});
assert.deepStrictEqual(t, {
node: {
type: 'tree',
props: {
c: 4
}
},
children: [
leaf('left', { a: 2 }),
leaf('right', { b: 'hi' })
],
});
});
});
describe('removeOrphanedBrackets', () => {
it('single (contained)', () => {
const input = '(foo)';
const expected = '(foo)';
const actual = removeOrphanedBrackets(input);
assert.deepStrictEqual(actual, expected);
});
it('single (head)', () => {
const input = '(foo)bar';
const expected = '(foo)bar';
const actual = removeOrphanedBrackets(input);
assert.deepStrictEqual(actual, expected);
});
it('single (tail)', () => {
const input = 'foo(bar)';
const expected = 'foo(bar)';
const actual = removeOrphanedBrackets(input);
assert.deepStrictEqual(actual, expected);
});
it('a', () => {
const input = '(foo';
const expected = '';
const actual = removeOrphanedBrackets(input);
assert.deepStrictEqual(actual, expected);
});
it('b', () => {
const input = ')foo';
const expected = '';
const actual = removeOrphanedBrackets(input);
assert.deepStrictEqual(actual, expected);
});
it('nested', () => {
const input = 'foo(「(bar)」)';
const expected = 'foo(「(bar)」)';
const actual = removeOrphanedBrackets(input);
assert.deepStrictEqual(actual, expected);
});
it('no brackets', () => {
const input = 'foo';
const expected = 'foo';
const actual = removeOrphanedBrackets(input);
assert.deepStrictEqual(actual, expected);
});
it('with foreign bracket (single)', () => {
const input = 'foo(bar))';
const expected = 'foo(bar)';
const actual = removeOrphanedBrackets(input);
assert.deepStrictEqual(actual, expected);
});
it('with foreign bracket (open)', () => {
const input = 'foo(bar';
const expected = 'foo';
const actual = removeOrphanedBrackets(input);
assert.deepStrictEqual(actual, expected);
});
it('with foreign bracket (close)', () => {
const input = 'foo)bar';
const expected = 'foo';
const actual = removeOrphanedBrackets(input);
assert.deepStrictEqual(actual, expected);
});
it('with foreign bracket (close and open)', () => {
const input = 'foo)(bar';
const expected = 'foo';
const actual = removeOrphanedBrackets(input);
assert.deepStrictEqual(actual, expected);
});
it('various bracket type', () => {
const input = 'foo「(bar)」(';
const expected = 'foo「(bar)」';
const actual = removeOrphanedBrackets(input);
assert.deepStrictEqual(actual, expected);
});
it('intersected', () => {
const input = 'foo(「)」';
const expected = 'foo(「)」';
const actual = removeOrphanedBrackets(input);
assert.deepStrictEqual(actual, expected);
});
});
describe('MFM', () => {
it('can be analyzed', () => {
const tokens = parse('@himawari @hima_sub@namori.net お腹ペコい :cat: #yryr');
assert.deepStrictEqual(tokens, [
leaf('mention', {
acct: '@himawari',
canonical: '@himawari',
username: 'himawari',
host: null
}),
text(' '),
leaf('mention', {
acct: '@hima_sub@namori.net',
canonical: '@hima_sub@namori.net',
username: 'hima_sub',
host: 'namori.net'
}),
text(' お腹ペコい '),
leaf('emoji', { name: 'cat' }),
text(' '),
leaf('hashtag', { hashtag: 'yryr' }),
]);
});
describe('elements', () => {
describe('bold', () => {
it('simple', () => {
const tokens = parse('**foo**');
assert.deepStrictEqual(tokens, [
tree('bold', [
text('foo')
], {}),
]);
});
it('with other texts', () => {
const tokens = parse('bar**foo**bar');
assert.deepStrictEqual(tokens, [
text('bar'),
tree('bold', [
text('foo')
], {}),
text('bar'),
]);
});
it('with underscores', () => {
const tokens = parse('__foo__');
assert.deepStrictEqual(tokens, [
tree('bold', [
text('foo')
], {}),
]);
});
it('with underscores (ensure it allows alphabet only)', () => {
const tokens = parse('(=^・__________・^=)');
assert.deepStrictEqual(tokens, [
text('(=^・__________・^=)')
]);
});
it('mixed syntax', () => {
const tokens = parse('**foo__');
assert.deepStrictEqual(tokens, [
text('**foo__'),
]);
});
it('mixed syntax', () => {
const tokens = parse('__foo**');
assert.deepStrictEqual(tokens, [
text('__foo**'),
]);
});
});
it('big', () => {
const tokens = parse('***Strawberry*** Pasta');
assert.deepStrictEqual(tokens, [
tree('big', [
text('Strawberry')
], {}),
text(' Pasta'),
]);
});
it('small', () => {
const tokens = parse('<small>smaller</small>');
assert.deepStrictEqual(tokens, [
tree('small', [
text('smaller')
], {}),
]);
});
it('flip', () => {
const tokens = parse('<flip>foo</flip>');
assert.deepStrictEqual(tokens, [
tree('flip', [
text('foo')
], {}),
]);
});
describe('spin', () => {
it('text', () => {
const tokens = parse('<spin>foo</spin>');
assert.deepStrictEqual(tokens, [
tree('spin', [
text('foo')
], {
attr: null
}),
]);
});
it('emoji', () => {
const tokens = parse('<spin>:foo:</spin>');
assert.deepStrictEqual(tokens, [
tree('spin', [
leaf('emoji', { name: 'foo' })
], {
attr: null
}),
]);
});
it('with attr', () => {
const tokens = parse('<spin left>:foo:</spin>');
assert.deepStrictEqual(tokens, [
tree('spin', [
leaf('emoji', { name: 'foo' })
], {
attr: 'left'
}),
]);
});
/*
it('multi', () => {
const tokens = parse('<spin>:foo:</spin><spin>:foo:</spin>');
assert.deepStrictEqual(tokens, [
tree('spin', [
leaf('emoji', { name: 'foo' })
], {
attr: null
}),
tree('spin', [
leaf('emoji', { name: 'foo' })
], {
attr: null
}),
]);
});
it('nested', () => {
const tokens = parse('<spin><spin>:foo:</spin></spin>');
assert.deepStrictEqual(tokens, [
tree('spin', [
tree('spin', [
leaf('emoji', { name: 'foo' })
], {
attr: null
}),
], {
attr: null
}),
]);
});
*/
});
it('jump', () => {
const tokens = parse('<jump>:foo:</jump>');
assert.deepStrictEqual(tokens, [
tree('jump', [
leaf('emoji', { name: 'foo' })
], {}),
]);
});
describe('motion', () => {
it('by triple brackets', () => {
const tokens = parse('(((foo)))');
assert.deepStrictEqual(tokens, [
tree('motion', [
text('foo')
], {}),
]);
});
it('by triple brackets (with other texts)', () => {
const tokens = parse('bar(((foo)))bar');
assert.deepStrictEqual(tokens, [
text('bar'),
tree('motion', [
text('foo')
], {}),
text('bar'),
]);
});
it('by <motion> tag', () => {
const tokens = parse('<motion>foo</motion>');
assert.deepStrictEqual(tokens, [
tree('motion', [
text('foo')
], {}),
]);
});
it('by <motion> tag (with other texts)', () => {
const tokens = parse('bar<motion>foo</motion>bar');
assert.deepStrictEqual(tokens, [
text('bar'),
tree('motion', [
text('foo')
], {}),
text('bar'),
]);
});
});
describe('mention', () => {
it('local', () => {
const tokens = parse('@himawari foo');
assert.deepStrictEqual(tokens, [
leaf('mention', {
acct: '@himawari',
canonical: '@himawari',
username: 'himawari',
host: null
}),
text(' foo')
]);
});
it('remote', () => {
const tokens = parse('@hima_sub@namori.net foo');
assert.deepStrictEqual(tokens, [
leaf('mention', {
acct: '@hima_sub@namori.net',
canonical: '@hima_sub@namori.net',
username: 'hima_sub',
host: 'namori.net'
}),
text(' foo')
]);
});
it('remote punycode', () => {
const tokens = parse('@hima_sub@xn--q9j5bya.xn--zckzah foo');
assert.deepStrictEqual(tokens, [
leaf('mention', {
acct: '@hima_sub@xn--q9j5bya.xn--zckzah',
canonical: '@hima_sub@なもり.テスト',
username: 'hima_sub',
host: 'xn--q9j5bya.xn--zckzah'
}),
text(' foo')
]);
});
it('ignore', () => {
const tokens = parse('idolm@ster');
assert.deepStrictEqual(tokens, [
text('idolm@ster')
]);
const tokens2 = parse('@a\n@b\n@c');
assert.deepStrictEqual(tokens2, [
leaf('mention', {
acct: '@a',
canonical: '@a',
username: 'a',
host: null
}),
text('\n'),
leaf('mention', {
acct: '@b',
canonical: '@b',
username: 'b',
host: null
}),
text('\n'),
leaf('mention', {
acct: '@c',
canonical: '@c',
username: 'c',
host: null
})
]);
const tokens3 = parse('**x**@a');
assert.deepStrictEqual(tokens3, [
tree('bold', [
text('x')
], {}),
leaf('mention', {
acct: '@a',
canonical: '@a',
username: 'a',
host: null
})
]);
const tokens4 = parse('@\n@v\n@veryverylongusername');
assert.deepStrictEqual(tokens4, [
text('@\n'),
leaf('mention', {
acct: '@v',
canonical: '@v',
username: 'v',
host: null
}),
text('\n'),
leaf('mention', {
acct: '@veryverylongusername',
canonical: '@veryverylongusername',
username: 'veryverylongusername',
host: null
}),
]);
});
});
describe('hashtag', () => {
it('simple', () => {
const tokens = parse('#alice');
assert.deepStrictEqual(tokens, [
leaf('hashtag', { hashtag: 'alice' })
]);
});
it('after line break', () => {
const tokens = parse('foo\n#alice');
assert.deepStrictEqual(tokens, [
text('foo\n'),
leaf('hashtag', { hashtag: 'alice' })
]);
});
it('with text', () => {
const tokens = parse('Strawberry Pasta #alice');
assert.deepStrictEqual(tokens, [
text('Strawberry Pasta '),
leaf('hashtag', { hashtag: 'alice' })
]);
});
it('with text (zenkaku)', () => {
const tokens = parse('こんにちは#世界');
assert.deepStrictEqual(tokens, [
text('こんにちは'),
leaf('hashtag', { hashtag: '世界' })
]);
});
it('ignore comma and period', () => {
const tokens = parse('Foo #bar, baz #piyo.');
assert.deepStrictEqual(tokens, [
text('Foo '),
leaf('hashtag', { hashtag: 'bar' }),
text(', baz '),
leaf('hashtag', { hashtag: 'piyo' }),
text('.'),
]);
});
it('ignore exclamation mark', () => {
const tokens = parse('#Foo!');
assert.deepStrictEqual(tokens, [
leaf('hashtag', { hashtag: 'Foo' }),
text('!'),
]);
});
it('ignore colon', () => {
const tokens = parse('#Foo:');
assert.deepStrictEqual(tokens, [
leaf('hashtag', { hashtag: 'Foo' }),
text(':'),
]);
});
it('ignore single quote', () => {
const tokens = parse('#foo\'');
assert.deepStrictEqual(tokens, [
leaf('hashtag', { hashtag: 'foo' }),
text('\''),
]);
});
it('ignore double quote', () => {
const tokens = parse('#foo"');
assert.deepStrictEqual(tokens, [
leaf('hashtag', { hashtag: 'foo' }),
text('"'),
]);
});
it('ignore square brackets', () => {
const tokens = parse('#foo]');
assert.deepStrictEqual(tokens, [
leaf('hashtag', { hashtag: 'foo' }),
text(']'),
]);
});
it('ignore 】', () => {
const tokens = parse('#foo】');
assert.deepStrictEqual(tokens, [
leaf('hashtag', { hashtag: 'foo' }),
text('】'),
]);
});
it('allow including number', () => {
const tokens = parse('#foo123');
assert.deepStrictEqual(tokens, [
leaf('hashtag', { hashtag: 'foo123' }),
]);
});
it('with brackets', () => {
const tokens1 = parse('(#foo)');
assert.deepStrictEqual(tokens1, [
text('('),
leaf('hashtag', { hashtag: 'foo' }),
text(')'),
]);
const tokens2 = parse('「#foo」');
assert.deepStrictEqual(tokens2, [
text('「'),
leaf('hashtag', { hashtag: 'foo' }),
text('」'),
]);
});
it('with mixed brackets', () => {
const tokens = parse('「#foo(bar)」');
assert.deepStrictEqual(tokens, [
text('「'),
leaf('hashtag', { hashtag: 'foo(bar)' }),
text('」'),
]);
});
it('with brackets (space before)', () => {
const tokens1 = parse('(bar #foo)');
assert.deepStrictEqual(tokens1, [
text('(bar '),
leaf('hashtag', { hashtag: 'foo' }),
text(')'),
]);
const tokens2 = parse('「bar #foo」');
assert.deepStrictEqual(tokens2, [
text('「bar '),
leaf('hashtag', { hashtag: 'foo' }),
text('」'),
]);
});
it('disallow number only', () => {
const tokens = parse('#123');
assert.deepStrictEqual(tokens, [
text('#123'),
]);
});
it('disallow number only (with brackets)', () => {
const tokens = parse('(#123)');
assert.deepStrictEqual(tokens, [
text('(#123)'),
]);
});
it('ignore slash', () => {
const tokens = parse('#foo/bar');
assert.deepStrictEqual(tokens, [
leaf('hashtag', { hashtag: 'foo' }),
text('/bar'),
]);
});
});
describe('quote', () => {
it('basic', () => {
const tokens1 = parse('> foo');
assert.deepStrictEqual(tokens1, [
tree('quote', [
text('foo')
], {})
]);
const tokens2 = parse('>foo');
assert.deepStrictEqual(tokens2, [
tree('quote', [
text('foo')
], {})
]);
});
it('series', () => {
const tokens = parse('> foo\n\n> bar');
assert.deepStrictEqual(tokens, [
tree('quote', [
text('foo')
], {}),
text('\n'),
tree('quote', [
text('bar')
], {}),
]);
});
it('trailing line break', () => {
const tokens1 = parse('> foo\n');
assert.deepStrictEqual(tokens1, [
tree('quote', [
text('foo')
], {}),
]);
const tokens2 = parse('> foo\n\n');
assert.deepStrictEqual(tokens2, [
tree('quote', [
text('foo')
], {}),
text('\n')
]);
});
it('multiline', () => {
const tokens1 = parse('>foo\n>bar');
assert.deepStrictEqual(tokens1, [
tree('quote', [
text('foo\nbar')
], {})
]);
const tokens2 = parse('> foo\n> bar');
assert.deepStrictEqual(tokens2, [
tree('quote', [
text('foo\nbar')
], {})
]);
});
it('multiline with trailing line break', () => {
const tokens1 = parse('> foo\n> bar\n');
assert.deepStrictEqual(tokens1, [
tree('quote', [
text('foo\nbar')
], {}),
]);
const tokens2 = parse('> foo\n> bar\n\n');
assert.deepStrictEqual(tokens2, [
tree('quote', [
text('foo\nbar')
], {}),
text('\n')
]);
});
it('with before and after texts', () => {
const tokens = parse('before\n> foo\nafter');
assert.deepStrictEqual(tokens, [
text('before\n'),
tree('quote', [
text('foo')
], {}),
text('after'),
]);
});
it('multiple quotes', () => {
const tokens = parse('> foo\nbar\n\n> foo\nbar\n\n> foo\nbar');
assert.deepStrictEqual(tokens, [
tree('quote', [
text('foo')
], {}),
text('bar\n\n'),
tree('quote', [
text('foo')
], {}),
text('bar\n\n'),
tree('quote', [
text('foo')
], {}),
text('bar'),
]);
});
it('require line break before ">"', () => {
const tokens = parse('foo>bar');
assert.deepStrictEqual(tokens, [
text('foo>bar'),
]);
});
it('nested', () => {
const tokens = parse('>> foo\n> bar');
assert.deepStrictEqual(tokens, [
tree('quote', [
tree('quote', [
text('foo')
], {}),
text('bar')
], {})
]);
});
it('trim line breaks', () => {
const tokens = parse('foo\n\n>a\n>>b\n>>\n>>>\n>>>c\n>>>\n>d\n\n');
assert.deepStrictEqual(tokens, [
text('foo\n\n'),
tree('quote', [
text('a\n'),
tree('quote', [
text('b\n\n'),
tree('quote', [
text('\nc\n')
], {})
], {}),
text('d')
], {}),
text('\n'),
]);
});
});
describe('url', () => {
it('simple', () => {
const tokens = parse('https://example.com');
assert.deepStrictEqual(tokens, [
leaf('url', { url: 'https://example.com' })
]);
});
it('ignore trailing period', () => {
const tokens = parse('https://example.com.');
assert.deepStrictEqual(tokens, [
leaf('url', { url: 'https://example.com' }),
text('.')
]);
});
it('with comma', () => {
const tokens = parse('https://example.com/foo?bar=a,b');
assert.deepStrictEqual(tokens, [
leaf('url', { url: 'https://example.com/foo?bar=a,b' })
]);
});
it('ignore trailing comma', () => {
const tokens = parse('https://example.com/foo, bar');
assert.deepStrictEqual(tokens, [
leaf('url', { url: 'https://example.com/foo' }),
text(', bar')
]);
});
it('with brackets', () => {
const tokens = parse('https://example.com/foo(bar)');
assert.deepStrictEqual(tokens, [
leaf('url', { url: 'https://example.com/foo(bar)' })
]);
});
it('ignore parent brackets', () => {
const tokens = parse('(https://example.com/foo)');
assert.deepStrictEqual(tokens, [
text('('),
leaf('url', { url: 'https://example.com/foo' }),
text(')')
]);
});
it('ignore parent brackets 2', () => {
const tokens = parse('(foo https://example.com/foo)');
assert.deepStrictEqual(tokens, [
text('(foo '),
leaf('url', { url: 'https://example.com/foo' }),
text(')')
]);
});
it('ignore parent brackets with internal brackets', () => {
const tokens = parse('(https://example.com/foo(bar))');
assert.deepStrictEqual(tokens, [
text('('),
leaf('url', { url: 'https://example.com/foo(bar)' }),
text(')')
]);
});
it('ignore non-ascii characters contained url without angle brackets', () => {
const tokens = parse('https://大石泉すき.example.com');
assert.deepStrictEqual(tokens, [
text('https://大石泉すき.example.com')
]);
});
it('match non-ascii characters contained url with angle brackets', () => {
const tokens = parse('<https://大石泉すき.example.com>');
assert.deepStrictEqual(tokens, [
leaf('url', { url: 'https://大石泉すき.example.com' })
]);
});
});
describe('link', () => {
it('simple', () => {
const tokens = parse('[foo](https://example.com)');
assert.deepStrictEqual(tokens, [
tree('link', [
text('foo')
], { url: 'https://example.com', silent: false })
]);
});
it('simple (with silent flag)', () => {
const tokens = parse('?[foo](https://example.com)');
assert.deepStrictEqual(tokens, [
tree('link', [
text('foo')
], { url: 'https://example.com', silent: true })
]);
});
it('in text', () => {
const tokens = parse('before[foo](https://example.com)after');
assert.deepStrictEqual(tokens, [
text('before'),
tree('link', [
text('foo')
], { url: 'https://example.com', silent: false }),
text('after'),
]);
});
it('with brackets', () => {
const tokens = parse('[foo](https://example.com/foo(bar))');
assert.deepStrictEqual(tokens, [
tree('link', [
text('foo')
], { url: 'https://example.com/foo(bar)', silent: false })
]);
});
it('with parent brackets', () => {
const tokens = parse('([foo](https://example.com/foo(bar)))');
assert.deepStrictEqual(tokens, [
text('('),
tree('link', [
text('foo')
], { url: 'https://example.com/foo(bar)', silent: false }),
text(')')
]);
});
});
it('emoji', () => {
const tokens1 = parse(':cat:');
assert.deepStrictEqual(tokens1, [
leaf('emoji', { name: 'cat' })
]);
const tokens2 = parse(':cat::cat::cat:');
assert.deepStrictEqual(tokens2, [
leaf('emoji', { name: 'cat' }),
leaf('emoji', { name: 'cat' }),
leaf('emoji', { name: 'cat' })
]);
const tokens3 = parse('🍎');
assert.deepStrictEqual(tokens3, [
leaf('emoji', { emoji: '🍎' })
]);
});
describe('block code', () => {
it('simple', () => {
const tokens = parse('```\nvar x = "Strawberry Pasta";\n```');
assert.deepStrictEqual(tokens, [
leaf('blockCode', { code: 'var x = "Strawberry Pasta";', lang: null })
]);
});
it('can specify language', () => {
const tokens = parse('``` json\n{ "x": 42 }\n```');
assert.deepStrictEqual(tokens, [
leaf('blockCode', { code: '{ "x": 42 }', lang: 'json' })
]);
});
it('require line break before "```"', () => {
const tokens = parse('before```\nfoo\n```');
assert.deepStrictEqual(tokens, [
text('before'),
leaf('inlineCode', { code: '`' }),
text('\nfoo\n'),
leaf('inlineCode', { code: '`' })
]);
});
it('series', () => {
const tokens = parse('```\nfoo\n```\n```\nbar\n```\n```\nbaz\n```');
assert.deepStrictEqual(tokens, [
leaf('blockCode', { code: 'foo', lang: null }),
leaf('blockCode', { code: 'bar', lang: null }),
leaf('blockCode', { code: 'baz', lang: null }),
]);
});
it('ignore internal marker', () => {
const tokens = parse('```\naaa```bbb\n```');
assert.deepStrictEqual(tokens, [
leaf('blockCode', { code: 'aaa```bbb', lang: null })
]);
});
it('trim after line break', () => {
const tokens = parse('```\nfoo\n```\nbar');
assert.deepStrictEqual(tokens, [
leaf('blockCode', { code: 'foo', lang: null }),
text('bar')
]);
});
});
describe('inline code', () => {
it('simple', () => {
const tokens = parse('`var x = "Strawberry Pasta";`');
assert.deepStrictEqual(tokens, [
leaf('inlineCode', { code: 'var x = "Strawberry Pasta";' })
]);
});
it('disallow line break', () => {
const tokens = parse('`foo\nbar`');
assert.deepStrictEqual(tokens, [
text('`foo\nbar`')
]);
});
it('disallow ´', () => {
const tokens = parse('`foo´bar`');
assert.deepStrictEqual(tokens, [
text('`foo´bar`')
]);
});
});
it('mathInline', () => {
const fomula = 'x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}';
const content = `\\(${fomula}\\)`;
const tokens = parse(content);
assert.deepStrictEqual(tokens, [
leaf('mathInline', { formula: fomula })
]);
});
describe('mathBlock', () => {
it('simple', () => {
const fomula = 'x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a}';
const content = `\\[\n${fomula}\n\\]`;
const tokens = parse(content);
assert.deepStrictEqual(tokens, [
leaf('mathBlock', { formula: fomula })
]);
});
});
it('search', () => {
const tokens1 = parse('a b c 検索');
assert.deepStrictEqual(tokens1, [
leaf('search', { content: 'a b c 検索', query: 'a b c' })
]);
const tokens2 = parse('a b c Search');
assert.deepStrictEqual(tokens2, [
leaf('search', { content: 'a b c Search', query: 'a b c' })
]);
const tokens3 = parse('a b c search');
assert.deepStrictEqual(tokens3, [
leaf('search', { content: 'a b c search', query: 'a b c' })
]);
const tokens4 = parse('a b c SEARCH');
assert.deepStrictEqual(tokens4, [
leaf('search', { content: 'a b c SEARCH', query: 'a b c' })
]);
});
describe('title', () => {
it('simple', () => {
const tokens = parse('【foo】');
assert.deepStrictEqual(tokens, [
tree('title', [
text('foo')
], {})
]);
});
it('require line break', () => {
const tokens = parse('a【foo】');
assert.deepStrictEqual(tokens, [
text('a【foo】')
]);
});
it('with before and after texts', () => {
const tokens = parse('before\n【foo】\nafter');
assert.deepStrictEqual(tokens, [
text('before\n'),
tree('title', [
text('foo')
], {}),
text('after')
]);
});
it('ignore multiple title blocks', () => {
const tokens = parse('【foo】bar【baz】');
assert.deepStrictEqual(tokens, [
text('【foo】bar【baz】')
]);
});
it('disallow linebreak in title', () => {
const tokens = parse('【foo\nbar】');
assert.deepStrictEqual(tokens, [
text('【foo\nbar】')
]);
});
});
describe('center', () => {
it('simple', () => {
const tokens = parse('<center>foo</center>');
assert.deepStrictEqual(tokens, [
tree('center', [
text('foo')
], {}),
]);
});
});
describe('strike', () => {
it('simple', () => {
const tokens = parse('~~foo~~');
assert.deepStrictEqual(tokens, [
tree('strike', [
text('foo')
], {}),
]);
});
});
describe('italic', () => {
it('<i>', () => {
const tokens = parse('<i>foo</i>');
assert.deepStrictEqual(tokens, [
tree('italic', [
text('foo')
], {}),
]);
});
it('underscore', () => {
const tokens = parse('_foo_');
assert.deepStrictEqual(tokens, [
tree('italic', [
text('foo')
], {}),
]);
});
it('simple with asterix', () => {
const tokens = parse('*foo*');
assert.deepStrictEqual(tokens, [
tree('italic', [
text('foo')
], {}),
]);
});
it('exlude emotes', () => {
const tokens = parse('*.*');
assert.deepStrictEqual(tokens, [
text('*.*'),
]);
});
it('mixed', () => {
const tokens = parse('_foo*');
assert.deepStrictEqual(tokens, [
text('_foo*'),
]);
});
it('mixed', () => {
const tokens = parse('*foo_');
assert.deepStrictEqual(tokens, [
text('*foo_'),
]);
});
it('ignore snake_case string', () => {
const tokens = parse('foo_bar_baz');
assert.deepStrictEqual(tokens, [
text('foo_bar_baz'),
]);
});
});
});
describe('plainText', () => {
it('text', () => {
const tokens = parsePlain('foo');
assert.deepStrictEqual(tokens, [
text('foo'),
]);
});
it('emoji', () => {
const tokens = parsePlain(':foo:');
assert.deepStrictEqual(tokens, [
leaf('emoji', { name: 'foo' })
]);
});
it('emoji in text', () => {
const tokens = parsePlain('foo:bar:baz');
assert.deepStrictEqual(tokens, [
text('foo'),
leaf('emoji', { name: 'bar' }),
text('baz'),
]);
});
it('disallow other syntax', () => {
const tokens = parsePlain('foo **bar** baz');
assert.deepStrictEqual(tokens, [
text('foo **bar** baz'),
]);
});
});
describe('toHtml', () => {
it('br', () => {
const input = 'foo\nbar\nbaz';
const output = '<p><span>foo<br>bar<br>baz</span></p>';
assert.equal(toHtml(parse(input)), output);
});
it('br alt', () => {
const input = 'foo\r\nbar\rbaz';
const output = '<p><span>foo<br>bar<br>baz</span></p>';
assert.equal(toHtml(parse(input)), output);
});
});
it('code block with quote', () => {
const tokens = parse('> foo\n```\nbar\n```');
assert.deepStrictEqual(tokens, [
tree('quote', [
text('foo')
], {}),
leaf('blockCode', { code: 'bar', lang: null })
]);
});
it('quote between two code blocks', () => {
const tokens = parse('```\nbefore\n```\n> foo\n```\nafter\n```');
assert.deepStrictEqual(tokens, [
leaf('blockCode', { code: 'before', lang: null }),
tree('quote', [
text('foo')
], {}),
leaf('blockCode', { code: 'after', lang: null })
]);
});
}); | the_stack |
import P from 'parsimmon'
import { MARPL, Annotation, Argument, Assignment, Assignments, Atom, Dot,
FunctionTerm, ObjectTerm, ParseResult, Placeholder, RelationalAtom,
Rule, SetTerm, SetVariable, SimpleNamed, Specifier, SpecifierAtom, SpecifierTerm,
SpecifierType, SpecifierExpressionType, isSetVariable, isSomeVariable, LiteralExpression,
isRelationalAtom, isSetAtom, isClosedSpecifier, isSpecifier, isSpecifierAtom } from './types'
import { verify } from './ast'
type Language = P.TypedLanguage<MARPL>
function word(w: string) {
return P.string(w).trim(P.regexp(/\s*/m))
}
function assignment(r: Language, rhs: P.Parser<ObjectTerm | Dot | Placeholder>) {
return P.seqObj<Assignment>(['attribute', r.ObjectTerm],
r.equals,
['value', rhs],
).thru(type('assignment'))
}
function specifierType(typeName: SpecifierType): 'open-specifier' | 'closed-specifier' {
// be a bit verbose to satisfy the type checker
if (typeName === 'open') {
return 'open-specifier'
}
return 'closed-specifier'
}
function specifier(r: Language,
opening: P.Parser<string>, closing: P.Parser<string>,
typeName: SpecifierType): P.Parser<Specifier> {
return P.seqObj<Assignments>(opening,
['assignments',
P.sepBy<Assignment, string>(
r.AssignmentWithPlaceholder,
r.comma)],
closing).thru(type(specifierType(typeName)))
}
function specifierExpression(r: Language, typeName: SpecifierExpressionType) {
return P.seqObj<{ lhs: SpecifierTerm,
rhs: SpecifierTerm,
}>(r.openingParenthesis,
['lhs', r.SpecifierTerm],
r[typeName],
['rhs', r.SpecifierTerm],
r.closingParenthesis,
).map((obj) => {
return {
type: typeName,
specifiers: [obj.lhs, obj.rhs],
}
})
}
function relationalAtom(r: Language, setTerm: P.Parser<Annotation>): P.Parser<RelationalAtom> {
return P.seqObj<{ subject: ObjectTerm,
predicate: ObjectTerm,
object: ObjectTerm,
annotation: Annotation,
}>(r.openingParenthesis,
['subject', r.ObjectTerm],
r.dot,
['predicate', r.ObjectTerm],
r.equals,
['object', r.ObjectTerm],
r.closingParenthesis,
r.at,
['annotation', setTerm],
).map((obj) => {
return {
type: 'relational-atom',
predicate: obj.predicate,
arguments: [obj.subject, obj.object],
annotation: obj.annotation,
}
})
}
function type<T extends ParseResult, U extends T>(typeName: U['type']): (parser: P.Parser<T>) => P.Parser<U> {
return (parser) => {
return (parser as P.Parser<U>).map((obj) => {
obj.type = typeName
return obj
})
}
}
const MARPL = P.createLanguage<MARPL>({
at: () => word('@'),
dot: () => word('.'),
comma: () => word(','),
colon: () => word(':'),
arrow: () => word('->'),
union: () => word('||'),
equals: () => word('='),
difference: () => word('\\'),
intersection: () => word('&&'),
objectName: () => P.regexp(/[PQ]\d+/),
literalExpression: () => P.regexp(/"[^"]*"/),
variableName: () => P.regexp(/\?[a-zA-Z]\w*/),
openingBrace: () => word('{'),
closingBrace: () => word('}'),
openingFloor: () => word('('),
closingFloor: () => word(')'),
openingBracket: () => word('['),
closingBracket: () => word(']'),
openingParenthesis: () => word('('),
closingParenthesis: () => word(')'),
someVariable: (r: Language) => {
return P.seqObj<SimpleNamed>(['name', r.variableName])
.desc('a variable')
.thru(type('some-variable'))
},
ObjectVariable: (r: Language) => {
return P.seqObj<SimpleNamed>(['name', r.variableName])
.desc('an object variable')
.thru(type('variable'))
},
ObjectLiteral: (r: Language) => {
return P.seqObj<SimpleNamed>(['name', r.objectName])
.desc('an object literal')
.thru(type('literal'))
},
LiteralExpression: (r: Language) => {
return P.seqObj<SimpleNamed>(['name', r.literalExpression])
.desc('a quoted literal expression')
.thru(type('literal-expression'))
},
ObjectTerm: (r: Language) => {
return P.alt(
r.ObjectVariable,
r.ObjectLiteral,
)
},
ObjectTermOrLiteral: (r: Language) => {
return P.alt(
r.literalExpression,
r.ObjectTerm,
)
},
SetLiteral: (r: Language) => {
return P.seqObj<Assignments>(r.openingBrace,
['assignments', P.sepBy(r.Assignment, r.comma)],
r.closingBrace,
)
.thru(type('set-term'))
},
SetVariable: (r: Language) => {
return P.seqObj<SimpleNamed>(['name', r.variableName])
.desc('a set variable')
.thru(type('set-variable'))
},
SetTerm: (r: Language) => {
return P.alt(
r.SetLiteral,
r.SetVariable,
specifier(r, r.openingFloor, r.closingFloor, 'open'),
specifier(r, r.openingBracket, r.closingBracket, 'closed'),
)
},
DottedSetTerm: (r: Language) => {
return P.alt(
P.seqObj<Assignments>(r.openingBrace,
['assignments', P.sepBy(r.DottedAssignment, r.comma)],
r.closingBrace,
).thru(type('set-term')),
P.seqObj<Assignments>(r.openingBracket,
['assignments', P.sepBy(r.DottedAssignment, r.comma)],
r.closingBracket,
).thru(type('closed-specifier')),
)
},
FunctionTerm: (r: Language) => {
return P.seqObj<FunctionTerm>(['name', P.regexp(/[a-zA-Z]\w*/)],
r.openingParenthesis,
['arguments',
P.sepBy<Argument,
string>(P.alt(r.ObjectLiteral,
r.SetLiteral,
r.someVariable),
r.comma)],
r.closingParenthesis,
).thru(type('function-term'))
},
RelationalAtom: (r: Language) => {
return relationalAtom(r, r.SetTerm)
},
RelationalAtomWithFunctionTerm: (r: Language) => {
return relationalAtom(r, r.FunctionTerm)
},
RelationalAtomWithDots: (r: Language) => {
return relationalAtom(r, r.DottedSetTerm)
},
SimpleRelationalAtom: (r: Language) => {
return P.seqObj<{ subject: ObjectTerm,
predicate: ObjectTerm,
object: ObjectTerm | LiteralExpression,
}>(r.openingParenthesis,
['subject', r.ObjectTerm],
r.dot,
['predicate', r.ObjectTerm],
r.equals,
['object', r.ObjectTermOrLiteral],
r.closingParenthesis,
).map((obj) => {
return {
type: 'relational-atom',
predicate: obj.predicate,
arguments: [obj.subject, obj.object],
annotation: {
type: 'closed-specifier',
assignments: [],
},
}
})
},
Dot: (r: Language) => {
return P.seqObj<Dot>(['fromSpecifier', r.SetVariable],
r.dot,
['item', r.ObjectLiteral],
).thru(type('dot'))
},
Placeholder: () => {
return P.alt(
word('*').map(() => {
return {
type: 'star' as const,
}
}),
word('+').map(() => {
return {
type: 'plus' as const,
}
})).desc('a placeholder')
},
Assignment: (r: Language) => {
return assignment(r, r.ObjectTerm)
},
AssignmentWithPlaceholder: (r: Language) => {
return assignment(r, P.alt(
r.ObjectTerm,
r.Placeholder,
))
},
DottedAssignment: (r: Language) => {
return assignment(r, P.alt(
r.Dot,
r.ObjectTerm,
r.Placeholder,
))
},
Specifier: (r: Language) => {
return P.alt(
specifier(r, r.openingFloor, r.closingFloor, 'open'),
specifier(r, r.openingBracket, r.closingBracket, 'closed'),
)
},
SpecifierExpression: (r: Language) => {
return P.alt(
specifierExpression(r, 'union'),
specifierExpression(r, 'intersection'),
specifierExpression(r, 'difference'),
)
},
SpecifierTerm: (r: Language) => {
return P.alt(r.SpecifierExpression,
r.Specifier)
},
SpecifierAtom: (r: Language) => {
return P.seqObj<SpecifierAtom>(['set', r.SetVariable],
r.colon,
['specifier', r.SpecifierTerm])
.thru(type('specifier-atom'))
},
Rule: (r: Language) => {
return P.seqObj<Rule>(['body', r.Body],
r.arrow,
['head', r.Head])
.thru(type('rule'))
},
Head: (r: Language) => {
return P.alt(
r.RelationalAtomWithDots,
r.RelationalAtom,
r.SimpleRelationalAtom,
r.RelationalAtomWithFunctionTerm,
)
},
Body: (r: Language) => {
return P.sepBy<RelationalAtom, string>(
P.alt(
r.RelationalAtom,
r.SimpleRelationalAtom,
r.SpecifierAtom),
r.comma)
},
})
export function parseRule(rule: string, schema?: object) {
const parsed = Object.freeze(rewrite(MARPL.Rule.tryParse(rule)))
if (schema) {
verify(schema, parsed)
}
return parsed
}
function rewrite(ast: Rule) {
if (ast.head.annotation.type === 'function-term') {
// disambiguate variable names in the function term
arguments: for (const [arg, argument] of ast.head.annotation.arguments.entries()) {
if (isSomeVariable(argument)) {
// find a binding for this variable in the body
const name = argument.name
for (const atom of ast.body) {
if (isRelationalAtom(atom)) {
const annotation = atom.annotation
if (isSetVariable(annotation) &&
annotation.name === name) {
ast.head.annotation.arguments[arg].type = 'set-variable'
continue arguments
}
if (atom.predicate.type === 'variable' &&
atom.predicate.name === name) {
ast.head.annotation.arguments[arg].type = 'variable'
continue arguments
}
for (const property of atom.arguments) {
if (property.type === 'variable' &&
property.name === name) {
ast.head.annotation.arguments[arg].type = 'variable'
continue arguments
}
}
} else if (isSetAtom(atom)) {
if (atom.set.name === name) {
ast.head.annotation.arguments[arg].type = 'set-variable'
continue arguments
}
} else if (isSpecifierAtom(atom)) {
if (atom.set.name === name) {
ast.head.annotation.arguments[arg].type = 'set-variable'
}
if (isSpecifier(atom.specifier)) {
for (const assign of atom.specifier.assignments) {
if (assign.attribute.name === name ||
('name' in assign.value && assign.value.name === name)) {
ast.head.annotation.arguments[arg].type = 'variable'
continue arguments
}
}
}
}
}
}
if (isSomeVariable(argument)) {
// this variable does not occour within the body, as is required
throw new SyntaxError(`Variable \`${name} is unbound in rule: ${ast}`)
}
}
}
if (isClosedSpecifier(ast.head.annotation)) {
// just treat it as a set literal
((ast.head.annotation as unknown) as SetTerm).type = 'set-term'
}
const atoms: Atom[] = ast.body
// push specifiers into specifier atoms
for (const [idx, atom] of ast.body.entries()) {
if (isRelationalAtom(atom) && isSpecifier(atom.annotation)) {
const variable = { type: 'set-variable',
name: `?_body_spec_for_${atom}`,
} as const
atoms.push(specifierAtom(variable, atom.annotation))
{
// this needs to be a new block so that the following line
// doesn't turn the previous expression into a function call,
// which would result in a type error, since Array.push
// returns a Number, and those are not callable.
(ast.body[idx] as RelationalAtom).annotation = variable
}
}
}
ast.body = atoms
return ast
}
function specifierAtom(set: SetVariable,
specifier: SpecifierTerm): SpecifierAtom { // tslint:disable-line:no-shadowed-variable
return { type: 'specifier-atom',
set,
specifier,
}
}
function maybeParse(parser: P.Parser<any>, str: string) {
try {
parser.tryParse(str)
} catch (err) {
return false
}
return true
}
export function isVariableName(name: string) {
return maybeParse(MARPL.variableName, name)
}
export function isObjectName(name: string) {
return maybeParse(MARPL.objectName, name)
} | the_stack |
import * as util from "util";
import * as assert from "assert";
import { nanoid } from "nanoid";
import { MapSchema, Schema, type, ArraySchema, defineTypes, Reflection, Context } from "../src";
import { State, Player } from "./Schema";
describe("Edge cases", () => {
it("Schema should support up to 64 fields", () => {
const maxFields = 64;
class State extends Schema {};
const schema = {};
for (let i = 0; i < maxFields; i++) { schema[`field_${i}`] = "string"; }
defineTypes(State, schema);
const state = new State();
for (let i = 0; i < maxFields; i++) { state[`field_${i}`] = "value " + i; }
const decodedState = Reflection.decode(Reflection.encode(state));
decodedState.decode(state.encode());
for (let i = 0; i < maxFields; i++) {
assert.strictEqual("value " + i, decodedState[`field_${i}`]);
}
});
it("should support more than 255 schema types", () => {
const maxSchemaTypes = 500;
const type = Context.create();
// @type("number") i: number;
class Base extends Schema { }
class State extends Schema {
@type([Base]) children = new ArraySchema<Base>();
}
const schemas: any = {};
for (let i = 0; i < maxSchemaTypes; i++) {
class Child extends Base {
@type("string") str: string;
};
schemas[i] = Child;
}
const state = new State();
for (let i = 0; i < maxSchemaTypes; i++) {
const child = new schemas[i]();
child.str = "value " + i;
state.children.push(child);
}
const decodedState: State = Reflection.decode(Reflection.encode(state));
decodedState.decode(state.encode());
for (let i = 0; i < maxSchemaTypes; i++) {
assert.strictEqual("value " + i, (decodedState.children[i] as any).str);
}
});
it("SWITCH_TO_STRUCTURE check should not collide", () => {
//
// The SWITCH_TO_STRUCTURE byte is `193`
//
class Child extends Schema {
@type("number") n: number;
}
class State extends Schema {
@type(["number"]) arrayOfNum = new ArraySchema<number>();
@type(Child) child = new Child();
@type({ map: "number" }) mapOfNum = new MapSchema<number>();
@type(Child) child4 = new Child();
@type(Child) child5 = new Child();
@type(Child) child6 = new Child();
@type(Child) child7 = new Child();
@type(Child) child8 = new Child();
@type(Child) child9 = new Child();
@type(Child) child10 = new Child();
@type(Child) child11 = new Child();
@type(Child) child12 = new Child();
@type(Child) child13 = new Child();
@type(Child) child14 = new Child();
@type(Child) child15 = new Child();
@type(Child) child16 = new Child();
@type(Child) child17 = new Child();
@type(Child) child18 = new Child();
@type(Child) child19 = new Child();
@type(Child) child20 = new Child();
@type(Child) child21 = new Child();
@type(Child) child22 = new Child();
@type(Child) child23 = new Child();
@type(Child) child24 = new Child();
@type(Child) child25 = new Child();
@type(Child) child26 = new Child();
@type(Child) child27 = new Child();
@type(Child) child28 = new Child();
@type(Child) child29 = new Child();
@type(Child) child30 = new Child();
@type(Child) child31 = new Child();
@type(Child) child32 = new Child();
@type(Child) child33 = new Child();
@type(Child) child34 = new Child();
@type(Child) child35 = new Child();
@type(Child) child36 = new Child();
@type(Child) child37 = new Child();
@type(Child) child38 = new Child();
@type(Child) child39 = new Child();
@type(Child) child40 = new Child();
@type(Child) child41 = new Child();
@type(Child) child42 = new Child();
@type(Child) child43 = new Child();
@type(Child) child44 = new Child();
@type(Child) child45 = new Child();
@type(Child) child46 = new Child();
@type(Child) child47 = new Child();
@type(Child) child48 = new Child();
@type(Child) child49 = new Child();
@type(Child) child50 = new Child();
@type(Child) child51 = new Child();
@type(Child) child52 = new Child();
@type(Child) child53 = new Child();
@type(Child) child54 = new Child();
@type(Child) child55 = new Child();
@type(Child) child56 = new Child();
@type(Child) child57 = new Child();
@type(Child) child58 = new Child();
@type(Child) child59 = new Child();
@type(Child) child60 = new Child();
@type(Child) child61 = new Child();
@type(Child) child62 = new Child();
@type(Child) child63 = new Child();
@type(Child) child64 = new Child();
}
const numItems = 100;
const state = new State();
for (let i = 0; i < numItems; i++) { state.arrayOfNum.push(i); }
for (let i = 0; i < numItems; i++) { state.mapOfNum.set(i.toString(), i); }
state.child.n = 0;
state.child64.n = 0;
const decodedState = new State();
decodedState.decode(state.encode());
state.child = undefined;
state.child = new Child();
state.child.n = 1;
for (let i = 0; i < numItems; i++) {
state.arrayOfNum[i] = undefined;
state.arrayOfNum[i] = i * 100;
}
for (let i = 0; i < numItems; i++) {
state.mapOfNum.delete(i.toString());
state.mapOfNum.set(i.toString(), i * 100);
}
assert.doesNotThrow(() => decodedState.decode(state.encode()));
//
// FIXME: this should not throw an error.
// SWITCH_TO_STRUCTURE conflicts with `DELETE_AND_ADD` + fieldIndex = 63
//
assert.throws(() => {
state.child64 = undefined;
state.child64 = new Child();
state.child64.n = 1;
decodedState.decode(state.encode());
});
state.arrayOfNum.clear();
// state.arrayOfNum.push(10);
state.mapOfNum.clear();
state.mapOfNum.set("one", 10);
assert.doesNotThrow(() => decodedState.decode(state.encode()));
});
it("string: containing specific UTF-8 characters", () => {
let bytes: number[];
const state = new State();
const decodedState = new State();
state.fieldString = "гхб";
bytes = state.encode();
decodedState.decode(bytes);
assert.strictEqual("гхб", decodedState.fieldString);
state.fieldString = "Пуредоминаце";
bytes = state.encode();
decodedState.decode(bytes);
assert.strictEqual("Пуредоминаце", decodedState.fieldString);
state.fieldString = "未知の選手";
bytes = state.encode();
decodedState.decode(bytes);
assert.strictEqual("未知の選手", decodedState.fieldString);
state.fieldString = "알 수없는 플레이어";
bytes = state.encode();
decodedState.decode(bytes);
assert.strictEqual("알 수없는 플레이어", decodedState.fieldString);
});
it("MapSchema: index with high number of items should be preserved", () => {
const state = new State();
state.mapOfPlayers = new MapSchema<Player>();
state.encodeAll(); // new client joining
let i = 0;
const decodedState1 = new State();
decodedState1.decode(state.encodeAll()); // new client joining
state.mapOfPlayers[nanoid(8)] = new Player("Player " + i++, i++, i++);
const decodedState2 = new State();
state.mapOfPlayers[nanoid(8)] = new Player("Player " + i++, i++, i++);
decodedState2.decode(state.encodeAll()); // new client joining
const decodedState3 = new State();
decodedState3.decode(state.encodeAll()); // new client joining
state.mapOfPlayers[nanoid(8)] = new Player("Player " + i++, i++, i++);
const encoded = state.encode(); // patch state
decodedState1.decode(encoded);
decodedState2.decode(encoded);
decodedState3.decode(encoded);
const decodedState4 = new State();
state.mapOfPlayers[nanoid(8)] = new Player("Player " + i++, i++, i++);
decodedState4.decode(state.encodeAll()); // new client joining
assert.strictEqual(JSON.stringify(decodedState1), JSON.stringify(decodedState2));
assert.strictEqual(JSON.stringify(decodedState2), JSON.stringify(decodedState3));
decodedState3.decode(state.encode()); // patch existing client.
assert.strictEqual(JSON.stringify(decodedState3), JSON.stringify(decodedState4));
});
describe("concurrency", () => {
it("MapSchema should support concurrent actions", (done) => {
class Entity extends Schema {
@type("number") id: number;
}
class Enemy extends Entity {
@type("number") level: number;
}
class State extends Schema {
@type({map: Entity}) entities = new MapSchema<Entity>();
}
function createEnemy(i: number) {
return new Enemy().assign({
id: i,
level: i * 100,
});
}
const state = new State();
const decodedState = new State();
decodedState.decode(state.encode());
const onAddCalledFor: string[] = [];
const onRemovedCalledFor: string[] = [];
decodedState.entities.onAdd = function(entity, key) {
onAddCalledFor.push(key);
};
decodedState.entities.onRemove = function(entity, key) {
onRemovedCalledFor.push(key);
};
// insert 100 items.
for (let i = 0; i < 100; i++) {
setTimeout(() => {
state.entities.set("item" + i, createEnemy(i));
}, Math.floor(Math.random() * 10));
}
//
// after all 100 items are added. remove half of them in the same
// pace
//
setTimeout(() => {
decodedState.decode(state.encode());
const removedIndexes: string[] = [];
const addedIndexes: string[] = [];
for (let i = 20; i < 70; i++) {
setTimeout(() => {
const index = 'item' + i;
removedIndexes.push(index);
delete state.entities[index];
}, Math.floor(Math.random() * 10));
}
for (let i = 100; i < 110; i++) {
setTimeout(() => {
const index = 'item' + i;
addedIndexes.push(index);
state.entities.set(index, createEnemy(i));
}, Math.floor(Math.random() * 10));
}
setTimeout(() => {
decodedState.decode(state.encode());
}, 5);
setTimeout(() => {
decodedState.decode(state.encode());
const expectedOnAdd: string[] = [];
const expectedOnRemove: string[] = [];
for (let i = 0; i < 110; i++) {
expectedOnAdd.push('item' + i);
if (i < 20 || i > 70) {
assert.strictEqual(i, decodedState.entities.get('item' + i).id);
} else if (i >= 20 && i < 70) {
expectedOnRemove.push('item' + i);
assert.strictEqual(false, decodedState.entities.has('item' + i));
}
}
onAddCalledFor.sort((a,b) => parseInt(a.substr(4)) - parseInt(b.substr(4)));
onRemovedCalledFor.sort((a,b) => parseInt(a.substr(4)) - parseInt(b.substr(4)));
assert.deepEqual(expectedOnAdd, onAddCalledFor);
assert.deepEqual(expectedOnRemove, onRemovedCalledFor);
assert.strictEqual(60, decodedState.entities.size);
done();
}, 10);
}, 10);
});
});
}); | the_stack |
* @param {Uint32Array} lgr_comm
* @param {WasmPastaFpPlonkVerifierIndex} index
* @param {WasmPastaFpProverProof} proof
* @returns {WasmPastaFpPlonkOracles}
*/
export function caml_pasta_fp_plonk_oracles_create(lgr_comm: Uint32Array, index: WasmPastaFpPlonkVerifierIndex, proof: WasmPastaFpProverProof): WasmPastaFpPlonkOracles;
/**
* @returns {WasmPastaFpPlonkOracles}
*/
export function caml_pasta_fp_plonk_oracles_dummy(): WasmPastaFpPlonkOracles;
/**
* @param {WasmPastaFpPlonkOracles} x
* @returns {WasmPastaFpPlonkOracles}
*/
export function caml_pasta_fp_plonk_oracles_deep_copy(x: WasmPastaFpPlonkOracles): WasmPastaFpPlonkOracles;
/**
* @param {WasmPastaFpPlonkIndex} index
* @param {Uint8Array} primary_input
* @param {Uint8Array} auxiliary_input
* @param {Uint8Array} prev_challenges
* @param {Uint32Array} prev_sgs
* @returns {WasmPastaFpProverProof}
*/
export function caml_pasta_fp_plonk_proof_create(index: WasmPastaFpPlonkIndex, primary_input: Uint8Array, auxiliary_input: Uint8Array, prev_challenges: Uint8Array, prev_sgs: Uint32Array): WasmPastaFpProverProof;
/**
* @param {Uint32Array} lgr_comm
* @param {WasmPastaFpPlonkVerifierIndex} index
* @param {WasmPastaFpProverProof} proof
* @returns {boolean}
*/
export function caml_pasta_fp_plonk_proof_verify(lgr_comm: Uint32Array, index: WasmPastaFpPlonkVerifierIndex, proof: WasmPastaFpProverProof): boolean;
/**
* @param {WasmVecVecVestaPolyComm} lgr_comms
* @param {Uint32Array} indexes
* @param {Uint32Array} proofs
* @returns {boolean}
*/
export function caml_pasta_fp_plonk_proof_batch_verify(lgr_comms: WasmVecVecVestaPolyComm, indexes: Uint32Array, proofs: Uint32Array): boolean;
/**
* @returns {WasmPastaFpProverProof}
*/
export function caml_pasta_fp_plonk_proof_dummy(): WasmPastaFpProverProof;
/**
* @param {WasmPastaFpProverProof} x
* @returns {WasmPastaFpProverProof}
*/
export function caml_pasta_fp_plonk_proof_deep_copy(x: WasmPastaFpProverProof): WasmPastaFpProverProof;
/**
* @returns {number}
*/
export function caml_pasta_fp_size_in_bits(): number;
/**
* @returns {Uint8Array}
*/
export function caml_pasta_fp_size(): Uint8Array;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {Uint8Array}
*/
export function caml_pasta_fp_add(x: Uint8Array, y: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {Uint8Array}
*/
export function caml_pasta_fp_sub(x: Uint8Array, y: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_pasta_fp_negate(x: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {Uint8Array}
*/
export function caml_pasta_fp_mul(x: Uint8Array, y: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {Uint8Array}
*/
export function caml_pasta_fp_div(x: Uint8Array, y: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array | undefined}
*/
export function caml_pasta_fp_inv(x: Uint8Array): Uint8Array | undefined;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_pasta_fp_square(x: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {boolean}
*/
export function caml_pasta_fp_is_square(x: Uint8Array): boolean;
/**
* @param {Uint8Array} x
* @returns {Uint8Array | undefined}
*/
export function caml_pasta_fp_sqrt(x: Uint8Array): Uint8Array | undefined;
/**
* @param {number} i
* @returns {Uint8Array}
*/
export function caml_pasta_fp_of_int(i: number): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {string}
*/
export function caml_pasta_fp_to_string(x: Uint8Array): string;
/**
* @param {string} s
* @returns {Uint8Array}
*/
export function caml_pasta_fp_of_string(s: string): Uint8Array;
/**
* @param {Uint8Array} x
*/
export function caml_pasta_fp_print(x: Uint8Array): void;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {number}
*/
export function caml_pasta_fp_compare(x: Uint8Array, y: Uint8Array): number;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {boolean}
*/
export function caml_pasta_fp_equal(x: Uint8Array, y: Uint8Array): boolean;
/**
* @returns {Uint8Array}
*/
export function caml_pasta_fp_random(): Uint8Array;
/**
* @param {number} i
* @returns {Uint8Array}
*/
export function caml_pasta_fp_rng(i: number): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_pasta_fp_to_bigint(x: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_pasta_fp_of_bigint(x: Uint8Array): Uint8Array;
/**
* @returns {Uint8Array}
*/
export function caml_pasta_fp_two_adic_root_of_unity(): Uint8Array;
/**
* @param {number} log2_size
* @returns {Uint8Array}
*/
export function caml_pasta_fp_domain_generator(log2_size: number): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_pasta_fp_to_bytes(x: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_pasta_fp_of_bytes(x: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_pasta_fp_deep_copy(x: Uint8Array): Uint8Array;
/**
* @returns {number}
*/
export function caml_pasta_fq_size_in_bits(): number;
/**
* @returns {Uint8Array}
*/
export function caml_pasta_fq_size(): Uint8Array;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {Uint8Array}
*/
export function caml_pasta_fq_add(x: Uint8Array, y: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {Uint8Array}
*/
export function caml_pasta_fq_sub(x: Uint8Array, y: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_pasta_fq_negate(x: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {Uint8Array}
*/
export function caml_pasta_fq_mul(x: Uint8Array, y: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {Uint8Array}
*/
export function caml_pasta_fq_div(x: Uint8Array, y: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array | undefined}
*/
export function caml_pasta_fq_inv(x: Uint8Array): Uint8Array | undefined;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_pasta_fq_square(x: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {boolean}
*/
export function caml_pasta_fq_is_square(x: Uint8Array): boolean;
/**
* @param {Uint8Array} x
* @returns {Uint8Array | undefined}
*/
export function caml_pasta_fq_sqrt(x: Uint8Array): Uint8Array | undefined;
/**
* @param {number} i
* @returns {Uint8Array}
*/
export function caml_pasta_fq_of_int(i: number): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {string}
*/
export function caml_pasta_fq_to_string(x: Uint8Array): string;
/**
* @param {string} s
* @returns {Uint8Array}
*/
export function caml_pasta_fq_of_string(s: string): Uint8Array;
/**
* @param {Uint8Array} x
*/
export function caml_pasta_fq_print(x: Uint8Array): void;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {number}
*/
export function caml_pasta_fq_compare(x: Uint8Array, y: Uint8Array): number;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {boolean}
*/
export function caml_pasta_fq_equal(x: Uint8Array, y: Uint8Array): boolean;
/**
* @returns {Uint8Array}
*/
export function caml_pasta_fq_random(): Uint8Array;
/**
* @param {number} i
* @returns {Uint8Array}
*/
export function caml_pasta_fq_rng(i: number): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_pasta_fq_to_bigint(x: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_pasta_fq_of_bigint(x: Uint8Array): Uint8Array;
/**
* @returns {Uint8Array}
*/
export function caml_pasta_fq_two_adic_root_of_unity(): Uint8Array;
/**
* @param {number} log2_size
* @returns {Uint8Array}
*/
export function caml_pasta_fq_domain_generator(log2_size: number): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_pasta_fq_to_bytes(x: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_pasta_fq_of_bytes(x: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_pasta_fq_deep_copy(x: Uint8Array): Uint8Array;
/**
* @param {Uint32Array} lgr_comm
* @param {WasmPastaFqPlonkVerifierIndex} index
* @param {WasmPastaFqProverProof} proof
* @returns {WasmPastaFqPlonkOracles}
*/
export function caml_pasta_fq_plonk_oracles_create(lgr_comm: Uint32Array, index: WasmPastaFqPlonkVerifierIndex, proof: WasmPastaFqProverProof): WasmPastaFqPlonkOracles;
/**
* @returns {WasmPastaFqPlonkOracles}
*/
export function caml_pasta_fq_plonk_oracles_dummy(): WasmPastaFqPlonkOracles;
/**
* @param {WasmPastaFqPlonkOracles} x
* @returns {WasmPastaFqPlonkOracles}
*/
export function caml_pasta_fq_plonk_oracles_deep_copy(x: WasmPastaFqPlonkOracles): WasmPastaFqPlonkOracles;
/**
* @param {number | undefined} offset
* @param {WasmPastaFpUrs} urs
* @param {string} path
* @returns {WasmPastaFpPlonkVerifierIndex}
*/
export function caml_pasta_fp_plonk_verifier_index_read(offset: number | undefined, urs: WasmPastaFpUrs, path: string): WasmPastaFpPlonkVerifierIndex;
/**
* @param {boolean | undefined} append
* @param {WasmPastaFpPlonkVerifierIndex} index
* @param {string} path
*/
export function caml_pasta_fp_plonk_verifier_index_write(append: boolean | undefined, index: WasmPastaFpPlonkVerifierIndex, path: string): void;
/**
* @param {WasmPastaFpPlonkIndex} index
* @returns {WasmPastaFpPlonkVerifierIndex}
*/
export function caml_pasta_fp_plonk_verifier_index_create(index: WasmPastaFpPlonkIndex): WasmPastaFpPlonkVerifierIndex;
/**
* @param {number} log2_size
* @returns {WasmPastaFpPlonkVerificationShifts}
*/
export function caml_pasta_fp_plonk_verifier_index_shifts(log2_size: number): WasmPastaFpPlonkVerificationShifts;
/**
* @returns {WasmPastaFpPlonkVerifierIndex}
*/
export function caml_pasta_fp_plonk_verifier_index_dummy(): WasmPastaFpPlonkVerifierIndex;
/**
* @param {WasmPastaFpPlonkVerifierIndex} x
* @returns {WasmPastaFpPlonkVerifierIndex}
*/
export function caml_pasta_fp_plonk_verifier_index_deep_copy(x: WasmPastaFpPlonkVerifierIndex): WasmPastaFpPlonkVerifierIndex;
/**
* @param {number | undefined} offset
* @param {WasmPastaFqUrs} urs
* @param {string} path
* @returns {WasmPastaFqPlonkVerifierIndex}
*/
export function caml_pasta_fq_plonk_verifier_index_read(offset: number | undefined, urs: WasmPastaFqUrs, path: string): WasmPastaFqPlonkVerifierIndex;
/**
* @param {boolean | undefined} append
* @param {WasmPastaFqPlonkVerifierIndex} index
* @param {string} path
*/
export function caml_pasta_fq_plonk_verifier_index_write(append: boolean | undefined, index: WasmPastaFqPlonkVerifierIndex, path: string): void;
/**
* @param {WasmPastaFqPlonkIndex} index
* @returns {WasmPastaFqPlonkVerifierIndex}
*/
export function caml_pasta_fq_plonk_verifier_index_create(index: WasmPastaFqPlonkIndex): WasmPastaFqPlonkVerifierIndex;
/**
* @param {number} log2_size
* @returns {WasmPastaFqPlonkVerificationShifts}
*/
export function caml_pasta_fq_plonk_verifier_index_shifts(log2_size: number): WasmPastaFqPlonkVerificationShifts;
/**
* @returns {WasmPastaFqPlonkVerifierIndex}
*/
export function caml_pasta_fq_plonk_verifier_index_dummy(): WasmPastaFqPlonkVerifierIndex;
/**
* @param {WasmPastaFqPlonkVerifierIndex} x
* @returns {WasmPastaFqPlonkVerifierIndex}
*/
export function caml_pasta_fq_plonk_verifier_index_deep_copy(x: WasmPastaFqPlonkVerifierIndex): WasmPastaFqPlonkVerifierIndex;
/**
* @returns {WasmPallasGProjective}
*/
export function caml_pasta_pallas_one(): WasmPallasGProjective;
/**
* @param {WasmPallasGProjective} x
* @param {WasmPallasGProjective} y
* @returns {WasmPallasGProjective}
*/
export function caml_pasta_pallas_add(x: WasmPallasGProjective, y: WasmPallasGProjective): WasmPallasGProjective;
/**
* @param {WasmPallasGProjective} x
* @param {WasmPallasGProjective} y
* @returns {WasmPallasGProjective}
*/
export function caml_pasta_pallas_sub(x: WasmPallasGProjective, y: WasmPallasGProjective): WasmPallasGProjective;
/**
* @param {WasmPallasGProjective} x
* @returns {WasmPallasGProjective}
*/
export function caml_pasta_pallas_negate(x: WasmPallasGProjective): WasmPallasGProjective;
/**
* @param {WasmPallasGProjective} x
* @returns {WasmPallasGProjective}
*/
export function caml_pasta_pallas_double(x: WasmPallasGProjective): WasmPallasGProjective;
/**
* @param {WasmPallasGProjective} x
* @param {Uint8Array} y
* @returns {WasmPallasGProjective}
*/
export function caml_pasta_pallas_scale(x: WasmPallasGProjective, y: Uint8Array): WasmPallasGProjective;
/**
* @returns {WasmPallasGProjective}
*/
export function caml_pasta_pallas_random(): WasmPallasGProjective;
/**
* @param {number} i
* @returns {WasmPallasGProjective}
*/
export function caml_pasta_pallas_rng(i: number): WasmPallasGProjective;
/**
* @returns {Uint8Array}
*/
export function caml_pasta_pallas_endo_base(): Uint8Array;
/**
* @returns {Uint8Array}
*/
export function caml_pasta_pallas_endo_scalar(): Uint8Array;
/**
* @param {WasmPallasGProjective} x
* @returns {WasmPallasGAffine}
*/
export function caml_pasta_pallas_to_affine(x: WasmPallasGProjective): WasmPallasGAffine;
/**
* @param {WasmPallasGAffine} x
* @returns {WasmPallasGProjective}
*/
export function caml_pasta_pallas_of_affine(x: WasmPallasGAffine): WasmPallasGProjective;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {WasmPallasGProjective}
*/
export function caml_pasta_pallas_of_affine_coordinates(x: Uint8Array, y: Uint8Array): WasmPallasGProjective;
/**
* @param {WasmPallasGAffine} x
* @returns {WasmPallasGAffine}
*/
export function caml_pasta_pallas_affine_deep_copy(x: WasmPallasGAffine): WasmPallasGAffine;
/**
* @returns {WasmPallasGAffine}
*/
export function caml_pasta_pallas_affine_one(): WasmPallasGAffine;
/**
* @returns {WasmVestaGProjective}
*/
export function caml_pasta_vesta_one(): WasmVestaGProjective;
/**
* @param {WasmVestaGProjective} x
* @param {WasmVestaGProjective} y
* @returns {WasmVestaGProjective}
*/
export function caml_pasta_vesta_add(x: WasmVestaGProjective, y: WasmVestaGProjective): WasmVestaGProjective;
/**
* @param {WasmVestaGProjective} x
* @param {WasmVestaGProjective} y
* @returns {WasmVestaGProjective}
*/
export function caml_pasta_vesta_sub(x: WasmVestaGProjective, y: WasmVestaGProjective): WasmVestaGProjective;
/**
* @param {WasmVestaGProjective} x
* @returns {WasmVestaGProjective}
*/
export function caml_pasta_vesta_negate(x: WasmVestaGProjective): WasmVestaGProjective;
/**
* @param {WasmVestaGProjective} x
* @returns {WasmVestaGProjective}
*/
export function caml_pasta_vesta_double(x: WasmVestaGProjective): WasmVestaGProjective;
/**
* @param {WasmVestaGProjective} x
* @param {Uint8Array} y
* @returns {WasmVestaGProjective}
*/
export function caml_pasta_vesta_scale(x: WasmVestaGProjective, y: Uint8Array): WasmVestaGProjective;
/**
* @returns {WasmVestaGProjective}
*/
export function caml_pasta_vesta_random(): WasmVestaGProjective;
/**
* @param {number} i
* @returns {WasmVestaGProjective}
*/
export function caml_pasta_vesta_rng(i: number): WasmVestaGProjective;
/**
* @returns {Uint8Array}
*/
export function caml_pasta_vesta_endo_base(): Uint8Array;
/**
* @returns {Uint8Array}
*/
export function caml_pasta_vesta_endo_scalar(): Uint8Array;
/**
* @param {WasmVestaGProjective} x
* @returns {WasmVestaGAffine}
*/
export function caml_pasta_vesta_to_affine(x: WasmVestaGProjective): WasmVestaGAffine;
/**
* @param {WasmVestaGAffine} x
* @returns {WasmVestaGProjective}
*/
export function caml_pasta_vesta_of_affine(x: WasmVestaGAffine): WasmVestaGProjective;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {WasmVestaGProjective}
*/
export function caml_pasta_vesta_of_affine_coordinates(x: Uint8Array, y: Uint8Array): WasmVestaGProjective;
/**
* @param {WasmVestaGAffine} x
* @returns {WasmVestaGAffine}
*/
export function caml_pasta_vesta_affine_deep_copy(x: WasmVestaGAffine): WasmVestaGAffine;
/**
* @returns {WasmVestaGAffine}
*/
export function caml_pasta_vesta_affine_one(): WasmVestaGAffine;
/**
* @param {number} depth
* @returns {WasmPastaFpUrs}
*/
export function caml_pasta_fp_urs_create(depth: number): WasmPastaFpUrs;
/**
* @param {boolean | undefined} append
* @param {WasmPastaFpUrs} urs
* @param {string} path
*/
export function caml_pasta_fp_urs_write(append: boolean | undefined, urs: WasmPastaFpUrs, path: string): void;
/**
* @param {number | undefined} offset
* @param {string} path
* @returns {WasmPastaFpUrs | undefined}
*/
export function caml_pasta_fp_urs_read(offset: number | undefined, path: string): WasmPastaFpUrs | undefined;
/**
* @param {WasmPastaFpUrs} urs
* @param {number} domain_size
* @param {number} i
* @returns {WasmPastaVestaPolyComm}
*/
export function caml_pasta_fp_urs_lagrange_commitment(urs: WasmPastaFpUrs, domain_size: number, i: number): WasmPastaVestaPolyComm;
/**
* @param {WasmPastaFpUrs} urs
* @param {number} domain_size
* @param {Uint8Array} evals
* @returns {WasmPastaVestaPolyComm}
*/
export function caml_pasta_fp_urs_commit_evaluations(urs: WasmPastaFpUrs, domain_size: number, evals: Uint8Array): WasmPastaVestaPolyComm;
/**
* @param {WasmPastaFpUrs} urs
* @param {Uint8Array} chals
* @returns {WasmPastaVestaPolyComm}
*/
export function caml_pasta_fp_urs_b_poly_commitment(urs: WasmPastaFpUrs, chals: Uint8Array): WasmPastaVestaPolyComm;
/**
* @param {WasmPastaFpUrs} urs
* @param {Uint32Array} comms
* @param {Uint8Array} chals
* @returns {boolean}
*/
export function caml_pasta_fp_urs_batch_accumulator_check(urs: WasmPastaFpUrs, comms: Uint32Array, chals: Uint8Array): boolean;
/**
* @param {WasmPastaFpUrs} urs
* @returns {WasmVestaGAffine}
*/
export function caml_pasta_fp_urs_h(urs: WasmPastaFpUrs): WasmVestaGAffine;
/**
* @param {number} depth
* @returns {WasmPastaFqUrs}
*/
export function caml_pasta_fq_urs_create(depth: number): WasmPastaFqUrs;
/**
* @param {boolean | undefined} append
* @param {WasmPastaFqUrs} urs
* @param {string} path
*/
export function caml_pasta_fq_urs_write(append: boolean | undefined, urs: WasmPastaFqUrs, path: string): void;
/**
* @param {number | undefined} offset
* @param {string} path
* @returns {WasmPastaFqUrs | undefined}
*/
export function caml_pasta_fq_urs_read(offset: number | undefined, path: string): WasmPastaFqUrs | undefined;
/**
* @param {WasmPastaFqUrs} urs
* @param {number} domain_size
* @param {number} i
* @returns {WasmPastaPallasPolyComm}
*/
export function caml_pasta_fq_urs_lagrange_commitment(urs: WasmPastaFqUrs, domain_size: number, i: number): WasmPastaPallasPolyComm;
/**
* @param {WasmPastaFqUrs} urs
* @param {number} domain_size
* @param {Uint8Array} evals
* @returns {WasmPastaPallasPolyComm}
*/
export function caml_pasta_fq_urs_commit_evaluations(urs: WasmPastaFqUrs, domain_size: number, evals: Uint8Array): WasmPastaPallasPolyComm;
/**
* @param {WasmPastaFqUrs} urs
* @param {Uint8Array} chals
* @returns {WasmPastaPallasPolyComm}
*/
export function caml_pasta_fq_urs_b_poly_commitment(urs: WasmPastaFqUrs, chals: Uint8Array): WasmPastaPallasPolyComm;
/**
* @param {WasmPastaFqUrs} urs
* @param {Uint32Array} comms
* @param {Uint8Array} chals
* @returns {boolean}
*/
export function caml_pasta_fq_urs_batch_accumulator_check(urs: WasmPastaFqUrs, comms: Uint32Array, chals: Uint8Array): boolean;
/**
* @param {WasmPastaFqUrs} urs
* @returns {WasmPallasGAffine}
*/
export function caml_pasta_fq_urs_h(urs: WasmPastaFqUrs): WasmPallasGAffine;
/**
* @returns {WasmPastaFqPlonkGateVector}
*/
export function caml_pasta_fq_plonk_gate_vector_create(): WasmPastaFqPlonkGateVector;
/**
* @param {WasmPastaFqPlonkGateVector} v
* @param {WasmPastaFqPlonkGate} gate
*/
export function caml_pasta_fq_plonk_gate_vector_add(v: WasmPastaFqPlonkGateVector, gate: WasmPastaFqPlonkGate): void;
/**
* @param {WasmPastaFqPlonkGateVector} v
* @param {number} i
* @returns {WasmPastaFqPlonkGate}
*/
export function caml_pasta_fq_plonk_gate_vector_get(v: WasmPastaFqPlonkGateVector, i: number): WasmPastaFqPlonkGate;
/**
* @param {WasmPastaFqPlonkGateVector} v
* @param {WasmPlonkWire} t
* @param {WasmPlonkWire} h
*/
export function caml_pasta_fq_plonk_gate_vector_wrap(v: WasmPastaFqPlonkGateVector, t: WasmPlonkWire, h: WasmPlonkWire): void;
/**
* @param {WasmPastaFqPlonkGateVector} gates
* @param {number} public_
* @param {WasmPastaFqUrs} urs
* @returns {WasmPastaFqPlonkIndex}
*/
export function caml_pasta_fq_plonk_index_create(gates: WasmPastaFqPlonkGateVector, public_: number, urs: WasmPastaFqUrs): WasmPastaFqPlonkIndex;
/**
* @param {WasmPastaFqPlonkIndex} index
* @returns {number}
*/
export function caml_pasta_fq_plonk_index_max_degree(index: WasmPastaFqPlonkIndex): number;
/**
* @param {WasmPastaFqPlonkIndex} index
* @returns {number}
*/
export function caml_pasta_fq_plonk_index_public_inputs(index: WasmPastaFqPlonkIndex): number;
/**
* @param {WasmPastaFqPlonkIndex} index
* @returns {number}
*/
export function caml_pasta_fq_plonk_index_domain_d1_size(index: WasmPastaFqPlonkIndex): number;
/**
* @param {WasmPastaFqPlonkIndex} index
* @returns {number}
*/
export function caml_pasta_fq_plonk_index_domain_d4_size(index: WasmPastaFqPlonkIndex): number;
/**
* @param {WasmPastaFqPlonkIndex} index
* @returns {number}
*/
export function caml_pasta_fq_plonk_index_domain_d8_size(index: WasmPastaFqPlonkIndex): number;
/**
* @param {number | undefined} offset
* @param {WasmPastaFqUrs} urs
* @param {string} path
* @returns {WasmPastaFqPlonkIndex}
*/
export function caml_pasta_fq_plonk_index_read(offset: number | undefined, urs: WasmPastaFqUrs, path: string): WasmPastaFqPlonkIndex;
/**
* @param {boolean | undefined} append
* @param {WasmPastaFqPlonkIndex} index
* @param {string} path
*/
export function caml_pasta_fq_plonk_index_write(append: boolean | undefined, index: WasmPastaFqPlonkIndex, path: string): void;
/**
* @returns {WasmPastaFpPlonkGateVector}
*/
export function caml_pasta_fp_plonk_gate_vector_create(): WasmPastaFpPlonkGateVector;
/**
* @param {WasmPastaFpPlonkGateVector} v
* @param {WasmPastaFpPlonkGate} gate
*/
export function caml_pasta_fp_plonk_gate_vector_add(v: WasmPastaFpPlonkGateVector, gate: WasmPastaFpPlonkGate): void;
/**
* @param {WasmPastaFpPlonkGateVector} v
* @param {number} i
* @returns {WasmPastaFpPlonkGate}
*/
export function caml_pasta_fp_plonk_gate_vector_get(v: WasmPastaFpPlonkGateVector, i: number): WasmPastaFpPlonkGate;
/**
* @param {WasmPastaFpPlonkGateVector} v
* @param {WasmPlonkWire} t
* @param {WasmPlonkWire} h
*/
export function caml_pasta_fp_plonk_gate_vector_wrap(v: WasmPastaFpPlonkGateVector, t: WasmPlonkWire, h: WasmPlonkWire): void;
/**
* @param {WasmPastaFpPlonkGateVector} gates
* @param {number} public_
* @param {WasmPastaFpUrs} urs
* @returns {WasmPastaFpPlonkIndex}
*/
export function caml_pasta_fp_plonk_index_create(gates: WasmPastaFpPlonkGateVector, public_: number, urs: WasmPastaFpUrs): WasmPastaFpPlonkIndex;
/**
* @param {WasmPastaFpPlonkIndex} index
* @returns {number}
*/
export function caml_pasta_fp_plonk_index_max_degree(index: WasmPastaFpPlonkIndex): number;
/**
* @param {WasmPastaFpPlonkIndex} index
* @returns {number}
*/
export function caml_pasta_fp_plonk_index_public_inputs(index: WasmPastaFpPlonkIndex): number;
/**
* @param {WasmPastaFpPlonkIndex} index
* @returns {number}
*/
export function caml_pasta_fp_plonk_index_domain_d1_size(index: WasmPastaFpPlonkIndex): number;
/**
* @param {WasmPastaFpPlonkIndex} index
* @returns {number}
*/
export function caml_pasta_fp_plonk_index_domain_d4_size(index: WasmPastaFpPlonkIndex): number;
/**
* @param {WasmPastaFpPlonkIndex} index
* @returns {number}
*/
export function caml_pasta_fp_plonk_index_domain_d8_size(index: WasmPastaFpPlonkIndex): number;
/**
* @param {number | undefined} offset
* @param {WasmPastaFpUrs} urs
* @param {string} path
* @returns {WasmPastaFpPlonkIndex}
*/
export function caml_pasta_fp_plonk_index_read(offset: number | undefined, urs: WasmPastaFpUrs, path: string): WasmPastaFpPlonkIndex;
/**
* @param {boolean | undefined} append
* @param {WasmPastaFpPlonkIndex} index
* @param {string} path
*/
export function caml_pasta_fp_plonk_index_write(append: boolean | undefined, index: WasmPastaFpPlonkIndex, path: string): void;
/**
* @param {string} s
* @param {number} _len
* @param {number} base
* @returns {Uint8Array}
*/
export function caml_bigint_256_of_numeral(s: string, _len: number, base: number): Uint8Array;
/**
* @param {string} s
* @returns {Uint8Array}
*/
export function caml_bigint_256_of_decimal_string(s: string): Uint8Array;
/**
* @returns {number}
*/
export function caml_bigint_256_num_limbs(): number;
/**
* @returns {number}
*/
export function caml_bigint_256_bytes_per_limb(): number;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {Uint8Array}
*/
export function caml_bigint_256_div(x: Uint8Array, y: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @param {Uint8Array} y
* @returns {number}
*/
export function caml_bigint_256_compare(x: Uint8Array, y: Uint8Array): number;
/**
* @param {Uint8Array} x
*/
export function caml_bigint_256_print(x: Uint8Array): void;
/**
* @param {Uint8Array} x
* @returns {string}
*/
export function caml_bigint_256_to_string(x: Uint8Array): string;
/**
* @param {Uint8Array} x
* @param {number} i
* @returns {boolean}
*/
export function caml_bigint_256_test_bit(x: Uint8Array, i: number): boolean;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_bigint_256_to_bytes(x: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_bigint_256_of_bytes(x: Uint8Array): Uint8Array;
/**
* @param {Uint8Array} x
* @returns {Uint8Array}
*/
export function caml_bigint_256_deep_copy(x: Uint8Array): Uint8Array;
/**
* @param {string} name
*/
export function greet(name: string): void;
/**
* @param {string} s
*/
export function console_log(s: string): void;
/**
* @returns {number}
*/
export function create_zero_u32_ptr(): number;
/**
* @param {number} ptr
*/
export function free_u32_ptr(ptr: number): void;
/**
* @param {number} ptr
* @param {number} arg
*/
export function set_u32_ptr(ptr: number, arg: number): void;
/**
* @param {number} ptr
* @returns {number}
*/
export function wait_until_non_zero(ptr: number): number;
/**
* @param {WasmPastaFqPlonkIndex} index
* @param {Uint8Array} primary_input
* @param {Uint8Array} auxiliary_input
* @param {Uint8Array} prev_challenges
* @param {Uint32Array} prev_sgs
* @returns {WasmPastaFqProverProof}
*/
export function caml_pasta_fq_plonk_proof_create(index: WasmPastaFqPlonkIndex, primary_input: Uint8Array, auxiliary_input: Uint8Array, prev_challenges: Uint8Array, prev_sgs: Uint32Array): WasmPastaFqProverProof;
/**
* @param {Uint32Array} lgr_comm
* @param {WasmPastaFqPlonkVerifierIndex} index
* @param {WasmPastaFqProverProof} proof
* @returns {boolean}
*/
export function caml_pasta_fq_plonk_proof_verify(lgr_comm: Uint32Array, index: WasmPastaFqPlonkVerifierIndex, proof: WasmPastaFqProverProof): boolean;
/**
* @param {WasmVecVecPallasPolyComm} lgr_comms
* @param {Uint32Array} indexes
* @param {Uint32Array} proofs
* @returns {boolean}
*/
export function caml_pasta_fq_plonk_proof_batch_verify(lgr_comms: WasmVecVecPallasPolyComm, indexes: Uint32Array, proofs: Uint32Array): boolean;
/**
* @returns {WasmPastaFqProverProof}
*/
export function caml_pasta_fq_plonk_proof_dummy(): WasmPastaFqProverProof;
/**
* @param {WasmPastaFqProverProof} x
* @returns {WasmPastaFqProverProof}
*/
export function caml_pasta_fq_plonk_proof_deep_copy(x: WasmPastaFqProverProof): WasmPastaFqProverProof;
/**
* @param {number} num_threads
* @param {string} worker_source
* @returns {Promise<any>}
*/
export function initThreadPool(num_threads: number, worker_source: string): Promise<any>;
/**
* @param {number} receiver
*/
export function wbg_rayon_start_worker(receiver: number): void;
/**
*/
export enum WasmPlonkGateType {
Zero,
Generic,
Poseidon,
Add1,
Add2,
Vbmul1,
Vbmul2,
Vbmul3,
Endomul1,
Endomul2,
Endomul3,
Endomul4,
}
/**
*/
export enum WasmPlonkCol {
L,
R,
O,
}
/**
*/
export class WasmPallasGAffine {
free(): void;
/**
*/
infinity: boolean;
/**
*/
x: Uint8Array;
/**
*/
y: Uint8Array;
}
/**
*/
export class WasmPallasGProjective {
free(): void;
}
/**
*/
export class WasmPastaFpOpeningProof {
free(): void;
/**
* @param {Uint32Array} lr_0
* @param {Uint32Array} lr_1
* @param {WasmVestaGAffine} delta
* @param {Uint8Array} z1
* @param {Uint8Array} z2
* @param {WasmVestaGAffine} sg
*/
constructor(lr_0: Uint32Array, lr_1: Uint32Array, delta: WasmVestaGAffine, z1: Uint8Array, z2: Uint8Array, sg: WasmVestaGAffine);
/**
* @returns {WasmVestaGAffine}
*/
delta: WasmVestaGAffine;
/**
* @returns {Uint32Array}
*/
lr_0: Uint32Array;
/**
* @returns {Uint32Array}
*/
lr_1: Uint32Array;
/**
* @returns {WasmVestaGAffine}
*/
sg: WasmVestaGAffine;
/**
*/
z1: Uint8Array;
/**
*/
z2: Uint8Array;
}
/**
*/
export class WasmPastaFpPlonkDomain {
free(): void;
/**
* @param {number} log_size_of_group
* @param {Uint8Array} group_gen
*/
constructor(log_size_of_group: number, group_gen: Uint8Array);
/**
*/
group_gen: Uint8Array;
/**
*/
log_size_of_group: number;
}
/**
*/
export class WasmPastaFpPlonkGate {
free(): void;
/**
* @param {number} typ
* @param {WasmPlonkWires} wires
* @param {Uint8Array} c
*/
constructor(typ: number, wires: WasmPlonkWires, c: Uint8Array);
/**
* @returns {Uint8Array}
*/
c: Uint8Array;
/**
*/
typ: number;
/**
*/
wires: WasmPlonkWires;
}
/**
*/
export class WasmPastaFpPlonkGateVector {
free(): void;
}
/**
*/
export class WasmPastaFpPlonkIndex {
free(): void;
}
/**
*/
export class WasmPastaFpPlonkOracles {
free(): void;
/**
* @param {Uint8Array} o
* @param {Uint8Array} p_eval0
* @param {Uint8Array} p_eval1
* @param {Uint8Array} opening_prechallenges
* @param {Uint8Array} digest_before_evaluations
*/
constructor(o: Uint8Array, p_eval0: Uint8Array, p_eval1: Uint8Array, opening_prechallenges: Uint8Array, digest_before_evaluations: Uint8Array);
/**
*/
digest_before_evaluations: Uint8Array;
/**
*/
o: Uint8Array;
/**
* @returns {Uint8Array}
*/
opening_prechallenges: Uint8Array;
/**
*/
p_eval0: Uint8Array;
/**
*/
p_eval1: Uint8Array;
}
/**
*/
export class WasmPastaFpPlonkVerificationEvals {
free(): void;
/**
* @param {WasmPastaVestaPolyComm} sigma_comm0
* @param {WasmPastaVestaPolyComm} sigma_comm1
* @param {WasmPastaVestaPolyComm} sigma_comm2
* @param {WasmPastaVestaPolyComm} ql_comm
* @param {WasmPastaVestaPolyComm} qr_comm
* @param {WasmPastaVestaPolyComm} qo_comm
* @param {WasmPastaVestaPolyComm} qm_comm
* @param {WasmPastaVestaPolyComm} qc_comm
* @param {WasmPastaVestaPolyComm} rcm_comm0
* @param {WasmPastaVestaPolyComm} rcm_comm1
* @param {WasmPastaVestaPolyComm} rcm_comm2
* @param {WasmPastaVestaPolyComm} psm_comm
* @param {WasmPastaVestaPolyComm} add_comm
* @param {WasmPastaVestaPolyComm} mul1_comm
* @param {WasmPastaVestaPolyComm} mul2_comm
* @param {WasmPastaVestaPolyComm} emul1_comm
* @param {WasmPastaVestaPolyComm} emul2_comm
* @param {WasmPastaVestaPolyComm} emul3_comm
*/
constructor(sigma_comm0: WasmPastaVestaPolyComm, sigma_comm1: WasmPastaVestaPolyComm, sigma_comm2: WasmPastaVestaPolyComm, ql_comm: WasmPastaVestaPolyComm, qr_comm: WasmPastaVestaPolyComm, qo_comm: WasmPastaVestaPolyComm, qm_comm: WasmPastaVestaPolyComm, qc_comm: WasmPastaVestaPolyComm, rcm_comm0: WasmPastaVestaPolyComm, rcm_comm1: WasmPastaVestaPolyComm, rcm_comm2: WasmPastaVestaPolyComm, psm_comm: WasmPastaVestaPolyComm, add_comm: WasmPastaVestaPolyComm, mul1_comm: WasmPastaVestaPolyComm, mul2_comm: WasmPastaVestaPolyComm, emul1_comm: WasmPastaVestaPolyComm, emul2_comm: WasmPastaVestaPolyComm, emul3_comm: WasmPastaVestaPolyComm);
/**
* @returns {WasmPastaVestaPolyComm}
*/
add_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
emul1_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
emul2_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
emul3_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
mul1_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
mul2_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
psm_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
qc_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
ql_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
qm_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
qo_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
qr_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
rcm_comm0: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
rcm_comm1: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
rcm_comm2: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
sigma_comm0: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
sigma_comm1: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
sigma_comm2: WasmPastaVestaPolyComm;
}
/**
*/
export class WasmPastaFpPlonkVerificationShifts {
free(): void;
/**
* @param {Uint8Array} r
* @param {Uint8Array} o
*/
constructor(r: Uint8Array, o: Uint8Array);
/**
*/
o: Uint8Array;
/**
*/
r: Uint8Array;
}
/**
*/
export class WasmPastaFpPlonkVerifierIndex {
free(): void;
/**
* @param {WasmPastaFpPlonkDomain} domain
* @param {number} max_poly_size
* @param {number} max_quot_size
* @param {WasmPastaFpUrs} urs
* @param {WasmPastaFpPlonkVerificationEvals} evals
* @param {WasmPastaFpPlonkVerificationShifts} shifts
*/
constructor(domain: WasmPastaFpPlonkDomain, max_poly_size: number, max_quot_size: number, urs: WasmPastaFpUrs, evals: WasmPastaFpPlonkVerificationEvals, shifts: WasmPastaFpPlonkVerificationShifts);
/**
*/
domain: WasmPastaFpPlonkDomain;
/**
* @returns {WasmPastaFpPlonkVerificationEvals}
*/
evals: WasmPastaFpPlonkVerificationEvals;
/**
*/
max_poly_size: number;
/**
*/
max_quot_size: number;
/**
*/
shifts: WasmPastaFpPlonkVerificationShifts;
/**
* @returns {WasmPastaFpUrs}
*/
urs: WasmPastaFpUrs;
}
/**
*/
export class WasmPastaFpProofEvaluations {
free(): void;
/**
* @param {Uint8Array} l
* @param {Uint8Array} r
* @param {Uint8Array} o
* @param {Uint8Array} z
* @param {Uint8Array} t
* @param {Uint8Array} f
* @param {Uint8Array} sigma1
* @param {Uint8Array} sigma2
*/
constructor(l: Uint8Array, r: Uint8Array, o: Uint8Array, z: Uint8Array, t: Uint8Array, f: Uint8Array, sigma1: Uint8Array, sigma2: Uint8Array);
/**
* @returns {Uint8Array}
*/
f: Uint8Array;
/**
* @returns {Uint8Array}
*/
l: Uint8Array;
/**
* @returns {Uint8Array}
*/
o: Uint8Array;
/**
* @returns {Uint8Array}
*/
r: Uint8Array;
/**
* @returns {Uint8Array}
*/
sigma1: Uint8Array;
/**
* @returns {Uint8Array}
*/
sigma2: Uint8Array;
/**
* @returns {Uint8Array}
*/
t: Uint8Array;
/**
* @returns {Uint8Array}
*/
z: Uint8Array;
}
/**
*/
export class WasmPastaFpProverCommitments {
free(): void;
/**
* @param {WasmPastaVestaPolyComm} l_comm
* @param {WasmPastaVestaPolyComm} r_comm
* @param {WasmPastaVestaPolyComm} o_comm
* @param {WasmPastaVestaPolyComm} z_comm
* @param {WasmPastaVestaPolyComm} t_comm
*/
constructor(l_comm: WasmPastaVestaPolyComm, r_comm: WasmPastaVestaPolyComm, o_comm: WasmPastaVestaPolyComm, z_comm: WasmPastaVestaPolyComm, t_comm: WasmPastaVestaPolyComm);
/**
* @returns {WasmPastaVestaPolyComm}
*/
l_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
o_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
r_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
t_comm: WasmPastaVestaPolyComm;
/**
* @returns {WasmPastaVestaPolyComm}
*/
z_comm: WasmPastaVestaPolyComm;
}
/**
*/
export class WasmPastaFpProverProof {
free(): void;
/**
* @param {WasmPastaFpProverCommitments} commitments
* @param {WasmPastaFpOpeningProof} proof
* @param {WasmPastaFpProofEvaluations} evals0
* @param {WasmPastaFpProofEvaluations} evals1
* @param {Uint8Array} public_
* @param {WasmVecVecPastaFp} prev_challenges_scalars
* @param {Uint32Array} prev_challenges_comms
*/
constructor(commitments: WasmPastaFpProverCommitments, proof: WasmPastaFpOpeningProof, evals0: WasmPastaFpProofEvaluations, evals1: WasmPastaFpProofEvaluations, public_: Uint8Array, prev_challenges_scalars: WasmVecVecPastaFp, prev_challenges_comms: Uint32Array);
/**
* @returns {WasmPastaFpProverCommitments}
*/
commitments: WasmPastaFpProverCommitments;
/**
* @returns {WasmPastaFpProofEvaluations}
*/
evals0: WasmPastaFpProofEvaluations;
/**
* @returns {WasmPastaFpProofEvaluations}
*/
evals1: WasmPastaFpProofEvaluations;
/**
* @returns {Uint32Array}
*/
prev_challenges_comms: Uint32Array;
/**
* @returns {WasmVecVecPastaFp}
*/
prev_challenges_scalars: WasmVecVecPastaFp;
/**
* @returns {WasmPastaFpOpeningProof}
*/
proof: WasmPastaFpOpeningProof;
/**
* @returns {Uint8Array}
*/
public_: Uint8Array;
}
/**
*/
export class WasmPastaFpUrs {
free(): void;
}
/**
*/
export class WasmPastaFqOpeningProof {
free(): void;
/**
* @param {Uint32Array} lr_0
* @param {Uint32Array} lr_1
* @param {WasmPallasGAffine} delta
* @param {Uint8Array} z1
* @param {Uint8Array} z2
* @param {WasmPallasGAffine} sg
*/
constructor(lr_0: Uint32Array, lr_1: Uint32Array, delta: WasmPallasGAffine, z1: Uint8Array, z2: Uint8Array, sg: WasmPallasGAffine);
/**
* @returns {WasmPallasGAffine}
*/
delta: WasmPallasGAffine;
/**
* @returns {Uint32Array}
*/
lr_0: Uint32Array;
/**
* @returns {Uint32Array}
*/
lr_1: Uint32Array;
/**
* @returns {WasmPallasGAffine}
*/
sg: WasmPallasGAffine;
/**
*/
z1: Uint8Array;
/**
*/
z2: Uint8Array;
}
/**
*/
export class WasmPastaFqPlonkDomain {
free(): void;
/**
* @param {number} log_size_of_group
* @param {Uint8Array} group_gen
*/
constructor(log_size_of_group: number, group_gen: Uint8Array);
/**
*/
group_gen: Uint8Array;
/**
*/
log_size_of_group: number;
}
/**
*/
export class WasmPastaFqPlonkGate {
free(): void;
/**
* @param {number} typ
* @param {WasmPlonkWires} wires
* @param {Uint8Array} c
*/
constructor(typ: number, wires: WasmPlonkWires, c: Uint8Array);
/**
* @returns {Uint8Array}
*/
c: Uint8Array;
/**
*/
typ: number;
/**
*/
wires: WasmPlonkWires;
}
/**
*/
export class WasmPastaFqPlonkGateVector {
free(): void;
}
/**
*/
export class WasmPastaFqPlonkIndex {
free(): void;
}
/**
*/
export class WasmPastaFqPlonkOracles {
free(): void;
/**
* @param {Uint8Array} o
* @param {Uint8Array} p_eval0
* @param {Uint8Array} p_eval1
* @param {Uint8Array} opening_prechallenges
* @param {Uint8Array} digest_before_evaluations
*/
constructor(o: Uint8Array, p_eval0: Uint8Array, p_eval1: Uint8Array, opening_prechallenges: Uint8Array, digest_before_evaluations: Uint8Array);
/**
*/
digest_before_evaluations: Uint8Array;
/**
*/
o: Uint8Array;
/**
* @returns {Uint8Array}
*/
opening_prechallenges: Uint8Array;
/**
*/
p_eval0: Uint8Array;
/**
*/
p_eval1: Uint8Array;
}
/**
*/
export class WasmPastaFqPlonkVerificationEvals {
free(): void;
/**
* @param {WasmPastaPallasPolyComm} sigma_comm0
* @param {WasmPastaPallasPolyComm} sigma_comm1
* @param {WasmPastaPallasPolyComm} sigma_comm2
* @param {WasmPastaPallasPolyComm} ql_comm
* @param {WasmPastaPallasPolyComm} qr_comm
* @param {WasmPastaPallasPolyComm} qo_comm
* @param {WasmPastaPallasPolyComm} qm_comm
* @param {WasmPastaPallasPolyComm} qc_comm
* @param {WasmPastaPallasPolyComm} rcm_comm0
* @param {WasmPastaPallasPolyComm} rcm_comm1
* @param {WasmPastaPallasPolyComm} rcm_comm2
* @param {WasmPastaPallasPolyComm} psm_comm
* @param {WasmPastaPallasPolyComm} add_comm
* @param {WasmPastaPallasPolyComm} mul1_comm
* @param {WasmPastaPallasPolyComm} mul2_comm
* @param {WasmPastaPallasPolyComm} emul1_comm
* @param {WasmPastaPallasPolyComm} emul2_comm
* @param {WasmPastaPallasPolyComm} emul3_comm
*/
constructor(sigma_comm0: WasmPastaPallasPolyComm, sigma_comm1: WasmPastaPallasPolyComm, sigma_comm2: WasmPastaPallasPolyComm, ql_comm: WasmPastaPallasPolyComm, qr_comm: WasmPastaPallasPolyComm, qo_comm: WasmPastaPallasPolyComm, qm_comm: WasmPastaPallasPolyComm, qc_comm: WasmPastaPallasPolyComm, rcm_comm0: WasmPastaPallasPolyComm, rcm_comm1: WasmPastaPallasPolyComm, rcm_comm2: WasmPastaPallasPolyComm, psm_comm: WasmPastaPallasPolyComm, add_comm: WasmPastaPallasPolyComm, mul1_comm: WasmPastaPallasPolyComm, mul2_comm: WasmPastaPallasPolyComm, emul1_comm: WasmPastaPallasPolyComm, emul2_comm: WasmPastaPallasPolyComm, emul3_comm: WasmPastaPallasPolyComm);
/**
* @returns {WasmPastaPallasPolyComm}
*/
add_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
emul1_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
emul2_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
emul3_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
mul1_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
mul2_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
psm_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
qc_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
ql_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
qm_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
qo_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
qr_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
rcm_comm0: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
rcm_comm1: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
rcm_comm2: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
sigma_comm0: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
sigma_comm1: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
sigma_comm2: WasmPastaPallasPolyComm;
}
/**
*/
export class WasmPastaFqPlonkVerificationShifts {
free(): void;
/**
* @param {Uint8Array} r
* @param {Uint8Array} o
*/
constructor(r: Uint8Array, o: Uint8Array);
/**
*/
o: Uint8Array;
/**
*/
r: Uint8Array;
}
/**
*/
export class WasmPastaFqPlonkVerifierIndex {
free(): void;
/**
* @param {WasmPastaFqPlonkDomain} domain
* @param {number} max_poly_size
* @param {number} max_quot_size
* @param {WasmPastaFqUrs} urs
* @param {WasmPastaFqPlonkVerificationEvals} evals
* @param {WasmPastaFqPlonkVerificationShifts} shifts
*/
constructor(domain: WasmPastaFqPlonkDomain, max_poly_size: number, max_quot_size: number, urs: WasmPastaFqUrs, evals: WasmPastaFqPlonkVerificationEvals, shifts: WasmPastaFqPlonkVerificationShifts);
/**
*/
domain: WasmPastaFqPlonkDomain;
/**
* @returns {WasmPastaFqPlonkVerificationEvals}
*/
evals: WasmPastaFqPlonkVerificationEvals;
/**
*/
max_poly_size: number;
/**
*/
max_quot_size: number;
/**
*/
shifts: WasmPastaFqPlonkVerificationShifts;
/**
* @returns {WasmPastaFqUrs}
*/
urs: WasmPastaFqUrs;
}
/**
*/
export class WasmPastaFqProofEvaluations {
free(): void;
/**
* @param {Uint8Array} l
* @param {Uint8Array} r
* @param {Uint8Array} o
* @param {Uint8Array} z
* @param {Uint8Array} t
* @param {Uint8Array} f
* @param {Uint8Array} sigma1
* @param {Uint8Array} sigma2
*/
constructor(l: Uint8Array, r: Uint8Array, o: Uint8Array, z: Uint8Array, t: Uint8Array, f: Uint8Array, sigma1: Uint8Array, sigma2: Uint8Array);
/**
* @returns {Uint8Array}
*/
f: Uint8Array;
/**
* @returns {Uint8Array}
*/
l: Uint8Array;
/**
* @returns {Uint8Array}
*/
o: Uint8Array;
/**
* @returns {Uint8Array}
*/
r: Uint8Array;
/**
* @returns {Uint8Array}
*/
sigma1: Uint8Array;
/**
* @returns {Uint8Array}
*/
sigma2: Uint8Array;
/**
* @returns {Uint8Array}
*/
t: Uint8Array;
/**
* @returns {Uint8Array}
*/
z: Uint8Array;
}
/**
*/
export class WasmPastaFqProverCommitments {
free(): void;
/**
* @param {WasmPastaPallasPolyComm} l_comm
* @param {WasmPastaPallasPolyComm} r_comm
* @param {WasmPastaPallasPolyComm} o_comm
* @param {WasmPastaPallasPolyComm} z_comm
* @param {WasmPastaPallasPolyComm} t_comm
*/
constructor(l_comm: WasmPastaPallasPolyComm, r_comm: WasmPastaPallasPolyComm, o_comm: WasmPastaPallasPolyComm, z_comm: WasmPastaPallasPolyComm, t_comm: WasmPastaPallasPolyComm);
/**
* @returns {WasmPastaPallasPolyComm}
*/
l_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
o_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
r_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
t_comm: WasmPastaPallasPolyComm;
/**
* @returns {WasmPastaPallasPolyComm}
*/
z_comm: WasmPastaPallasPolyComm;
}
/**
*/
export class WasmPastaFqProverProof {
free(): void;
/**
* @param {WasmPastaFqProverCommitments} commitments
* @param {WasmPastaFqOpeningProof} proof
* @param {WasmPastaFqProofEvaluations} evals0
* @param {WasmPastaFqProofEvaluations} evals1
* @param {Uint8Array} public_
* @param {WasmVecVecPastaFq} prev_challenges_scalars
* @param {Uint32Array} prev_challenges_comms
*/
constructor(commitments: WasmPastaFqProverCommitments, proof: WasmPastaFqOpeningProof, evals0: WasmPastaFqProofEvaluations, evals1: WasmPastaFqProofEvaluations, public_: Uint8Array, prev_challenges_scalars: WasmVecVecPastaFq, prev_challenges_comms: Uint32Array);
/**
* @returns {WasmPastaFqProverCommitments}
*/
commitments: WasmPastaFqProverCommitments;
/**
* @returns {WasmPastaFqProofEvaluations}
*/
evals0: WasmPastaFqProofEvaluations;
/**
* @returns {WasmPastaFqProofEvaluations}
*/
evals1: WasmPastaFqProofEvaluations;
/**
* @returns {Uint32Array}
*/
prev_challenges_comms: Uint32Array;
/**
* @returns {WasmVecVecPastaFq}
*/
prev_challenges_scalars: WasmVecVecPastaFq;
/**
* @returns {WasmPastaFqOpeningProof}
*/
proof: WasmPastaFqOpeningProof;
/**
* @returns {Uint8Array}
*/
public_: Uint8Array;
}
/**
*/
export class WasmPastaFqUrs {
free(): void;
}
/**
*/
export class WasmPastaPallasPolyComm {
free(): void;
/**
* @param {Uint32Array} unshifted
* @param {WasmPallasGAffine | undefined} shifted
*/
constructor(unshifted: Uint32Array, shifted?: WasmPallasGAffine);
/**
*/
shifted?: WasmPallasGAffine;
/**
* @returns {Uint32Array}
*/
unshifted: Uint32Array;
}
/**
*/
export class WasmPastaVestaPolyComm {
free(): void;
/**
* @param {Uint32Array} unshifted
* @param {WasmVestaGAffine | undefined} shifted
*/
constructor(unshifted: Uint32Array, shifted?: WasmVestaGAffine);
/**
*/
shifted?: WasmVestaGAffine;
/**
* @returns {Uint32Array}
*/
unshifted: Uint32Array;
}
/**
*/
export class WasmPlonkWire {
free(): void;
/**
* @param {number} row
* @param {number} col
*/
constructor(row: number, col: number);
/**
*/
col: number;
/**
*/
row: number;
}
/**
*/
export class WasmPlonkWires {
free(): void;
/**
* @param {number} row
* @param {WasmPlonkWire} l
* @param {WasmPlonkWire} r
* @param {WasmPlonkWire} o
*/
constructor(row: number, l: WasmPlonkWire, r: WasmPlonkWire, o: WasmPlonkWire);
/**
*/
l: WasmPlonkWire;
/**
*/
o: WasmPlonkWire;
/**
*/
r: WasmPlonkWire;
/**
*/
row: number;
}
/**
*/
export class WasmVecVecPallasPolyComm {
free(): void;
/**
* @param {number} n
*/
constructor(n: number);
/**
* @param {Uint32Array} x
*/
push(x: Uint32Array): void;
}
/**
*/
export class WasmVecVecPastaFp {
free(): void;
/**
* @param {number} n
*/
constructor(n: number);
/**
* @param {Uint8Array} x
*/
push(x: Uint8Array): void;
/**
* @param {number} i
* @returns {Uint8Array}
*/
get(i: number): Uint8Array;
/**
* @param {number} i
* @param {Uint8Array} x
*/
set(i: number, x: Uint8Array): void;
}
/**
*/
export class WasmVecVecPastaFq {
free(): void;
/**
* @param {number} n
*/
constructor(n: number);
/**
* @param {Uint8Array} x
*/
push(x: Uint8Array): void;
/**
* @param {number} i
* @returns {Uint8Array}
*/
get(i: number): Uint8Array;
/**
* @param {number} i
* @param {Uint8Array} x
*/
set(i: number, x: Uint8Array): void;
}
/**
*/
export class WasmVecVecVestaPolyComm {
free(): void;
/**
* @param {number} n
*/
constructor(n: number);
/**
* @param {Uint32Array} x
*/
push(x: Uint32Array): void;
}
/**
*/
export class WasmVestaGAffine {
free(): void;
/**
*/
infinity: boolean;
/**
*/
x: Uint8Array;
/**
*/
y: Uint8Array;
}
/**
*/
export class WasmVestaGProjective {
free(): void;
}
/**
*/
export class wbg_rayon_PoolBuilder {
free(): void;
/**
* @returns {number}
*/
numThreads(): number;
/**
* @returns {number}
*/
receiver(): number;
/**
*/
build(): void;
} | the_stack |
import { PdfDocument, PdfGraphics, PdfPage, PdfTextWebLink, PdfColor, SizeF, PdfLayoutFormat, PdfSection } from './../../src/index';
import { PdfStringFormat } from './../../src/index';
import { PdfGrid, PdfGridCellStyle } from './../../src/index';
import { PdfGridRow, PdfPen, PdfDocumentLinkAnnotation, PdfSolidBrush, PdfNumberStyle, PdfVerticalAlignment } from './../../src/index';
import { PdfDestination, PdfFont, PdfStandardFont, PdfDestinationMode, PdfDashStyle, PdfTextAlignment } from './../../src/index';
import { PdfBorders, PdfPageSize, PdfPageRotateAngle, RectangleF, PointF, PdfBorderOverlapStyle, PdfPageTemplateElement } from './../../src/index';
import { PdfHorizontalOverflowType, PdfPageOrientation, PdfFontFamily, PdfFontStyle, PdfPageNumberField, PdfBitmap } from './../../src/index';
import { PdfPageCountField } from './../../src/implementation/document/automatic-fields/page-count-field';
import { PdfCompositeField } from './../../src/implementation/document/automatic-fields/composite-field';
import { StreamWriter } from '@syncfusion/ej2-file-utils';
import { PdfTextElement, PdfLayoutResult } from './../../src/index';
import { Utils } from './utils.spec';
describe('PDFGrid_longtext_innercell',()=>{
it('PDFGrid_longtext_innercell_rowspan', (done) => {
let document : PdfDocument = new PdfDocument();
// add a page
let page1 : PdfPage = document.pages.add();
// create a PdfGrid
let parentGrid : PdfGrid = new PdfGrid();
//add column
parentGrid.columns.add(3);
// add row
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow(); ;
// add nested grid
let childPdfGrid : PdfGrid = new PdfGrid();
//Set the column and rows for child grid
childPdfGrid.columns.add(3);
let childpdfGridRow1 :PdfGridRow;
let childpdfGridRow2 :PdfGridRow;
childpdfGridRow1 = childPdfGrid.rows.addRow();
childpdfGridRow2 = childPdfGrid.rows.addRow();
childpdfGridRow1.cells.getCell(2).rowSpan = 2;
childpdfGridRow1.cells.getCell(0).value = "the value is 0 0 points are equal then point 5";
childpdfGridRow1.cells.getCell(1).value = "1 1";
childpdfGridRow1.cells.getCell(2).value = "2 2";
childpdfGridRow2.cells.getCell(0).value = "3 3";
childpdfGridRow2.cells.getCell(1).value = "the Cell value is 4 4 ";
childpdfGridRow2.cells.getCell(2).value = "the Cell value is 5 6 nested grid value";
pdfGridRow1.cells.getCell(0).value="Nested Table";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow1.cells.getCell(2).value="last";
pdfGridRow2.cells.getCell(0).value="implementation of long test support in multiple nested grid implementation of long test support in multiple nested grid implementation of long test support in multiple nested grid implementation of long test support in multiple nested grid";
pdfGridRow2.cells.getCell(1).value="first row has 2 lines and second row has 3 lines";
pdfGridRow2.cells.getCell(2).value=childPdfGrid;
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_longtext_rowspan.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_longtext_rowspan.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
// destroy the document
document.destroy();
})
})
describe('PDFGrid_Both_1_to_1(parent_rowspan)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(4);
parentGrid.columns.getColumn(0).width=50;
//parentGrid.columns.getColumn(2).width=300;
parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow3 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(0).width=30;
// childPdfGrid.columns.getColumn(1).width=50;
childPdfGrid.columns.getColumn(2).width=50;
let childpdfGridRow1 :PdfGridRow;
let childpdfGridRow2 :PdfGridRow;
childpdfGridRow1 = childPdfGrid.rows.addRow();
childpdfGridRow2 = childPdfGrid.rows.addRow();
childpdfGridRow1.cells.getCell(0).value = "the value is 0 0 points are equal then point 5";
childpdfGridRow1.cells.getCell(1).value = "1 1";
childpdfGridRow1.cells.getCell(2).value = "2 2";
childpdfGridRow2.cells.getCell(0).value = "3 3";
childpdfGridRow2.cells.getCell(1).value = "the Cell value is 4 4 nested grid ";
childpdfGridRow2.cells.getCell(2).value = "the Cell value is 5 6";
pdfGridRow2.cells.getCell(0).rowSpan = 2;
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
pdfGridRow3.cells.getCell(3).value=childPdfGrid;
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_2to2(first)parent_rowspan.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_2to2(first)parent_rowspan.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_multiplegrid',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(4);
parentGrid.columns.getColumn(0).width=200;
// parentGrid.columns.getColumn(1).width=120;
// parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
// childPdfGrid.columns.getColumn(0).width=30;
childPdfGrid.columns.getColumn(1).width=50;
// childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
let childPdfGrid2 : PdfGrid = new PdfGrid();
childPdfGrid2.columns.add(3);
childPdfGrid2.columns.getColumn(0).width=70;
let childpdfGridRow12 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow12 = childPdfGrid2.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow12.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value=childPdfGrid;
pdfGridRow2.cells.getCell(2).value=childPdfGrid2;
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_multiplegrid.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_multiplegrid.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_onepage',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(4);
parentGrid.columns.getColumn(0).width=200;
// parentGrid.columns.getColumn(1).width=120;
// parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow3 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow4 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow5 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow6 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow7 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow8 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow9 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow10 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow11 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow12 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow13 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow14 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow15 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow16 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow17 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow18 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow19 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow20 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
// childPdfGrid.columns.getColumn(0).width=30;
childPdfGrid.columns.getColumn(1).width=50;
// childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow7.cells.getCell(2).value=childPdfGrid;
pdfGridRow15.cells.getCell(3).value=childPdfGrid;
pdfGridRow12.cells.getCell(2).value=childPdfGrid;
pdfGridRow3.cells.getCell(1).value=childPdfGrid;
pdfGridRow18.cells.getCell(3).value=childPdfGrid;
pdfGridRow17.cells.getCell(2).value=" Implementation process";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_onepage(long).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_onepage(long).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_singlechild(point)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
parentGrid.columns.getColumn(0).width=180;
parentGrid.columns.getColumn(1).width=220;
parentGrid.columns.getColumn(2).width=250;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
// childPdfGrid.columns.getColumn(0).width=30;
// childPdfGrid.columns.getColumn(1).width=50;
childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(100,200));
//document.save('PDFGrid_EJ2-11297_singlechild(points).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_singlechild(points).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_inner_characterwrap',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
parentGrid.columns.getColumn(0).width=70;
parentGrid.columns.getColumn(1).width=130;
parentGrid.columns.getColumn(2).width=60;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(0).width=30;
childPdfGrid.columns.getColumn(1).width=50;
// childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
let childpdfGridRow2 :PdfGridRow;
childpdfGridRow1 = childPdfGrid.rows.addRow();
childpdfGridRow2 = childPdfGrid.rows.addRow();
childpdfGridRow1.cells.getCell(0).value= "fixed width changes";
childpdfGridRow1.cells.getCell(1).value= "RowImplementation";
childpdfGridRow1.cells.getCell(2).value= "Nested grid";
childpdfGridRow2.cells.getCell(0).value= "cell value";
childpdfGridRow2.cells.getCell(1).value= "changes123";
childpdfGridRow2.cells.getCell(2).value= "columns to changes";
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(0).value="Fixed width Implementation in nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Nested grid";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_inner_characterwrap.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_inner_characterwrap.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_outer_characterwrap',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
parentGrid.columns.getColumn(0).width=70;
parentGrid.columns.getColumn(1).width=130;
parentGrid.columns.getColumn(2).width=60;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(0).width=30;
childPdfGrid.columns.getColumn(1).width=50;
// childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
let childpdfGridRow2 :PdfGridRow;
childpdfGridRow1 = childPdfGrid.rows.addRow();
childpdfGridRow2 = childPdfGrid.rows.addRow();
childpdfGridRow1.cells.getCell(0).value= "fixed width changes kfjsdajfd jdsaf djalkd f";
childpdfGridRow1.cells.getCell(1).value= "RowImplementation";
childpdfGridRow1.cells.getCell(2).value= "Nested grid";
childpdfGridRow2.cells.getCell(0).value= "cell value";
childpdfGridRow2.cells.getCell(1).value= "changes123";
childpdfGridRow2.cells.getCell(2).value= "columns to changes";
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(0).value="Fixed width Implementation in nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="RowImplementationColumnImplementationCellImplementation123456789";
pdfGridRow2.cells.getCell(2).value="Nested grid";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_outer_characterwrap.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_outer_characterwrap.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_both3in2(Fc)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
parentGrid.columns.getColumn(0).width=50;
parentGrid.columns.getColumn(1).width=120;
parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(0).width=30;
childPdfGrid.columns.getColumn(1).width=50;
// childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
let childpdfGridRow2 :PdfGridRow;
childpdfGridRow1 = childPdfGrid.rows.addRow();
childpdfGridRow2 = childPdfGrid.rows.addRow();
childpdfGridRow1.cells.getCell(0).value= "fixed width changes";
childpdfGridRow1.cells.getCell(1).value= "RowImplementation";
childpdfGridRow1.cells.getCell(2).value= "Nested grid";
childpdfGridRow2.cells.getCell(0).value= "cell value";
childpdfGridRow2.cells.getCell(1).value= "changes123";
childpdfGridRow2.cells.getCell(2).value= "columns to changes";
pdfGridRow1.cells.getCell(0).value="nested grid";
// for (var i = 0; i <2; i++)
// {
// childpdfGridRow1 = childPdfGrid.rows.addRow();
// for (var j = 0; j < 3; j++)
// {
// childpdfGridRow1.cells.getCell(j).value = " Row Implementation ";
// }
// }
pdfGridRow1.cells.getCell(0).value="Fixed width Implementation in nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Nested grid";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_both3in2(Fc).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_both3in2(Fc).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_Maximumcolumns',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(2);
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(10);
let childpdfGridRow1 :PdfGridRow = childPdfGrid.rows.addRow();
childpdfGridRow1.cells.getCell(0).value = "Child Grid Cell 1 are equal";
childpdfGridRow1.cells.getCell(1).value = "Child Grid Cell 2";
childpdfGridRow1.cells.getCell(2).value = "Child Grid Cell 3";
childpdfGridRow1.cells.getCell(3).value = "Child Grid Cell 4";
childpdfGridRow1.cells.getCell(4).value = "Child Grid Cell 5";
childpdfGridRow1.cells.getCell(5).value = "Child Grid Cell 6 implementation";
childpdfGridRow1.cells.getCell(6).value = "Child Grid Cell 7";
childpdfGridRow1.cells.getCell(7).value = "Child Grid Cell 8";
childpdfGridRow1.cells.getCell(8).value = "Child Grid Cell 9";
childpdfGridRow1.cells.getCell(9).value = "Child Grid Cell 10";
// for (var i = 0; i <10; i++){
// childPdfGrid.columns.getColumn(i).width=40;
// }
pdfGridRow1.cells.getCell(0).value = childPdfGrid;
//pdfGridRow2.cells.getCell(2).value=childPdfGrid;
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_nestedgrid(Maximumcolumns).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_nestedgrid(Maximumcolumns).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_Both_2_to_1_last(rowspan)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(4);
//parentGrid.columns.getColumn(0).width=50;
parentGrid.columns.getColumn(1).width=100;
parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow3 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(2).width=60;
// childPdfGrid.columns.getColumn(1).width=50;
// childPdfGrid.columns.getColumn(2).width=60;
let childpdfGridRow1 :PdfGridRow;
let childpdfGridRow2 :PdfGridRow;
let childpdfGridRow3 :PdfGridRow;
childpdfGridRow1 = childPdfGrid.rows.addRow();
childpdfGridRow2 = childPdfGrid.rows.addRow();
childpdfGridRow3 = childPdfGrid.rows.addRow();
childpdfGridRow2.cells.getCell(2).rowSpan = 2;
childpdfGridRow1.cells.getCell(0).value = "the value is 0 0 points are equal then point 5";
childpdfGridRow1.cells.getCell(1).value = "1 1";
childpdfGridRow1.cells.getCell(2).value = "2 2";
childpdfGridRow2.cells.getCell(0).value = "3 3";
childpdfGridRow2.cells.getCell(1).value = "the Cell value is 4 4 nested grid ";
childpdfGridRow2.cells.getCell(2).value = "the Cell value is 5 6";
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value= childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_2to1(last)rowspan.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_2to1(last)rowspan.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_Both_1_to_1(center_rowspan)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(4);
//parentGrid.columns.getColumn(0).width=50;
parentGrid.columns.getColumn(1).width=300;
// parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow3 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(1).width=60;
// childPdfGrid.columns.getColumn(1).width=50;
// childPdfGrid.columns.getColumn(2).width=60;
let childpdfGridRow1 :PdfGridRow;
let childpdfGridRow2 :PdfGridRow;
childpdfGridRow1 = childPdfGrid.rows.addRow();
childpdfGridRow2 = childPdfGrid.rows.addRow();
childpdfGridRow1.cells.getCell(0).rowSpan = 2;
childpdfGridRow1.cells.getCell(0).value = "the value is 0 0 points are equal then point 5";
childpdfGridRow1.cells.getCell(1).value = "1 1";
childpdfGridRow1.cells.getCell(2).value = "2 2";
childpdfGridRow2.cells.getCell(0).value = "3 3";
childpdfGridRow2.cells.getCell(1).value = "the Cell value is 4 4 nested grid ";
childpdfGridRow2.cells.getCell(2).value = "the Cell value is 5 6";
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_1to1(center)rowspan.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_1to1(center)rowspan.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_1_to_1(below20)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
parentGrid.columns.getColumn(1).width = 80;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(2).width = 20;
let childpdfGridRow1 :PdfGridRow;
let childpdfGridRow2 : PdfGridRow;
let childpdfGridRow3 : PdfGridRow;
childpdfGridRow1 = childPdfGrid.rows.addRow();
childpdfGridRow3 = childPdfGrid.rows.addRow();
childpdfGridRow2 = childPdfGrid.rows.addRow();
childpdfGridRow1.cells.getCell(0).value= "Row";
childpdfGridRow1.cells.getCell(1).value= "RowImplementation";
childpdfGridRow1.cells.getCell(2).value= "Nested grid";
childpdfGridRow2.cells.getCell(0).value= "1 1";
childpdfGridRow2.cells.getCell(1).value= "changes123";
childpdfGridRow2.cells.getCell(2).value= "columns 2 changes";
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_1to1(below20).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_1to1(below20).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_0_to_1(rowspan)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(4);
//parentGrid.columns.getColumn(0).width=50;
//parentGrid.columns.getColumn(2).width=300;
// parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow3 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(0).width=60;
// childPdfGrid.columns.getColumn(1).width=50;
// childPdfGrid.columns.getColumn(2).width=60;
let childpdfGridRow1 :PdfGridRow;
let childpdfGridRow2 :PdfGridRow;
childpdfGridRow1 = childPdfGrid.rows.addRow();
childpdfGridRow2 = childPdfGrid.rows.addRow();
childpdfGridRow1.cells.getCell(2).rowSpan = 2;
childpdfGridRow1.cells.getCell(0).value = "the value is 0 0 points are equal then point 5";
childpdfGridRow1.cells.getCell(1).value = "1 1";
childpdfGridRow1.cells.getCell(2).value = "2 2";
childpdfGridRow2.cells.getCell(0).value = "3 3";
childpdfGridRow2.cells.getCell(1).value = "the Cell value is 4 4 nested grid ";
childpdfGridRow2.cells.getCell(2).value = "the Cell value is 5 6";
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_0to1(first)rowspan.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_0to1(first)rowspan.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_nestedgrid_longtext(default)',()=>{
it("single-long-row", (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(1);
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(10);
let childpdfGridRow1 :PdfGridRow = childPdfGrid.rows.addRow();
//let childpdfGridRow2 :PdfGridRow = childPdfGrid.rows.addRow();
childpdfGridRow1.cells.getCell(0).value = "Child Grid Cell 1 are equal";
childpdfGridRow1.cells.getCell(1).value = "Fixed width";
childpdfGridRow1.cells.getCell(2).value = "Child Grid Cell 3";
childpdfGridRow1.cells.getCell(3).value = "Child Grid Cell 4";
childpdfGridRow1.cells.getCell(4).value = "Child Grid Cell 5";
childpdfGridRow1.cells.getCell(5).value = "Child Grid Cell 6 implementation";
childpdfGridRow1.cells.getCell(6).value = "Child Grid Cell 7";
childpdfGridRow1.cells.getCell(7).value = "Row Implementation";
childpdfGridRow1.cells.getCell(8).value = "Child Grid Cell 9";
childpdfGridRow1.cells.getCell(9).value = "Child Grid Cell 10";
for (var i = 0; i <10; i++){
childPdfGrid.columns.getColumn(i).width = 40;
}
pdfGridRow1.cells.getCell(0).value = childPdfGrid;
//pdfGridRow2.cells.getCell(2).value=childPdfGrid;
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_nestedgrid_longtext(default).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_nestedgrid_longtext(default).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_single_grid_font',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
let font : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 12);
let font2 : PdfFont = new PdfStandardFont(PdfFontFamily.Helvetica, 14);
let childPdfGrid : PdfGrid = new PdfGrid();
parentGrid.style.font=font;
childPdfGrid.style.font=font2;
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(1).width=40;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "cell word";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_single_grid_font.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_single_grid_font.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_nestedgrid_longtext(middle)',()=>{
it("single-long-row", (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(1);
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(10);
let childpdfGridRow1 :PdfGridRow = childPdfGrid.rows.addRow();
childpdfGridRow1.cells.getCell(0).value = "Child Grid Cell 1 are equal";
childpdfGridRow1.cells.getCell(1).value = "Child Grid Cell 2";
childpdfGridRow1.cells.getCell(2).value = "Child Grid Cell 3";
childpdfGridRow1.cells.getCell(3).value = "Child Grid Cell 4";
childpdfGridRow1.cells.getCell(4).value = "Child Grid Cell 5";
childpdfGridRow1.cells.getCell(5).value = "Child Grid Cell 6";
childpdfGridRow1.cells.getCell(6).value = "Child Grid Cell 7";
childpdfGridRow1.cells.getCell(7).value = "Child Grid Cell 8";
childpdfGridRow1.cells.getCell(8).value = "Child Grid Cell 9";
childpdfGridRow1.cells.getCell(9).value = "Child Grid Cell 10";
childPdfGrid.columns.getColumn(5).width=20.55;
// for (var i = 0; i <10; i++){
// childPdfGrid.columns.getColumn(i).width=51.5;
// }
pdfGridRow1.cells.getCell(0).value = childPdfGrid;
//pdfGridRow2.cells.getCell(2).value=childPdfGrid;
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_nestedgrid_longtext(middle).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_nestedgrid_longtext(middle).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_Multiple_inner_grid(inner)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
// add a page
let page1 : PdfPage = document.pages.add();
// create a PdfGrid
let parentGrid : PdfGrid = new PdfGrid();
//add column
parentGrid.columns.add(3);
// add row
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow3 : PdfGridRow = parentGrid.rows.addRow();
parentGrid.columns.getColumn(1).width = 100;
// add nested grid
let childPdfGrid : PdfGrid = new PdfGrid();
//Set the column and rows for child grid
childPdfGrid.columns.add(3);
let childpdfGridRow1 :PdfGridRow;
childPdfGrid.columns.getColumn(2).width = 20;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = j +" "+ i;
}
}
let childPdfGrid2 : PdfGrid = new PdfGrid();
//Set the column and rows for child grid
childPdfGrid2.columns.add(2);
let childpdfGridRow12 :PdfGridRow;
childPdfGrid2.columns.getColumn(0).width = 10;
for (var i = 0; i <2; i++)
{
childpdfGridRow12 = childPdfGrid2.rows.addRow();
for (var j = 0; j < 2; j++)
{
childpdfGridRow12.cells.getCell(j).value = " "+ j ;
}
}
let childPdfGrid3 : PdfGrid = new PdfGrid();
//Set the column and rows for child grid
childPdfGrid3.columns.add(2);
let childpdfGridRow13 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow13 = childPdfGrid3.rows.addRow();
for (var j = 0; j < 2; j++)
{
childpdfGridRow13.cells.getCell(j).value =" "+ j ;
}
}
// drawing a grid
pdfGridRow1.cells.getCell(0).value=childPdfGrid;
pdfGridRow1.cells.getCell(2).value="This is the example sample for pdf nested grid support in EJ2 pdf -library using typescript";
pdfGridRow2.cells.getCell(1).value=childPdfGrid;
pdfGridRow3.cells.getCell(2).value=" Nested Grid";
childpdfGridRow1.cells.getCell(1).value=childPdfGrid2;
childpdfGridRow12.cells.getCell(0).value=childPdfGrid3;
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_Multiple_grid(inner).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_Multiple_grid(inner).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
// destroy the document
document.destroy();
})
})
describe('PDFGrid_1_to_1(below20)Columnspan',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow3 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow4 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow5 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow6 : PdfGridRow = parentGrid.rows.addRow();
parentGrid.columns.getColumn(1).width = 80;
let childPdfGrid : PdfGrid = new PdfGrid();
pdfGridRow5.cells.getCell(1).columnSpan = 2;
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(2).width = 40;
let childpdfGridRow1 :PdfGridRow;
let childpdfGridRow2 : PdfGridRow;
let childpdfGridRow3 : PdfGridRow;
childpdfGridRow1 = childPdfGrid.rows.addRow();
childpdfGridRow3 = childPdfGrid.rows.addRow();
childpdfGridRow2 = childPdfGrid.rows.addRow();
childpdfGridRow1.cells.getCell(0).columnSpan = 2;
childpdfGridRow1.cells.getCell(0).value= "Row";
childpdfGridRow1.cells.getCell(1).value= "RowImplementation";
childpdfGridRow1.cells.getCell(2).value= "Nested grid";
childpdfGridRow2.cells.getCell(0).value= "1 1";
childpdfGridRow2.cells.getCell(1).value= "changes123";
childpdfGridRow2.cells.getCell(2).value= "columns 2 changes";
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow3.cells.getCell(1).value="hello";
pdfGridRow4.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_1to1(below20)Columnspan.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_1to1(below20)Columnspan.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_Multiple_inner_grid',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
// add a page
let page1 : PdfPage = document.pages.add();
// create a PdfGrid
let parentGrid : PdfGrid = new PdfGrid();
//add column
parentGrid.columns.add(3);
// add row
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow3 : PdfGridRow = parentGrid.rows.addRow();
parentGrid.columns.getColumn(1).width = 100;
// add nested grid
let childPdfGrid : PdfGrid = new PdfGrid();
//Set the column and rows for child grid
childPdfGrid.columns.add(3);
let childpdfGridRow1 :PdfGridRow;
childPdfGrid.columns.getColumn(2).width = 20;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = j +" "+ i;
}
}
let childPdfGrid2 : PdfGrid = new PdfGrid();
//Set the column and rows for child grid
childPdfGrid2.columns.add(2);
let childpdfGridRow12 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow12 = childPdfGrid2.rows.addRow();
for (var j = 0; j < 2; j++)
{
childpdfGridRow12.cells.getCell(j).value = " "+ j ;
}
}
let childPdfGrid3 : PdfGrid = new PdfGrid();
//Set the column and rows for child grid
childPdfGrid3.columns.add(2);
let childpdfGridRow13 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow13 = childPdfGrid3.rows.addRow();
for (var j = 0; j < 2; j++)
{
childpdfGridRow13.cells.getCell(j).value =" "+ j ;
}
}
// drawing a grid
pdfGridRow1.cells.getCell(0).value=childPdfGrid;
pdfGridRow1.cells.getCell(2).value="This is the example sample for pdf nested grid support in EJ2 pdf -library using typescript";
pdfGridRow2.cells.getCell(1).value=childPdfGrid;
pdfGridRow3.cells.getCell(2).value=" Nested Grid";
childpdfGridRow1.cells.getCell(1).value=childPdfGrid2;
childpdfGridRow12.cells.getCell(0).value=childPdfGrid3;
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_Multiple_grid.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_Multiple_grid.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
// destroy the document
document.destroy();
})
})
describe('PDFGrid_both1in2(first&last)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
//parentGrid.columns.getColumn(0).width=100;
parentGrid.columns.getColumn(1).width=200;
// parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(1).width=90;
//childPdfGrid.columns.getColumn(1).width=60;
childPdfGrid.columns.getColumn(2).width=70;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+ " width value";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_both1in2(first&last).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_both1in2(first&last).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_both2in1(first)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
// parentGrid.columns.getColumn(0).width=60;
parentGrid.columns.getColumn(1).width=160;
parentGrid.columns.getColumn(0).width=30;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(0).width=70;
// childPdfGrid.columns.getColumn(1).width=50;
// childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width vlaue for 3rd column";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_both2in1(first).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_both2in1(first).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_simple_grid',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
// parentGrid.columns.getColumn(0).width=50;
// parentGrid.columns.getColumn(1).width=120;
// parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
// childPdfGrid.columns.getColumn(0).width=30;
// childPdfGrid.columns.getColumn(1).width=50;
// childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_simplegrid.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_simplegrid.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_both_2in2(last)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
// parentGrid.columns.getColumn(0).width=50;
parentGrid.columns.getColumn(1).width=180;
parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
// childPdfGrid.columns.getColumn(0).width=30;
childPdfGrid.columns.getColumn(1).width=50;
childPdfGrid.columns.getColumn(2).width=100;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_both_2in2(last).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_both_2in2(last).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_1_to_1(center)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
//parentGrid.columns.getColumn(0).width=50;
parentGrid.columns.getColumn(1).width=120;
// parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
// childPdfGrid.columns.getColumn(0).width=30;
childPdfGrid.columns.getColumn(1).width=50;
//childPdfGrid.columns.getColumn(2).width=60;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_1to1(center).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_1to1(center).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_Both_1_to_1(first)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
//parentGrid.columns.getColumn(0).width=50;
parentGrid.columns.getColumn(1).width=120;
// parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(0).width=60;
// childPdfGrid.columns.getColumn(1).width=50;
// childPdfGrid.columns.getColumn(2).width=60;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_1to1(first).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_1to1(first).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_singlechild(center)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
// parentGrid.columns.getColumn(0).width=50;
// parentGrid.columns.getColumn(1).width=120;
// parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
// childPdfGrid.columns.getColumn(0).width=30;
childPdfGrid.columns.getColumn(1).width=30;
// childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_singlechild(center).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_singlechild(center).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_singlechild(first)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
// parentGrid.columns.getColumn(0).width=50;
// parentGrid.columns.getColumn(1).width=120;
// parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(0).width=30;
// childPdfGrid.columns.getColumn(1).width=50;
// childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_singlechild(first).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_singlechild(first).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_singlechild',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
// parentGrid.columns.getColumn(0).width=50;
// parentGrid.columns.getColumn(1).width=120;
// parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
// childPdfGrid.columns.getColumn(0).width=30;
// childPdfGrid.columns.getColumn(1).width=50;
childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_singlechild(last).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_singlechild(last).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_nestedchild(Extra)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
parentGrid.columns.getColumn(0).width=50;
parentGrid.columns.getColumn(1).width=120;
parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(0).width=70;
childPdfGrid.columns.getColumn(1).width=60;
childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_nestedchild(extra).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_nestedchild(extra).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_Nested_parentonly',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
parentGrid.columns.getColumn(0).width=50;
parentGrid.columns.getColumn(1).width=120;
parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
// childPdfGrid.columns.getColumn(0).width=30;
// childPdfGrid.columns.getColumn(1).width=50;
// childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_Nested_parentonly.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_Nested_parentonly.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_Both',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
parentGrid.columns.getColumn(0).width=50;
parentGrid.columns.getColumn(1).width=120;
parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(0).width=30;
childPdfGrid.columns.getColumn(1).width=50;
childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_BothGrid.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_BothGrid.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_Nested-childonly',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
// parentGrid.columns.getColumn(0).width=50;
// parentGrid.columns.getColumn(1).width=120;
// parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
childPdfGrid.columns.getColumn(0).width=30;
childPdfGrid.columns.getColumn(1).width=50;
childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_Nestedchildonly.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_Nestedchildonly.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_singleparent(center)',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
// parentGrid.columns.getColumn(0).width=50;
parentGrid.columns.getColumn(1).width=120;
// parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
// childPdfGrid.columns.getColumn(0).width=30;
// childPdfGrid.columns.getColumn(1).width=50;
// childPdfGrid.columns.getColumn(2).width=40;
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_singleparent(center).pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_singleparent(center).pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_singlegrid_parent_rowheight',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(4);
parentGrid.columns.getColumn(0).width=100;
parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow3 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow5 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow4 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.grid.size.width=100;
pdfGridRow5.cells.getCell(0).height=100;
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value="Fixed width";
pdfGridRow2.cells.getCell(2).value="single word";
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="childPdfGrid";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_singlegrid_parent_rowheight.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_singlegrid_parent_rowheight.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_singlegrid_parent_width',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(4);
parentGrid.columns.getColumn(0).width=100;
parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow3 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow5 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow4 : PdfGridRow = parentGrid.rows.addRow();
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value="Fixed width";
pdfGridRow2.cells.getCell(2).value="single word";
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="childPdfGrid";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_singlegrid_parent_width.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_singlegrid_parent_width.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
})
describe('PDFGrid_nestedgrid_parent_width',()=>{
it('PDFGrid', (done) => {
let document : PdfDocument = new PdfDocument();
let page1 : PdfPage = document.pages.add();
let parentGrid : PdfGrid = new PdfGrid();
parentGrid.columns.add(3);
parentGrid.columns.getColumn(1).width=100;
parentGrid.columns.getColumn(2).width=50;
let pdfGridRow1 : PdfGridRow = parentGrid.rows.addRow();
let pdfGridRow2 : PdfGridRow = parentGrid.rows.addRow();
//pdfGridRow1.cells.getCell(1).width=50;
let childPdfGrid : PdfGrid = new PdfGrid();
childPdfGrid.columns.add(3);
let childpdfGridRow1 :PdfGridRow;
for (var i = 0; i <2; i++)
{
childpdfGridRow1 = childPdfGrid.rows.addRow();
for (var j = 0; j < 3; j++)
{
childpdfGridRow1.cells.getCell(j).value = "Cell "+ j +" "+ i+" width";
}
}
pdfGridRow1.cells.getCell(0).value="nested grid";
pdfGridRow1.cells.getCell(1).value=childPdfGrid;
pdfGridRow2.cells.getCell(1).value="hello";
pdfGridRow2.cells.getCell(2).value="Fixed width";
// drawing a grid
parentGrid.draw(page1, new PointF(0,0));
//document.save('PDFGrid_EJ2-11297_nestedgrid_parent_width.pdf');
document.save().then((xlBlob: { blobData: Blob }) => {
if (Utils.isDownloadEnabled) {
Utils.download(xlBlob.blobData, 'PDFGrid_EJ2-11297_nestedgrid_parent_width.pdf');
}
let reader: FileReader = new FileReader();
reader.readAsArrayBuffer(xlBlob.blobData);
reader.onload = (): void => {
if (reader.readyState == 2) { // DONE == 2
expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0);
done();
}
}
});
document.destroy();
})
}) | the_stack |
import { prraypromise, PrrayPromise } from './prraypromise'
import * as methods from './methods'
// TODO: thisArg
export default class Prray<T> extends Array<T> {
/**
_Compatible with [`Array.of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of) but returns a Prray instance._
The Prray.of() method creates a new Prray instance from a variable number of arguments, regardless of number or type of the arguments.
```javascript
const prr = Prray.of(1, 2, 3, 4)
```
* @param args
*/
static of<T>(...args: T[]): Prray<T> {
return Prray.from(args)
}
/**
The Prray.isArray() method determines whether the passed value is a Prray instance.
```javascript
Prray.isPrray([1, 2, 3]) // false
Prray.isPrray(new Prray(1, 2, 3)) // true
```
* @param obj
*/
static isPrray(obj: any): boolean {
return obj instanceof Prray
}
/**
_Compatible with [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) but returns a Prray instance._
The Prray.from() method creates a new, shallow-copied Prray instance from an array-like or iterable object.
```javascript
const prr = Prray.from([1, 2, 3, 4])
```
* @param arrayLike
*/
static from<T>(arrayLike: Iterable<T> | ArrayLike<T>): Prray<T>
static from<T, U>(arrayLike: Iterable<T> | ArrayLike<T>, mapFunc: (v: T, ix: number) => U, thisArg?: any): Prray<U>
static from<T, U>(
arrayLike: Iterable<T> | ArrayLike<T>,
mapFunc?: (v: T, ix: number) => U,
thisArg?: any,
): Prray<any> {
const arr = mapFunc === undefined ? super.from(arrayLike) : super.from(arrayLike, mapFunc, thisArg)
const prr = new Prray()
for (let i = arr.length - 1; i >= 0; i--) {
prr[i] = arr[i]
}
return prr
}
/**
The Prray.delay() method returns a promise (`PrrayPromise` exactly) that will be resolved after given ms milliseconds.
```javascript
await Prray.delay(1000) // resolve after 1 second
const prr = Prray.from([1,2,3])
await prr
.mapAsync(action1)
.delay(500) // delay 500ms between two iterations
.forEach(action2)
```
* @param ms
*/
static delay<T>(ms: number): PrrayPromise<T> {
const prray = new Prray<T>()
return new PrrayPromise(resolve => setTimeout(() => resolve(prray), ms))
}
constructor(length: number)
constructor(...args: T[])
constructor(...args: any[]) {
super(...args)
}
/**
_Think of it as an async version of method `map`_
The mapAsync() method returns a promise (`PrrayPromise` exactly) that resolved with a new prray with the resolved results of calling a provided async function on every element in the calling prray, or rejected immediately if any of the promises reject.
The provided async function is called on every element concurrently. You may optionally specify a concurrency limit.
- `func(currentValue, index, prray)`
- options
- `concurrency` Number of concurrently pending promises returned by provided function. Default: `Infinity`
```javascript
const urls = Prray.from(urlArray)
const jsons = await urls.mapAsync(fetch).mapAsync(res => res.json())
await jsons.mapAsync(insertToDB, { concurrency: 2 })
```
* @param func
* @param opts
*/
mapAsync<U>(
func: (currentValue: T, index: number, prray: Prray<T>) => Promise<U> | U,
opts?: { concurrency: number },
): PrrayPromise<U> {
const promise = methods.mapAsync(this, func, opts)
return prraypromise(promise.then(arr => Prray.from(arr)))
}
map<U>(func: (currentValue: T, index: number, prray: Prray<T>) => U): Prray<U> {
return _ensurePrray(methods.map(this, func))
}
/**
_Think of it as an async version of method `filter`_
The filterAsync() method returns a promise (`PrrayPromise` exactly) that resolved with a new prray with all elements that pass the test implemented by the provided async function, or rejected immediately if any of the promises reject.
The provided async function is called on every element concurrently. You may optionally specify a concurrency limit.
- `func(currentValue, index, prray)`
- options
- `concurrency` Number of concurrently pending promises returned by provided function. Default: `Infinity`
```javascript
const files = Prray.from(fileArray)
await files.filterAsync(isExisted).mapAsync(removeFile)
await files.filterAsync(isExisted, { concurrency: 2 })
```
* @param func
* @param opts
*/
filterAsync(
func: (currentValue: T, index: number, prray: Prray<T>) => Promise<boolean> | boolean,
opts?: { concurrency: number },
): PrrayPromise<T> {
const promise = methods.filterAsync(this, func, opts)
return prraypromise(promise.then(arr => Prray.from(arr)))
}
filter(func: (currentValue: T, index: number, prray: Prray<T>) => boolean): Prray<T> {
return _ensurePrray(methods.filter(this, func))
}
/**
_Think of it as an async version of method `reduce`_
The reduceAsync() method executes a async reducer function (that you provide) on each element of the prray, resulting in a single output value resolved by a promise (`PrrayPromise` exactly).
```javascript
const productIds = Prray.from(idArray)
const total = await productIds.reduceAsync(async (total, id) => {
const price = await getPrice(id)
return total + price
}, 0)
```
* @param func
*/
reduceAsync(func: (accumulator: T, currentValue: T, index: number, prray: Prray<T>) => T | Promise<T>): Promise<T>
reduceAsync(
func: (accumulator: T, currentValue: T, index: number, prray: Prray<T>) => T | Promise<T>,
initialValue: T,
): Promise<T>
reduceAsync<U>(
func: (accumulator: U, currentValue: T, index: number, prray: Prray<T>) => U | Promise<U>,
initialValue: U,
): Promise<U>
reduceAsync(
func: (accumulator: any, currentValue: T, index: number, prray: Prray<T>) => any | Promise<any>,
initialValue?: any,
): Promise<any> {
const promise = methods.reduceAsync(this, func, initialValue)
return promise
}
reduce(func: (accumulator: T, currentValue: T, index: number, prray: Prray<T>) => T): T
reduce(func: (accumulator: T, currentValue: T, index: number, prray: Prray<T>) => T, initialValue: T): T
reduce<U>(func: (accumulator: U, currentValue: T, index: number, prray: Prray<T>) => U, initialValue: U): U
reduce(func: (accumulator: any, currentValue: T, index: number, prray: Prray<T>) => any, initialValue?: any): any {
return methods.reduce(this, func, initialValue)
}
/**
_Think of it as an async version of method `reduceRight`_
The reduceRightAsync() method applies an async function against an accumulator and each value of the prray (from right-to-left) to reduce it to a single value.
```javascript
const productIds = Prray.from(idArray)
const total = await productIds.reduceRightAsync(async (total, id) => {
const price = await getPrice(id)
return total + price
}, 0)
```
* @param func
*/
reduceRightAsync(
func: (accumulator: T, currentValue: T, index: number, prray: Prray<T>) => T | Promise<T>,
): Promise<T>
reduceRightAsync(
func: (accumulator: T, currentValue: T, index: number, prray: Prray<T>) => T | Promise<T>,
initialValue: T,
): Promise<T>
reduceRightAsync<U>(
func: (accumulator: U, currentValue: T, index: number, prray: Prray<T>) => U | Promise<U>,
initialValue: U,
): Promise<U>
reduceRightAsync(
func: (accumulator: any, currentValue: T, index: number, prray: Prray<T>) => any | Promise<any>,
initialValue?: any,
): Promise<any> {
const promise = methods.reduceRightAsync(this, func, initialValue)
return promise
}
reduceRight(func: (accumulator: T, currentValue: T, index: number, prray: Prray<T>) => T): T
reduceRight(func: (accumulator: T, currentValue: T, index: number, prray: Prray<T>) => T, initialValue: T): T
reduceRight<U>(func: (accumulator: U, currentValue: T, index: number, prray: Prray<T>) => U, initialValue: U): U
reduceRight(
func: (accumulator: any, currentValue: T, index: number, prray: Prray<T>) => any,
initialValue?: any,
): any {
return methods.reduceRight(this, func, initialValue)
}
/**
_Think of it as an async version of method `sort`_
The sortAsync() method sorts the elements of a prray in place and returns a promise (`PrrayPromise` exactly) resolved with the sorted prray. The provided function can be an async function that returns a promise resolved with a number.
```javascript
const students = Prray.from(idArray)
const rank = await students.sortAsync((a, b) => {
const scoreA = await getScore(a)
const scoreB = await getScore(b)
return scoreA - scoreB
})
```
* @param func
*/
sortAsync(func?: (a: T, b: T) => Promise<number> | number): PrrayPromise<T> {
const promise = methods.sortAsync(this, func)
return prraypromise(promise)
}
/**
_Think of it as an async version of method `find`_
The findAsync() method returns a promise (`PrrayPromise` exactly) resolved with the first element in the prray that satisfies the provided async testing function.
```javascript
const workers = Prray.from(workerArray)
const unhealthy = await workers.findAsync(checkHealth)
```
* @param func
*/
findAsync(
func: (currentValue: T, index: number, prray: Prray<T>) => Promise<boolean> | boolean,
): Promise<T | undefined> {
return methods.findAsync(this, func)
}
find(func: (currentValue: T, index: number, prray: Prray<T>) => boolean): T | undefined {
return methods.find(this, func)
}
/**
_Think of it as an async version of method `findIndex`_
The findIndexAsync() method returns a promise (`PrrayPromise` exactly) resolved with the index of the first element in the prray that satisfies the provided async testing function. Otherwise, it returns promise resolved with -1, indicating that no element passed the test.
```javascript
const workers = Prray.from(workerArray)
const ix = await workers.findIndexAsync(checkHealth)
const unhealthy = workers[ix]
```
*/
findIndexAsync(
func: (currentValue: T, index: number, prray: Prray<T>) => Promise<boolean> | boolean,
): Promise<number> {
return methods.findIndexAsync(this, func)
}
findIndex(func: (currentValue: T, index: number, prray: Prray<T>) => boolean): number {
return methods.findIndex(this, func)
}
/**
_Think of it as an async version of method `every`_
The everyAsync() method tests whether all elements in the prray pass the test implemented by the provided async function. It returns a promise (`PrrayPromise` exactly) that resolved with a Boolean value, or rejected immediately if any of the promises reject.
The provided async function is called on every element concurrently. You may optionally specify a concurrency limit.
- `func(currentValue, index, prray)`
- options
- `concurrency` Number of concurrently pending promises returned by provided function. Default: `Infinity`
```javascript
const filenames = Prray.from(fileNameArray)
const isAllFileExisted = await filenames.everyAsync(isExisted)
if (isAllFileExisted) {
// do some things
}
```
*/
everyAsync(
func: (currentValue: T, index: number, prray: Prray<T>) => Promise<boolean> | boolean,
opts?: { concurrency: number },
): Promise<boolean> {
return methods.everyAsync(this, func, opts)
}
every(func: (currentValue: T, index: number, prray: Prray<T>) => boolean): boolean {
return methods.every(this, func)
}
/**
_Think of it as an async version of method `some`_
The some() method tests whether at least one element in the prray passes the test implemented by the provided async function. It returns a promise (`PrrayPromise` exactly) that resolved with Boolean value, or rejected immediately if any of the promises reject.
The provided async function is called on every element concurrently. You may optionally specify a concurrency limit.
- `func(currentValue, index, prray)`
- options
- `concurrency` Number of concurrently pending promises returned by provided function. Default: `Infinity`
```javascript
const filenames = Prray.from(fileNameArray)
const hasExistedFile = await filenames.someAsync(isExisted)
if (hasExistedFile) {
// do some things
}
```
*/
someAsync(
func: (currentValue: T, index: number, prray: Prray<T>) => Promise<boolean> | boolean,
opts?: { concurrency: number },
): Promise<boolean> {
return methods.someAsync(this, func, opts)
}
some(func: (currentValue: T, index: number, prray: Prray<T>) => boolean): boolean {
return methods.some(this, func)
}
/**
_Think of it as an async version of method `forEach`_
The forEachAsync() method executes a provided async function once for each prray element concurrently. It returns a promise (`PrrayPromise` exactly) that resolved after all iteration promises resolved, or rejected immediately if any of the promises reject.
The provided async function is called on every element concurrently. You may optionally specify a concurrency limit.
- `func(currentValue, index, prray)`
- options
- `concurrency` Number of concurrently pending promises returned by provided function. Default: `Infinity`
```javascript
const emails = Prray.from(emailArray)
await emails.forEachAsync(sendAsync)
await emails.forEachAsync(sendAsync, { concurrency: 20 })
```
* @param func
* @param opts
*/
forEachAsync(
func: (currentValue: T, index: number, prray: Prray<T>) => Promise<any> | any,
opts?: { concurrency: number },
): Promise<undefined> {
return methods.forEachAsync(this, func, opts)
}
forEach(func: (currentValue: T, index: number, prray: Prray<T>) => any): undefined {
return methods.forEach(this, func)
}
slice(start?: number, end?: number): Prray<T> {
const result: T[] = super.slice(start, end)
return _ensurePrray(result)
}
concat(...items: ConcatArray<T>[]): Prray<T>
concat(...items: (ConcatArray<T> | T)[]): Prray<T>
concat(...items: any[]): Prray<T> {
return _ensurePrray(super.concat(...items))
}
reverse(): Prray<T> {
return super.reverse() as Prray<T>
}
splice(start: number): Prray<T>
splice(start: number, deleteCount: number): Prray<T>
splice(start: number, deleteCount: number, ...items: T[]): Prray<T>
splice(start: number, deleteCount?: number, ...items: T[]): Prray<T> {
// Why? If pass parameter deleteCount as undefined directly, the delete count will be zero actually :(
const result = deleteCount === undefined ? super.splice(start) : super.splice(start, deleteCount, ...items)
return _ensurePrray(result)
}
/**
The toArray() method returns a new normal array with every element in the prray.
```javascript
const prr = new Prray(1, 2, 3)
prr.toArray() // [1,2,3]
```
*/
toArray(): T[] {
return [...this]
}
/**
The delay() method returns a promise (`PrrayPromise` exactly) that will be resolved with current prray instance after given ms milliseconds.
```javascript
const emails = Prray.from(emailArray)
await emails
.mapAsync(registerReceiver)
.delay(1000)
.forEachAsync(send)
```
*/
delay(ms: number): PrrayPromise<T> {
return new PrrayPromise(resolve => setTimeout(() => resolve(this), ms))
}
}
export function _ensurePrray<T>(arr: T[]): Prray<T> {
if (arr instanceof Prray) {
return arr
} else {
return Prray.from(arr)
}
} | the_stack |
import { getMineProjectList } from '@/api/common';
import { generateId } from '@/common/js/util';
import PermissionApplyWindow from '@/pages/authCenter/permissions/PermissionApplyWindow';
import { EmptyView } from '@/pages/DataModelManage/Components/Common/index';
import { MenuItemList, ModelLeftMenu, ModeRight } from '@/pages/DataModelManage/Components/index';
import { Component, Ref, Watch } from 'vue-property-decorator';
import { VNode } from 'vue/types/umd';
import { cancelTop, deleteModel, getModelList, topModel } from './Api/index';
import { DataModelManageBase } from './Controller/DataModelManageBase';
import { IUpdateEvent, TabItem } from './Controller/DataModelTabManage';
@Component({
components: { ModelLeftMenu, MenuItemList, EmptyView, ModeRight, PermissionApplyWindow },
})
export default class DMMIndex extends DataModelManageBase {
@Ref() public readonly projectApply!: VNode;
public projectList = [];
public topTabList = [
{ name: 'project', label: '项目' },
{ name: 'market', label: this.$t('公开'), disabled: true, tips: '功能暂未开放' },
];
/** 顶部tab选中| 项目或者数据集市 */
public activeTypeName = 'project';
/** fact_table/dimension_table **/
public leftTabList = [
{ name: 'fact_table', label: '事实表数据模型', icon: 'fact-model' },
{ name: 'dimension_table', label: '维度表数据模型', icon: 'dimension-model' },
];
/** 模型列表是否正在加载 */
public isLoadingModelList = false;
/** 模型类型选中 */
public activeModelType = 'fact_table';
/** 项目-模型列表 */
public pDataSource: IDataModelManage.IModelList[] = [];
/** 数据集市-模型列表 */
public sDataSource: IDataModelManage.IModelList[] = [];
/** 用于标识:项目-模型列表是否已经拉取,避免多次请求 */
public isPDatasourceLoad = false;
/** 用于标识:数据集市-模型列表是否已经拉取,避免多次请求 */
public isSDatasourceLoad = false;
/** 搜索值 */
public searchValue = '';
/** 选择项目Tab时,选择项目ID */
public pProjectId: number | string = '';
/** 初始化activeItem */
public isInitActiveItem = false;
public isShowLeftMenu = true;
@Watch('pProjectId', { immediate: true })
public handleProjectIdChanged(val) {
this.getModelInfoByProjectId();
}
@Watch('updateEvents', { deep: true, immediate: true })
public handleUpdateEventFired(val: IUpdateEvent) {
/**
/* updateModelName : 事件来自右侧顶部工具栏更新模型名称
* updateModel : 事件来自右侧表单更新触发
*/
if (val && (val.name === 'updateModel' || val.name === 'updateModelName')) {
this.handleUpdateModel(val.params[0]);
}
}
/** 根据当前选中Tab类型,计算当前模型列表数据 */
get modelInfoList() {
return this.isProject ? this.pDataSource : this.sDataSource;
}
/** 根据model_type过滤当前列表 */
get filterTypeData() {
return this.modelInfoList.filter(info => info.model_type === this.activeModelType);
}
get searchList() {
return this.filterTypeData.filter(
item => String.prototype.includes.call(item.model_name, this.searchValue)
|| String.prototype.includes.call(item.model_alias, this.searchValue)
);
}
get isProject() {
return this.activeTypeName === 'project';
}
get activeLeftTab() {
return this.leftTabList.find(tab => tab.name === this.activeModelType) || {};
}
/** 置顶数据 */
get pinedList() {
return this.searchList.filter(item => item.sticky_on_top);
}
/** 不置顶数据 */
get unPinedList() {
return this.searchList.filter(item => !item.sticky_on_top);
}
/** 设置左侧栏收起/展开 icon */
get expandIcon() {
return this.isShowLeftMenu ? 'icon-shrink-fill' : 'icon-expand-fill';
}
get iconList() {
return {
project: {
icon: 'plus-8',
label: this.$t('新建') + this.activeLeftTab.label,
callback() {
if (this.pProjectId > 0) {
if (
this.DataModelTabManage.insertItem(
new TabItem({
id: 0,
name: 'New Model',
displayName: this.$t('新建模型'),
type: this.activeTypeName,
isNew: true,
projectId: this.pProjectId,
modelType: this.activeLeftTab.name,
modelId: 0,
icon: this.activeLeftTab.icon,
lastStep: 0,
}),
true
)
) {
this.changeRouterWithParams('dataModelEdit',
{ project_id: this.pProjectId }, { modelId: 0 });
// this.appendRouter({ modelId: 0 }, { project_id: this.pProjectId })
}
} else {
this.$bkMessage({
message: this.$t('请选择项目'),
delay: 1000,
theme: 'warning ',
offsetY: 80,
ellipsisLine: 5,
limit: 1,
});
}
},
},
market: {
icon: 'share',
label: '查看数据集市',
callback: () => {
window.open('#/data-mart/data-dictionary/search-result', '_blank');
},
},
};
}
public handleNewModel() {
const curType = this.iconList[this.activeTypeName];
curType.callback.call(this);
this.sendUserActionData({ name: '点击【新建模型】' });
}
/** 点击选中数据表 */
public clickList(item) {
/**
* 数据集市暂时无处跳转,不做处理
* 二期处理数据集市跳转
*/
if (this.activeTypeName === 'project') {
if (
this.DataModelTabManage.activeItemById(item.model_id)
|| this.DataModelTabManage.insertItem(
new TabItem({
id: item.model_id,
modelId: item.model_id,
name: item.model_name,
displayName: item.model_alias,
type: this.activeTypeName,
modelType: this.activeLeftTab.name,
isNew: false,
projectId: item.project_id,
icon: this.activeLeftTab.icon,
lastStep: item.step_id,
publishStatus: item.publish_status,
activeStep: 1,
routeName: 'dataModelView',
}),
true
)
) {
// this.appendRouter({ modelId: item.model_id }, { project_id: item.project_id })
this.changeRouterWithParams(
this.activeModelTabItem?.routeName || 'dataModelView',
{ project_id: item.project_id },
{ modelId: item.model_id }
);
this.updateStorageModelId(item.model_id);
this.updateStorageProjectId(item.project_id);
}
}
}
/**
* 置顶 & 取消置顶
* @param item 操作对象
* @param stickyOnTop 是否置顶
*/
public handleTopData(item, stickyOnTop) {
const { model_id } = item;
(stickyOnTop ? topModel(model_id) : cancelTop(model_id)).then(res => {
if (res.data) {
item.sticky_on_top = stickyOnTop;
}
});
}
/**
* 删除数据表
* @param item 操作对象
*/
public handleDeleteModel(item) {
const { model_id } = item;
const h = this.$createElement;
// const vdom = h('div', {}, [h('p', { class: 'mb10 mt10' },
// '数据模型:' + `${item.model_name} (${item.model_alias})`), h('p', {}, '删除数据模型及所属指标统计口径和指标')]);
this.$bkInfo({
theme: 'primary',
title: this.$t('确认删除数据模型?'),
subTitle: this.$t('删除当前数据模型(附带删除所属的指标统计口径和指标),可能会影响其他模型草稿的使用'),
confirmFn: () => {
deleteModel(model_id).then(res => {
if (res.validateResult()) {
this.$bkMessage({
message: this.$t('删除成功'),
theme: 'success',
});
this.getModelInfoByProjectId();
const findItem = (this.DataModelTabManage.tabManage.items || [])
.find(tab => tab.modelId === item.model_id);
if (findItem) {
this.DataModelTabManage.removeItem(findItem);
const activeItem = this.DataModelTabManage.activeItemByIndex(0);
if (activeItem) {
// this.appendRouter({ modelId: activeItem.modelId },
// { project_id: activeItem.projectId })
this.changeRouterWithParams(
activeItem.routeName || 'dataModelView',
{ project_id: activeItem.projectId },
{ modelId: activeItem.modelId }
);
this.updateStorageModelId(activeItem.id);
this.updateStorageProjectId(activeItem.projectId);
this.handleActiveTabChanged(activeItem);
} else {
// this.appendRouter({ modelId: undefined }, {}, true)
this.changeRouterWithParams('dataModelView',
{ project_id: undefined }, { modelId: undefined });
}
}
}
});
},
});
}
/** 项目模式下面获取模型列表 */
public getModelInfoByProjectId() {
if (this.pProjectId) {
this.isPDatasourceLoad = true;
getModelList({ project_id: this.pProjectId })
.then(res => {
res.setData(this, 'pDataSource');
// 处理通过直接点链接进入数据模型的情况
if (this.isInitActiveItem && this.modelId) {
const model = this.pDataSource.find(item => item.model_id === Number(this.modelId));
if (!model) {
if (
this.DataModelTabManage.insertItem(
new TabItem({
id: 0,
name: 'New Model',
displayName: this.$t('新建模型'),
type: this.activeTypeName,
isNew: true,
projectId: this.pProjectId,
modelType: this.activeLeftTab.name,
modelId: 0,
icon: this.activeLeftTab.icon,
lastStep: 0,
}),
true
)
) {
this.changeRouterWithParams('dataModelEdit',
{ project_id: this.pProjectId }, { modelId: 0 });
// this.appendRouter({ modelId: 0 }, { project_id: this.pProjectId })
}
} else {
this.activeModelType = model.model_type;
this.clickList(model);
this.updateStorageModelType(model.model_type);
}
}
})
['finally'](() => {
this.isPDatasourceLoad = false;
});
}
}
/** 数据集市获取模型列表 */
public getModelInfoByMart() {
this.isSDatasourceLoad = true;
getModelList({})
.then(res => {
res.setData(this, 'sDataSource');
})
['finally'](() => {
this.isSDatasourceLoad = false;
});
}
public getProjectList() {
getMineProjectList().then(res => {
res.setData(this, 'projectList');
const existProject = this.projectList.find(item => item.project_id === Number(this.pProjectId));
this.pProjectId && !existProject && this.projectApply && this.projectApply.openDialog();
});
}
public handleProjectChanged(id: number) {
this.DataModelTabManage.clearTabItems();
// this.appendRouter({ modelId: undefined }, { project_id: undefined })
this.changeRouterWithParams('dataModelView', { project_id: undefined }, { modelId: undefined });
this.updateStorageProjectId(id);
}
/**
* 当前选中类型改变事件 项目|数据集市
* 因为数据集市跳转新开Tab,此处不做缓存
* 目前只处理项目类型下面的模型类型
* activeType缓存暂时只能为 project
* @param typeName
*/
public handleActiveTypeChanged(typeName: string) {
this.searchValue = '';
// this.updateStorageActiveType(typeName)
}
public handleModelTypeChanged(typeName: string) {
this.updateStorageModelType(typeName);
}
/**
* 右侧已经打开的标签点击激活事件
* 目前只有项目才能在右侧新开标签
* 此处逻辑为数据集市也开新的标签时的处理逻辑
* 目前状态下无影响
* @param activeTab
*/
public handleActiveTabChanged(activeTab: IDataModelManage.IModeRightTabItem) {
this.activeTypeName = activeTab.type;
this.activeModelType = activeTab.modelType;
}
public handleUpdateModel(item: any) {
const index = this.modelInfoList.findIndex(ite => ite.model_id === item.model_id);
if (index >= 0) {
const oldItem = this.modelInfoList[index];
Object.assign(oldItem, item);
this.modelInfoList.splice(index, 1, oldItem);
} else {
this.modelInfoList.splice(0, 0, item);
}
}
public handleToggleLeftMenu() {
this.isShowLeftMenu = !this.isShowLeftMenu;
}
public created() {
this.getProjectList();
this.getModelInfoByMart();
this.restoreLocalStorage();
const projectId = this.projectId || this.storageData.pProjectId;
// 通过分享链接进入
if (this.projectId && Number(this.projectId) !== Number(this.storageData.pProjectId)) {
this.DataModelTabManage.clearTabItems();
this.updateStorageProjectId(projectId);
}
this.activeTypeName = this.storageData.activeType;
const activeItem = this.DataModelTabManage.getActiveItem()[0];
// 如果激活项和router modelId不同,以router modelId为准
this.isInitActiveItem = !activeItem || (activeItem && activeItem.modelId !== this.modelId);
if (!!activeItem) {
this.activeModelType = activeItem.modelType;
if (!this.modelId) {
this.modelId = activeItem.modelId;
}
}
this.pProjectId = Number(projectId) || projectId;
}
} | the_stack |
import compareAsc from 'date-fns/compareAsc'
import fetch, { Response } from 'node-fetch'
import * as kennitala from 'kennitala'
import format from 'date-fns/format'
import { Cache as CacheManager } from 'cache-manager'
import { Injectable, Inject } from '@nestjs/common'
import type { Logger } from '@island.is/logging'
import { logger, LOGGER_PROVIDER } from '@island.is/logging'
import { User } from '@island.is/auth-nest-tools'
import { GenericDrivingLicenseResponse } from './genericDrivingLicense.type'
import { parseDrivingLicensePayload } from './drivingLicenseMappers'
import {
CONFIG_PROVIDER,
GenericLicenseClient,
GenericLicenseUserdataExternal,
GenericUserLicensePkPassStatus,
GenericUserLicenseStatus,
PkPassVerification,
PkPassVerificationError,
} from '../../licenceService.type'
import { Config } from '../../licenseService.module'
import { PkPassClient } from './pkpass.client'
import { PkPassPayload } from './pkpass.type'
/** Category to attach each log message to */
const LOG_CATEGORY = 'drivinglicense-service'
/** Defined cut-off point for driving license images */
const IMAGE_CUTOFF_DATE = '1997-08-15'
// PkPass service wants dates in DD-MM-YYYY format
const dateToPkpassDate = (date: string): string => {
if (!date) {
return ''
}
try {
return format(new Date(date), 'dd-MM-yyyy')
} catch (e) {
return ''
}
}
@Injectable()
export class GenericDrivingLicenseApi
implements GenericLicenseClient<GenericDrivingLicenseResponse> {
private readonly xroadApiUrl: string
private readonly xroadClientId: string
private readonly xroadPath: string
private readonly xroadSecret: string
private pkpassClient: PkPassClient
constructor(
@Inject(CONFIG_PROVIDER) private config: Config,
@Inject(LOGGER_PROVIDER) private logger: Logger,
private cacheManager?: CacheManager | null,
) {
// TODO inject the actual RLS x-road client
this.xroadApiUrl = config.xroad.baseUrl
this.xroadClientId = config.xroad.clientId
this.xroadPath = config.xroad.path
this.xroadSecret = config.xroad.secret
this.logger = logger
this.cacheManager = cacheManager
// TODO this should be injected by nest
this.pkpassClient = new PkPassClient(config, logger, cacheManager)
}
private headers() {
return {
'X-Road-Client': this.xroadClientId,
SECRET: this.xroadSecret,
Accept: 'application/json',
}
}
private async requestApi(url: string): Promise<unknown | null> {
let res: Response | null = null
try {
res = await fetch(`${this.xroadApiUrl}/${url}`, {
headers: this.headers(),
})
if (!res.ok) {
throw new Error(
`Expected 200 status for Drivers license query, got ${res.status}`,
)
}
} catch (e) {
this.logger.error('Unable to query for drivers licence', {
exception: e,
url,
category: LOG_CATEGORY,
})
return null
}
let json: unknown
try {
json = await res.json()
} catch (e) {
this.logger.error('Unable to parse JSON for drivers licence', {
exception: e,
url,
category: LOG_CATEGORY,
})
return null
}
return json
}
private async requestFromXroadApi(
nationalId: string,
): Promise<GenericDrivingLicenseResponse[] | null> {
const response = await this.requestApi(
`${this.xroadPath}/api/Okuskirteini/${nationalId}`,
)
if (!response) {
logger.warn('Falsy result from drivers license response', {
category: LOG_CATEGORY,
})
return null
}
if (!Array.isArray(response)) {
logger.warn('Expected drivers license response to be an array', {
category: LOG_CATEGORY,
})
return null
}
const licenses = response as GenericDrivingLicenseResponse[]
// If we get more than one license, sort in descending order so we can pick the first one as the
// newest license later on
// TODO(osk): This is a bug, fixed in v2 of the service (see https://www.notion.so/R-kisl-greglustj-ri-60f22ab2789e4e0296f5fe6e25fa19cf)
licenses.sort(
(
a?: GenericDrivingLicenseResponse,
b?: GenericDrivingLicenseResponse,
) => {
const timeA = a?.utgafuDagsetning
? new Date(a.utgafuDagsetning).getTime()
: 0
const timeB = b?.utgafuDagsetning
? new Date(b.utgafuDagsetning).getTime()
: 0
if (isNaN(timeA) || isNaN(timeB)) {
return 0
}
return timeB - timeA
},
)
return licenses
}
private drivingLicenseToPkpassPayload(
license: GenericDrivingLicenseResponse,
): PkPassPayload {
return {
nafn: license.nafn,
gildirTil: dateToPkpassDate(license.gildirTil ?? ''),
faedingardagur: dateToPkpassDate(
kennitala.info(license.kennitala ?? '').birthday.toISOString(),
),
faedingarstadur: license.faedingarStadurHeiti,
utgafuDagsetning: dateToPkpassDate(license.utgafuDagsetning ?? ''),
nafnUtgafustadur: license.nafnUtgafustadur,
kennitala: license.kennitala,
id: license.id,
rettindi: license.rettindi?.map((rettindi) => {
return {
id: rettindi.id,
nr: rettindi.nr,
utgafuDags: dateToPkpassDate(rettindi.utgafuDags ?? ''),
gildirTil: dateToPkpassDate(rettindi.gildirTil ?? ''),
aths: rettindi.aths,
}
}),
mynd: {
id: license.mynd?.id,
kennitala: license.mynd?.kennitala,
skrad: dateToPkpassDate(license.mynd?.skrad ?? ''),
mynd: license.mynd?.mynd,
gaedi: license.mynd?.gaedi,
forrit: license.mynd?.forrit,
tegund: license.mynd?.tegund,
},
}
}
static licenseIsValidForPkpass(
license: GenericDrivingLicenseResponse,
): GenericUserLicensePkPassStatus {
if (!license || license.mynd === undefined) {
return GenericUserLicensePkPassStatus.Unknown
}
if (!license.mynd?.skrad || !license.mynd?.mynd) {
return GenericUserLicensePkPassStatus.NotAvailable
}
const cutoffDate = new Date(IMAGE_CUTOFF_DATE)
const imageDate = new Date(license.mynd?.skrad)
const comparison = compareAsc(imageDate, cutoffDate)
if (isNaN(comparison) || comparison < 0) {
return GenericUserLicensePkPassStatus.NotAvailable
}
return GenericUserLicensePkPassStatus.Available
}
async getPkPassUrlByNationalId(nationalId: string): Promise<string | null> {
const licenses = await this.requestFromXroadApi(nationalId)
if (!licenses) {
this.logger.warn('Missing licenses, null from x-road', {
category: LOG_CATEGORY,
})
return null
}
const license = licenses[0]
if (!license) {
this.logger.warn(
'Missing license, unable to generate pkpass for drivers license',
{ category: LOG_CATEGORY },
)
return null
}
if (!GenericDrivingLicenseApi.licenseIsValidForPkpass(license)) {
this.logger.info('License is not valid for pkpass generation', {
category: LOG_CATEGORY,
})
}
const payload = this.drivingLicenseToPkpassPayload(license)
return this.pkpassClient.getPkPassUrl(payload)
}
async getPkPassUrl(nationalId: User['nationalId']): Promise<string | null> {
return this.getPkPassUrlByNationalId(nationalId)
}
/**
* Fetch drivers license data from RLS through x-road.
*
* @param nationalId NationalId to fetch drivers licence for.
* @return {Promise<GenericLicenseUserdataExternal | null>} Latest driving license or null if an error occured.
*/
async getLicense(
nationalId: User['nationalId'],
): Promise<GenericLicenseUserdataExternal | null> {
const licenses = await this.requestFromXroadApi(nationalId)
if (!licenses) {
this.logger.warn('Missing licenses, null from x-road', {
category: LOG_CATEGORY,
})
return null
}
const payload = parseDrivingLicensePayload(licenses)
let pkpassStatus: GenericUserLicensePkPassStatus =
GenericUserLicensePkPassStatus.Unknown
if (payload) {
pkpassStatus = GenericDrivingLicenseApi.licenseIsValidForPkpass(
licenses[0],
)
}
return {
payload,
status: GenericUserLicenseStatus.HasLicense,
pkpassStatus,
}
}
async getLicenseDetail(
nationalId: User['nationalId'],
): Promise<GenericLicenseUserdataExternal | null> {
return this.getLicense(nationalId)
}
async verifyPkPass(data: string): Promise<PkPassVerification | null> {
const result = await this.pkpassClient.verifyPkpassByPdf417(data)
if (!result) {
this.logger.warn('Missing pkpass verify from client', {
category: LOG_CATEGORY,
})
return null
}
let error: PkPassVerificationError | undefined
if (result.error) {
let data = ''
try {
data = JSON.stringify(result.error.serviceError?.data)
} catch {
// noop
}
// Is there a status code from the service?
const serviceErrorStatus = result.error.serviceError?.status
// Use status code, or http status code from serivce, or "0" for unknown
const status = serviceErrorStatus ?? (result.error.statusCode || 0)
error = {
status: status.toString(),
message: result.error.serviceError?.message || 'Unknown error',
data,
}
return {
valid: false,
data: undefined,
error,
}
}
let response:
| Record<string, string | null | GenericDrivingLicenseResponse['mynd']>
| undefined = undefined
if (result.nationalId) {
const nationalId = result.nationalId.replace('-', '')
const licenses = await this.requestFromXroadApi(nationalId)
if (!licenses) {
this.logger.warn(
'Missing licenses from x-road, unable to return license info for pkpass verify',
{ category: LOG_CATEGORY },
)
error = {
status: '0',
message: 'missing licenses',
}
}
const licenseNationalId = licenses?.[0]?.kennitala ?? null
const name = licenses?.[0]?.nafn ?? null
const photo = licenses?.[0]?.mynd ?? null
const rawData = licenses?.[0] ? JSON.stringify(licenses?.[0]) : undefined
response = {
nationalId: licenseNationalId,
name,
photo,
rawData,
}
}
return {
valid: result.valid,
data: response ? JSON.stringify(response) : undefined,
error,
}
}
} | the_stack |
import React, { PropsWithChildren, useEffect, useRef } from 'react';
import * as ts from 'typescript';
import { useLocalStore, useObserver } from 'mobx-react';
import MonacoEditor from 'react-monaco-editor';
import * as dedent from 'dedent';
import { useReaction } from 'hooks/use-reaction';
import { useEventListener } from 'hooks/use-event-listener';
import { safeLsSet, safeLsGet } from 'models/ls-sync';
import { Portal } from 'react-portal';
import { Transition } from 'react-transition-group';
import { theme } from 'constants/theme.constant';
import ContentEditable from 'react-contenteditable';
import { pull, camelCase, debounce } from 'lodash';
import traverse from 'traverse';
import styled from '@emotion/styled';
import { Switch, Tabs, Tab, Tooltip, IconButton, TextField, MenuItem } from '@material-ui/core';
import { humanCase } from 'functions/human-case.function';
import { appState } from 'constants/app-state.constant';
import { ShoppingCart, Code, BubbleChart } from '@material-ui/icons';
// TODO: add default lib to the language services below too
monaco.languages.typescript.typescriptDefaults.addExtraLib(`
declare var state = any;
declare var context = any;
`);
// TODO: get dynamically from typeChecker or languageService
const stateProperties = ['active', 'text'];
export const FILE_NAME = 'code.tsx';
export function getProgramForText(text: string) {
const dummyFilePath = FILE_NAME;
const textAst = ts.createSourceFile(dummyFilePath, text, ts.ScriptTarget.Latest);
const options: ts.CompilerOptions = {};
const host: ts.CompilerHost = {
fileExists: filePath => filePath === dummyFilePath,
directoryExists: dirPath => dirPath === '/',
getCurrentDirectory: () => '/',
getDirectories: () => [],
getCanonicalFileName: fileName => fileName,
getNewLine: () => '\n',
getDefaultLibFileName: () => '',
getSourceFile: filePath => (filePath === dummyFilePath ? textAst : undefined),
readFile: filePath => (filePath === dummyFilePath ? text : undefined),
useCaseSensitiveFileNames: () => true,
writeFile: () => {},
};
const languageHost: ts.LanguageServiceHost = {
getScriptFileNames: () => [FILE_NAME],
// What is this?
getScriptVersion: fileName => '3',
getCurrentDirectory: () => '/',
getCompilationSettings: () => options,
getDefaultLibFileName: options => ts.getDefaultLibFilePath(options),
fileExists: filePath => filePath === dummyFilePath,
readFile: filePath => (filePath === dummyFilePath ? text : undefined),
getScriptSnapshot: filePath =>
filePath === dummyFilePath ? ts.ScriptSnapshot.fromString(text) : undefined,
};
const program = ts.createProgram({
host,
options,
rootNames: [dummyFilePath],
});
// TODO: reaction for this on code change
const checker = program.getTypeChecker();
const languageService = ts.createLanguageService(languageHost);
return {
checker,
languageService,
program,
};
}
type LanguageExtension = (node: ts.Node, options: Options) => void | JSX.Element;
export function SetStateExtension(props: AstEditorProps<ts.BinaryExpression>) {
const { node, options } = props;
const propertyName = (node.left as ts.PropertyAccessExpression).name as ts.Identifier;
const value = node.right;
const fadedBlue = 'rgb(112, 141, 154)';
const state = useLocalStore(() => ({
// Get all state properties via typescripts type checker
getPropertyNames() {
return options.programState.program
.getTypeChecker()
.getTypeAtLocation((node.left as ts.PropertyAccessExpression).expression)
.getApparentProperties()
.map(item => item.name);
},
getCompletionItems() {
return options.programState.languageService.getCompletionsAtPosition(
FILE_NAME,
(node.left as ts.PropertyAccessExpression).name.getStart(),
{}
);
},
}));
return useObserver(() => {
return (
<Row>
<Tooltip
title={
// TODO: change the tooltips to be interactive. Right now using the built in component links aren't
// actually clickable. Change to be more like VS Code's tooltips that can be moused onto and clicked
<>
Set a state property.{' '}
<a css={{ color: theme.colors.primaryLight }}>Learn about state</a>
</>
}
>
<span>
<Bubble color={fadedBlue} open="right" options={options}>
<BubbleChart css={{ fontSize: 16, marginRight: 7, marginLeft: 2, opacity: 0.6 }} />
Set state
</Bubble>
</span>
</Tooltip>
<Tooltip
title={
<>
Choose or create a name for your state property.{' '}
<a css={{ color: theme.colors.primaryLight }}>Learn more</a>
</>
}
>
<span>
<Identifier node={propertyName} options={options} />
</span>
</Tooltip>
<Bubble color={fadedBlue} open="both" options={options}>
To
</Bubble>
<Node node={value} options={options} />
</Row>
);
});
}
const SPACER_TOKEN = '__SPACER__';
const createSpacer = () => ts.createIdentifier(SPACER_TOKEN);
const normalizeExpression = (expression: string) => expression.replace(/\s+/g, '');
export function LiquidBubble(props: AstEditorProps<ts.CallExpression>) {
const { node, options } = props;
const state = useLocalStore(() => ({
hovering: false,
showCode: false,
}));
const liquidEditorRef = useRef<HTMLElement | null>(null);
useEffect(() => {
if (state.showCode && liquidEditorRef.current) {
setTimeout(() => {
liquidEditorRef.current?.focus();
}, 500);
}
}, [state.showCode]);
return useObserver(() => {
const liquidExpression = node.arguments[0] as ts.StringLiteral;
const simpleExpression = humanCase(liquidExpression.text.split('|')[0]);
return (
<span
onMouseEnter={() => (state.hovering = true)}
onMouseLeave={() => (state.hovering = false)}
>
<Bubble color="rgb(158,189,89)" htmlMode={false} options={options}>
<ShoppingCart css={{ fontSize: 14, marginLeft: 2, marginRight: 7, opacity: 0.7 }} />
<Row css={{ marginRight: 5 }}>
{simpleExpression}
<Row
css={{
maxWidth: state.showCode ? 500 : 0,
overflow: 'hidden',
transition: theme.transitions.for('max-width'),
}}
>
<ContentEditable
innerRef={liquidEditorRef}
tagName="pre"
css={{
outline: 'none',
cursor: 'text',
height: bubbleHeight,
marginLeft: 10,
lineHeight: bubbleHeight - 1 + 'px',
padding: '0 10px',
borderLeft: `1px solid rgba(0, 0, 0, 0.1)`,
borderRight: `1px solid rgba(0, 0, 0, 0.1)`,
backgroundColor: 'rgba(0, 0, 0, 0.2)',
}}
html={liquidExpression.text}
onChange={e => {
(node.arguments as any)[0] = ts.createStringLiteral(stripHtml(e.target.value));
options.programState.updateCode();
}}
/>
</Row>
</Row>
<div
css={{
width: state.hovering || state.showCode ? 20 : 0,
opacity: state.hovering || state.showCode ? 1 : 0,
transition: theme.transitions.for('width', 'opacity'),
}}
>
<Tooltip
title={
<>
Toggle liquid code. <a css={{ color: theme.colors.primary }}>Learn more</a>{' '}
</>
}
>
<IconButton
onMouseDown={e => {
e.stopPropagation();
state.showCode = !state.showCode;
}}
css={{ padding: 2 }}
>
<Code css={{ fontSize: 16 }} />
</IconButton>
</Tooltip>
</div>
</Bubble>
</span>
);
});
}
export function EventListener(props: AstEditorProps<ts.CallExpression>) {
const state = useLocalStore(() => ({}));
const { options, node } = props;
const eventNode = node.arguments[0] as ts.StringLiteral;
const callback = node.arguments[1] as ts.ArrowFunction;
return useObserver(() => {
return (
<Stack>
<Row>
<Bubble color="rgb(121, 165, 245)" options={options}>
On page
<TextField
SelectProps={{
style: {
paddingTop: 0,
paddingBottom: 0,
paddingLeft: 5,
},
}}
InputProps={{
disableUnderline: true,
style: {
fontSize: 'inherit',
},
}}
css={{ marginLeft: 5, fontSize: 'inherit' }}
select
value={eventNode.text}
onChange={e => {
(node.arguments as any)[0] = ts.createStringLiteral(stripHtml(e.target.value));
options.programState.updateCode();
}}
>
{['scroll', 'click', 'mousedown', 'keypress'].map(item => (
<MenuItem value={item} key={item}>
{humanCase(item).toLowerCase()}
</MenuItem>
))}
</TextField>
</Bubble>
</Row>
{callback.body && <Node node={callback.body} options={options} />}
</Stack>
);
});
}
const languageExtensions: LanguageExtension[] = [
// Liquid bubbles
(node, options) => {
if (
ts.isCallExpression(node) &&
normalizeExpression(node.getText().split('(')[0]) === 'context.shopify.liquid.get' &&
node.arguments.length &&
ts.isStringLiteral(node.arguments[0])
) {
return <LiquidBubble node={node} options={options} />;
}
},
// Liquid bubbles
(node, options) => {
if (
ts.isPropertyAccessExpression(node) &&
normalizeExpression(node.getText()) === 'document.body.scrollTop'
) {
return (
<Bubble color={theme.colors.primary} options={options}>
Page scroll position
</Bubble>
);
}
},
// Liquid bubbles
(node, options) => {
if (
ts.isCallExpression(node) &&
normalizeExpression(node.getText().split('(')[0]) === 'document.addEventListener'
) {
return <EventListener node={node} options={options} />;
}
},
// Render spacers
(node, options) => {
if (ts.isIdentifier(node) && node.text === SPACER_TOKEN) {
// TODO: make component and listen for mouseup and delete all spacers
return (
<div
className="spacer"
css={{
flexGrow: 1,
alignSelf: 'stretch',
minWidth: 50,
minHeight: 50,
borderRadius: 6,
backgroundColor: theme.colors.primaryWithOpacity(0.5),
boreder: `1px solid ${theme.colors.primaryWithOpacity(0.9)}`,
}}
/>
);
}
},
// `state.foo = 'bar' to "set state"
(node, options) => {
if (ts.isBinaryExpression(node) && node.operatorToken.getText() === '=') {
if (ts.isPropertyAccessExpression(node.left)) {
if (
ts.isIdentifier(node.left.expression) &&
node.left.expression.text === 'state' &&
ts.isIdentifier(node.left.name)
) {
return <SetStateExtension node={node} options={options} />;
}
}
}
},
];
const replace = <T extends any>(arr: T[], newArr: T[]) => {
arr.length = 0;
arr.push(...newArr);
};
const Row = styled.div({ display: 'flex', alignItems: 'center', flexWrap: 'wrap' });
const Stack = styled.div({ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' });
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
const findKey = (obj: { [key: string]: any }, value: object) => {
for (const key in obj) {
if (obj[key] === value) {
return key;
}
}
};
const replaceNode = (oldNode: ts.Node, newNode: ts.Node) => {
const key = findKey(oldNode.parent, oldNode);
if (key) {
(oldNode.parent as any)[key] = newNode;
} else {
console.error('Could not find key to replace node', { oldNode, newNode });
}
};
type VisualProgrammingProps = {
className?: string;
};
export type ProgramState = {
draggingNode: ts.Node | null;
hoveringNode: ts.Node | null;
ast: ts.SourceFile;
selection: ts.Node[];
updateCode: () => void;
hoveringCodeEditor: boolean;
program: ts.Program;
languageService: ts.LanguageService;
};
type Options = {
programState: ProgramState;
};
interface AstEditorProps<NodeType = ts.Node> {
options: Options;
node: NodeType;
}
const stripHtml = (html: string) => {
const div = document.createElement('div');
div.innerHTML = html;
return div.innerText;
};
const localStorageCodeKey = 'builder.experiments.visualProgramming.code';
export function VariableStatement(props: AstEditorProps<ts.VariableStatement>) {
const { node, options } = props;
return useObserver(() => {
return (
<>
{node.declarationList.declarations.map((item, index) => (
<Node node={item} key={index} options={options} />
))}
</>
);
});
}
export function CallExpression(props: AstEditorProps<ts.CallExpression>) {
const { node, options } = props;
return useObserver(() => {
return (
<Row>
<Bubble color="rgb(144, 87, 218)" options={options} open="right">
Do action
</Bubble>
{node.expression && <Node node={node.expression} options={options} />}
{node.arguments &&
node.arguments.map((arg, index) => {
const isFirst = index === 0;
return (
<React.Fragment key={index}>
<Bubble humanCase={false} options={options} open="both" css={{ zIndex: 0 }}>
{isFirst ? 'With' : ','}
</Bubble>
<Node node={arg} options={options} />
</React.Fragment>
);
})}
</Row>
);
});
}
export function Identifier(
props: AstEditorProps<ts.Identifier> & { open?: 'left' | 'right' | 'both'; color?: string }
) {
const { node, options } = props;
return useObserver(() => {
const isActive = Boolean(
options.programState.selection.find(item => ts.isIdentifier(item) && item.text === node.text)
);
return (
<Bubble
options={options}
onFocus={() => replace(options.programState.selection, [node])}
onBlur={() => {
if (options.programState.selection.includes(node)) {
pull(options.programState.selection, node);
}
}}
open={props.open}
active={isActive}
color={props.color || theme.colors.primary}
onChange={text => {
const file = node.getSourceFile();
const newNode = ts.createIdentifier(text);
// Update all references to this identifier
// TODO: use ts.transform or ts.visitEachChild or another
// built-in API after figuring out which one is actually right for this
traverse(file).forEach((child: any) => {
if (
child &&
ts.isIdentifier(child) &&
!(
ts.isPropertyAssignment(child.parent) || ts.isPropertyAccessExpression(child.parent)
) &&
child.text === node.text
) {
// Identifiers seem to be immutable in TS AST
replaceNode(child, newNode);
}
});
options.programState.updateCode();
}}
>
{node.text}
</Bubble>
);
});
}
const bubbleHeight = 30;
export function Bubble(
props: PropsWithChildren<{
options: Options;
color?: string;
active?: boolean;
className?: string;
onFocus?: (event: React.FocusEvent<HTMLElement>) => void;
onBlur?: (event: React.FocusEvent<HTMLElement>) => void;
onChange?: (text: string) => void;
open?: 'right' | 'left' | 'both' | 'none';
humanCase?: boolean;
htmlMode?: boolean;
}>
) {
const size = bubbleHeight;
const spacerStyles: Partial<React.CSSProperties> = {
backgroundColor: '#222',
width: size + 3,
height: size + 4,
borderRadius: 100,
};
const openLeft = props.open === 'left' || props.open === 'both';
const openRight = props.open === 'right' || props.open === 'both';
const gap = 3;
const htmlMode = props.htmlMode === true || props.onChange;
return useObserver(() => (
<div
css={{
opacity: props.active ? 1 : 0.8,
borderRadius: 50,
height: size,
paddingLeft: 10 + (openLeft ? size / 2 : 0),
paddingRight: 10 + (openRight ? size / 2 : 0),
display: 'flex',
alignItems: 'center',
cursor: 'pointer',
position: 'relative',
zIndex: openLeft ? 1 : 2,
backgroundColor: props.color || '#555',
marginTop: 5,
marginBottom: 5,
marginLeft: gap,
marginRight: gap,
...(openRight && {
marginRight: -size + gap,
}),
...(openLeft && {
marginLeft: -size + gap,
}),
}}
className={props.className}
>
{openLeft && (
<div
css={{
...spacerStyles,
marginRight: 5,
marginLeft: -size,
}}
/>
)}
{!htmlMode ? (
props.children
) : (
<ContentEditable
css={{ outline: 'none', cursor: props.onChange ? 'text' : 'pointer' }}
onFocus={props.onFocus}
onBlur={props.onBlur}
disabled={!props.onChange}
html={
props.humanCase === false
? (props.children as string)
: humanCase(props.children as string)
}
onChange={e => {
props.onChange?.(camelCase(stripHtml(e.target.value)));
props.options.programState.updateCode();
}}
/>
)}
{openRight && (
<div
css={{
...spacerStyles,
marginLeft: 5,
marginRight: -size,
}}
/>
)}
</div>
));
}
export function VariableDeclaration(props: AstEditorProps<ts.VariableDeclaration>) {
const { node, options } = props;
return useObserver(() => {
return (
<Row>
<Bubble options={options} open="right">
Set
</Bubble>
<Node node={node.name} options={options} />
<Bubble options={options} open="both">
To
</Bubble>
{node.initializer && <Node node={node.initializer} options={options} />}
</Row>
);
});
}
export function Block(props: AstEditorProps<ts.Block>) {
const { node, options } = props;
const tabSpace = 40;
return useObserver(() => {
return (
<Stack
css={{
paddingLeft: tabSpace,
position: 'relative',
width: '100%',
paddingBottom: 10,
}}
>
<div
css={{
backgroundColor: '#333',
top: 0,
bottom: 10,
width: 2,
borderRadius: 4,
position: 'absolute',
left: tabSpace / 1.5,
}}
/>
{node.statements.map((item, index) => (
<Node key={index} node={item} options={options} />
))}
</Stack>
);
});
}
export function ExpressionStatement(props: AstEditorProps<ts.ExpressionStatement>) {
const { node, options } = props;
return useObserver(() => {
return <>{node.expression && <Node node={node.expression} options={options} />}</>;
});
}
export function ReturnStatement(props: AstEditorProps<ts.ReturnStatement>) {
const { node, options } = props;
return useObserver(() => {
return (
<Row>
<Bubble color="rgb(134, 107, 218)" options={options} open="right">
Respond
</Bubble>
{node.expression && <Node node={node.expression} options={options} />}
</Row>
);
});
}
export function FunctionDeclaration(props: AstEditorProps<ts.FunctionDeclaration>) {
const { node, options } = props;
const color = 'rgb(226, 158, 56)';
return useObserver(() => {
return (
<Stack>
<Row>
<Bubble color={color} options={options} open="right">
Create action named
</Bubble>
{node.name && <Node node={node.name} options={options} />}
<Bubble humanCase={false} color={color} options={options} open="left">
that does
</Bubble>
</Row>
{node.body && <Node node={node.body} options={options} />}
</Stack>
);
});
}
export function ArrowFunction(props: AstEditorProps<ts.ArrowFunction>) {
const { node, options } = props;
const color = 'rgb(226, 158, 56)';
return useObserver(() => {
return (
<span>
<Row>
<Bubble color={color} options={options}>
Do
</Bubble>
</Row>
{node.body && <Node node={node.body} options={options} />}
</span>
);
});
}
export function IfStatement(props: AstEditorProps<ts.IfStatement>) {
const { node, options } = props;
const thenHasIf = node.elseStatement && ts.isIfStatement(node.elseStatement);
return useObserver(() => {
return (
<>
<Row>
<Bubble options={options} open="right">
If
</Bubble>
<Node node={node.expression} options={options} />
</Row>
<Node node={node.thenStatement} options={options} />
{thenHasIf ? (
<Row>
<Bubble options={options} open="right">
Otherwise
</Bubble>
<Node node={node.elseStatement!} options={options} />
</Row>
) : (
node.elseStatement && (
<>
<Bubble options={options}>Otherwise</Bubble>
<Node node={node.elseStatement} options={options} />
</>
)
)}
</>
);
});
}
export function SourceFile(props: AstEditorProps<ts.SourceFile>) {
const { node, options } = props;
return useObserver(() => {
return (
<Stack>
{node.statements.map((item, index) => (
<Node node={item} key={index} options={options} />
))}
</Stack>
);
});
}
export function BinaryExpression(props: AstEditorProps<ts.BinaryExpression>) {
const { node, options } = props;
const tokenText = node.operatorToken.getText();
const isEquals = tokenText === '=';
const textMap: { [key: string]: string | undefined } = {
'===': 'is',
'==': 'is',
'&&': 'and',
'||': 'or',
'!==': 'is not',
'!=': 'is not',
};
const useText = textMap[tokenText] || tokenText;
return useObserver(() => {
return (
<Row>
{isEquals && (
<Bubble options={options} open="right">
Set
</Bubble>
)}
<Node node={node.left} options={options} />
<Bubble css={{ zIndex: 0 }} options={options} open="both">
{useText}
</Bubble>
<Node node={node.right} options={options} />
</Row>
);
});
}
const booleanBubbleStyles: Partial<React.CSSProperties> = {
height: bubbleHeight,
display: 'flex',
alignItems: 'center',
borderRadius: bubbleHeight,
backgroundColor: '#555',
position: 'relative',
marginLeft: 3,
zIndex: 2,
};
export function TrueKeyword(props: AstEditorProps<ts.Node>) {
const { node, options } = props;
return useObserver(() => {
return (
<div css={booleanBubbleStyles}>
<Tooltip title="True">
<Switch
color="primary"
checked
onChange={() => {
replaceNode(node, ts.createFalse());
options.programState.updateCode();
}}
/>
</Tooltip>
</div>
);
});
}
export function FalseKeyword(props: AstEditorProps<ts.Node>) {
const { node, options } = props;
return useObserver(() => {
return (
<div css={booleanBubbleStyles}>
<Tooltip title="False">
<Switch
color="primary"
onChange={() => {
replaceNode(node, ts.createTrue());
options.programState.updateCode();
}}
/>
</Tooltip>
</div>
);
});
}
/**
* This is things like `!foo` or `!state.foo` or `+foo`
*/
export function PrefixUnaryExpression(props: AstEditorProps<ts.PrefixUnaryExpression>) {
const { node, options } = props;
return useObserver(() => {
return (
<Row>
{/*
TODO: handle other operators than "!", e.g. `-foo` of `-10`
Rarer ones to add eventually are also things like `+foo` and `~foo` etc
*/}
<Bubble open="right" options={options}>
Not
</Bubble>
<Node options={options} node={node.operand} />
</Row>
);
});
}
export function PropertyAccessExpression(props: AstEditorProps<ts.PropertyAccessExpression>) {
const { node, options } = props;
return useObserver(() => {
return (
<Row>
<Node options={options} node={node.expression} />
<Identifier
color={theme.colors.primaryLight}
options={options}
node={node.name as ts.Identifier}
open="left"
/>
</Row>
);
});
}
// TODO: if works for comments rename to NodeWrapper or something
export function Hoverable(props: PropsWithChildren<{ node: ts.Node; options: Options }>) {
const { options, node } = props;
const state = useLocalStore(() => ({
onMouseEnter() {
options.programState.hoveringNode = node;
if (options.programState.draggingNode) {
// TODO: find first AST element parent that is an array, make that the subject, splice in
// the spacer
}
},
onMouseLeave() {
if (options.programState.hoveringNode === node) {
options.programState.hoveringNode = null;
// TODO: remove all spacers from AST
}
},
}));
// TODO: turn back on when updated to handle below tasks
const renderComments = false as boolean;
const comments =
renderComments &&
ts.getLeadingCommentRanges(options.programState.ast.getFullText(), node.getFullStart());
return (
<>
{/*
TODO: special handling for jsdoc style
TODO: handle same comment matching multiple times
TODO: make editable
*/}
{renderComments &&
comments &&
comments.map((item, index) => (
<Stack
css={{ whiteSpace: 'pre', margin: 10, color: '#999' }}
className="comment"
key={index}
>
{options.programState.ast.getFullText().slice(item.pos, item.end)}
</Stack>
))}
<span
// TODO: improve this logic and get it back in
// onMouseDown={() => {
// if (!ts.isLiteralExpression(node)) {
// options.programState.draggingNode = node;
// }
// }}
onMouseEnter={state.onMouseEnter}
onMouseLeave={state.onMouseLeave}
>
{props.children}
</span>
</>
);
}
const hoverable = (
node: ts.Node,
options: Options,
children: JSX.Element | (() => JSX.Element)
) => (
<Hoverable node={node} options={options}>
{typeof children === 'function' ? children() : children}
</Hoverable>
);
export function Node(props: AstEditorProps<ts.Node>) {
const { node, options } = props;
return useObserver(() =>
hoverable(node, options, () => {
for (const extension of languageExtensions) {
const result = extension(node, options);
if (result) {
return result;
}
}
if (ts.isVariableStatement(node)) {
return <VariableStatement node={node} options={options} />;
}
if (ts.isVariableDeclaration(node)) {
return <VariableDeclaration node={node} options={options} />;
}
if (ts.isSourceFile(node)) {
return <SourceFile node={node} options={options} />;
}
if (ts.isIdentifier(node)) {
return <Identifier node={node} options={options} />;
}
if (ts.isPropertyAccessExpression(node)) {
return <PropertyAccessExpression node={node} options={options} />;
}
if (ts.isBinaryExpression(node)) {
return <BinaryExpression node={node} options={options} />;
}
if (ts.isFunctionDeclaration(node)) {
return <FunctionDeclaration node={node} options={options} />;
}
if (ts.isArrowFunction(node)) {
return <ArrowFunction node={node} options={options} />;
}
if (ts.isPrefixUnaryExpression(node)) {
return <PrefixUnaryExpression node={node} options={options} />;
}
if (ts.isBlock(node)) {
return <Block node={node} options={options} />;
}
if (ts.isExpressionStatement(node)) {
return <ExpressionStatement node={node} options={options} />;
}
if (ts.isCallExpression(node)) {
return <CallExpression node={node} options={options} />;
}
if (ts.isReturnStatement(node)) {
return <ReturnStatement node={node} options={options} />;
}
if (ts.isIfStatement(node)) {
return <IfStatement node={node} options={options} />;
}
// Can't seem to find a `ts.is*` method for these like the above
if (node.kind === 106) {
return <TrueKeyword node={node} options={options} />;
}
if (node.kind === 91) {
return <FalseKeyword node={node} options={options} />;
}
if (ts.isStringLiteral(node)) {
return (
<Bubble
options={options}
color="rgb(189, 63, 241)"
onChange={text => {
node.text = text;
}}
>
{node.text}
</Bubble>
);
}
if (ts.isNumericLiteral(node)) {
return (
<Bubble
options={options}
color="rgb(189, 63, 241)"
onChange={text => {
node.text = text;
}}
>
{node.text}
</Bubble>
);
}
return (
<Bubble options={options}>
<Tooltip title="Custom code - click to view">
<IconButton
css={{ padding: 5 }}
onClick={() =>
appState.globalState.openDialog(
<div
css={{
padding: 20,
backgroundColor: '#333',
minWidth: 300,
width: '90vw',
maxWidth: 1000,
height: '90vh',
maxHeight: 800,
position: 'relative',
}}
>
<MonacoEditor
language="typescript"
theme="vs-dark"
defaultValue={printer.printNode(
ts.EmitHint.Unspecified,
node,
node.getSourceFile()
)}
options={{
fontSize: 11,
renderLineHighlight: 'none',
minimap: { enabled: false },
scrollbar: {
horizontal: 'hidden',
vertical: 'hidden',
},
automaticLayout: true,
scrollBeyondLastLine: false,
}}
onChange={val => {
replaceNode(node, parseCode(val));
options.programState.updateCode();
}}
/>
{/* <ContentEditable
css={{ whiteSpace: 'pre', color: '#777', fontFamily: 'roboto' }}
html={printer.printNode(ts.EmitHint.Unspecified, node, node.getSourceFile())}
onChange={() => null}
/> */}
</div>
)
}
>
<Code
css={{
fontSize: 20,
color: 'black',
margin: '0 -10px',
}}
/>
</IconButton>
</Tooltip>
</Bubble>
);
})
);
}
export const createSourceFile = (code: string) => {
return ts.createSourceFile(FILE_NAME, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
};
// TODO: support multiple statements
const parseCode = (code: string) => {
const file = createSourceFile(code);
return file.statements[0];
};
const defaultTemplates = [
[`state.active = true`, 'state'],
[`state.text = 'Hello!'`, 'state'],
// TODO: make shopify dynamic, for instance if there is a product-like name in current scope
[`context.shopify.liquid.get('product.price | currency')`, 'shopify'],
[`context.shopify.liquid.get('product.name')`, 'shopify'],
[`context.shopify.liquid.get('product.description')`, 'shopify'],
[
dedent`document.addEventListener('scroll', event => {
if (document.body.scrollTop > 10) {
state.scrolledDown = true
}
})`,
'logic',
],
[
dedent`if (state.active) {
state.active = false;
}`,
'logic',
],
[
dedent`function toggleState() {
state.active = !state.active;
}`,
'logic',
],
].map(item => {
const [code, ...tags] = item;
return {
tags,
ast: parseCode(code),
};
});
function Draggable(props: { node: ts.Node; options: Options }) {
const { node, options } = props;
return useObserver(() => (
<Stack
onMouseDown={e => {
e.preventDefault();
options.programState.draggingNode = node;
}}
css={{
opacity: 0.85,
marginBottom: 5,
cursor: 'pointer',
'&:hover': {
opacity: 1,
},
'& *': {
pointerEvents: 'none',
},
}}
>
<Node options={options} node={node} />
</Stack>
));
}
function DraggingNodeOverlay(props: { options: Options }) {
const { options } = props;
return useObserver(() => {
const node = options.programState.draggingNode;
return (
node && (
<div
css={{
position: 'fixed',
top: appState.document.mouseY + 5,
left: appState.document.mouseX + 5,
zIndex: 10,
pointerEvents: 'none',
paddingRight: 5,
paddingLeft: 2,
backdropFilter: 'blur(20px)',
borderRadius: 50,
background: 'rgba(0, 0, 0, 0.1)',
}}
>
<Node node={node} options={options} />
</div>
)
);
});
}
function Toolbox(props: { options: Options; className?: string }) {
const { options } = props;
const templates = defaultTemplates;
const TAB_KEY = 'builder.experiments.visualCodingTab';
const state = useLocalStore(() => ({
tab: safeLsGet(TAB_KEY) ?? 0,
}));
useReaction(
() => state.tab,
tab => safeLsSet(TAB_KEY, tab)
);
const tabStyle: Partial<React.CSSProperties> = {
minWidth: 0,
minHeight: 0,
maxWidth: 'none',
height: 39,
color: '#888',
};
return useObserver(() => {
return (
<Stack
css={{
padding: 20,
}}
className={props.className}
>
<Tabs
css={{ marginBottom: 20, marginTop: -10 }}
value={state.tab}
onChange={(e, value) => (state.tab = value)}
indicatorColor="primary"
textColor="primary"
variant="fullWidth"
>
<Tab css={tabStyle} label="All" />
<Tab css={tabStyle} label="State" />
<Tab css={tabStyle} label="Shopify" />
<Tab css={tabStyle} label="Logic" />
<Tab css={tabStyle} label="Learn" />
</Tabs>
{templates
.filter(item => {
switch (state.tab) {
case 0:
return true;
case 1:
return item.tags.includes('state');
case 2:
return item.tags.includes('shopify');
case 3:
return item.tags.includes('logic');
case 4:
return false;
}
})
.map((item, index) => (
<Draggable key={index} options={options} node={item.ast} />
))}
</Stack>
);
});
}
export function VisualProgramming(props: VisualProgrammingProps) {
const state = useLocalStore(() => {
const initialCode = safeLsGet(localStorageCodeKey) || '';
return {
programState: {
hoveringCodeEditor: false,
draggingNode: null,
program: null as any,
hoveringNode: null,
updateCode() {
state.updateCode();
},
get ast(): ts.SourceFile {
return state.ast;
},
get selection(): ts.Node[] {
return state.selection;
},
set selection(arr) {
replace(state.selection, arr);
},
} as ProgramState,
selection: [] as ts.Node[],
code: initialCode,
ast: createSourceFile(initialCode),
codeToAst(this: { code: string }, code = this.code) {
return createSourceFile(code);
},
astToCode(this: { ast: ts.SourceFile | null }, ast = this.ast) {
return !ast ? '' : printer.printFile(ast);
},
updateAst() {
this.ast = this.codeToAst(this.code);
},
updateCode() {
this.code = this.astToCode(this.ast as ts.SourceFile);
},
};
});
useReaction(
() => state.code,
code => safeLsSet(localStorageCodeKey, code)
);
useReaction(
() => state.code,
() => {
state.updateAst();
const tsInfo = getProgramForText(state.code);
state.programState.program = tsInfo.program;
state.programState.languageService = tsInfo.languageService;
}
);
useEventListener(document, 'mouseup', () => {
if (state.programState.draggingNode) {
if (state.programState.hoveringCodeEditor) {
const node = state.programState.draggingNode;
traverse(node).forEach(function (child) {
if (child && ts.isStringLiteral(child)) {
this.update(ts.createStringLiteral(child.text));
}
if (child && ts.isNumericLiteral(child)) {
this.update(ts.createNumericLiteral(child.text));
}
});
// TODO: modify AST here
state.code += '\n' + printer.printNode(ts.EmitHint.Unspecified, node, state.ast);
}
state.programState.draggingNode = null;
}
});
useEventListener(document, 'keydown', e => {
const event = e as KeyboardEvent;
// Esc key
if (event.which === 27 && state.programState.draggingNode) {
state.programState.draggingNode = null;
}
});
return useObserver(() => {
const options = { programState: state.programState };
return (
<div
css={{
height: '100vh',
overflow: 'hidden',
display: 'flex',
backgroundColor: '#222',
}}
className={props.className}
>
<Portal>
<Transition timeout={200} unmountOnExit appear in mountOnEnter>
{transitionState => (
<div
className="sidebar-darkening-overlay"
css={{
backgroundBlendMode: 'multiply',
position: 'fixed',
backgroundColor: 'rgba(0, 0, 0, 0.45)',
pointerEvents: 'none',
opacity: transitionState === 'entered' ? 1 : 0,
transition: 'opacity 0.2s ease-in-out',
top: 0,
width: 300,
left: 0,
bottom: 0,
}}
/>
)}
</Transition>
</Portal>
<div
css={{
width: '50%',
height: '100%',
}}
>
<div css={{ height: '100%', overflow: 'auto', fontSize: 14 }}>
<Toolbox options={options} />
</div>
</div>
<div
css={{ width: '50%', display: 'flex', flexDirection: 'column', alignItems: 'stretch' }}
>
<div
css={{
height: '50%',
fontSize: 14,
padding: 20,
overflow: 'auto',
}}
onMouseEnter={() => {
state.programState.hoveringCodeEditor = true;
}}
onMouseLeave={() => {
state.programState.hoveringCodeEditor = false;
}}
>
{state.ast && <Node node={state.ast} options={options} />}
{state.programState.draggingNode &&
!state.programState.hoveringNode &&
state.programState.hoveringCodeEditor && (
<div
css={{
backgroundColor: theme.colors.primary,
height: 2,
borderRadius: 10,
width: '100%',
}}
/>
)}
<DraggingNodeOverlay options={options} />
</div>
<div
css={{
height: '50%',
'.monaco-editor, .monaco-editor-background, .monaco-editor .inputarea.ime-input, .monaco-editor .margin': {
backgroundColor: 'transparent !important',
},
}}
>
<MonacoEditor
language="typescript"
theme="vs-dark"
value={state.code}
options={{
fontSize: 11,
renderLineHighlight: 'none',
minimap: { enabled: false },
scrollbar: {
horizontal: 'hidden',
vertical: 'hidden',
},
automaticLayout: true,
scrollBeyondLastLine: false,
}}
onChange={val => {
state.code = val;
}}
/>
</div>
</div>
</div>
);
});
} | the_stack |
import dox from 'dox';
import fs from 'fs';
import path from 'path';
import {
upperFirst,
ObjectTypeComposer,
EnumTypeComposer,
ObjectTypeComposerArgumentConfigDefinition,
ObjectTypeComposerFieldConfigMapDefinition,
ObjectTypeComposerArgumentConfigAsObjectDefinition,
ObjectTypeComposerFieldConfigAsObjectDefinition,
} from 'graphql-compose';
import { reorderKeys } from './utils';
export type ElasticParamConfigT = {
type: string;
name?: string;
options?: any;
default?: any;
};
export type ElasticCaSettingsUrlT = {
fmt: string;
req: {
[name: string]: ElasticParamConfigT;
};
};
export type ElasticCaSettingsT = {
params: {
[name: string]: ElasticParamConfigT;
};
url?: ElasticCaSettingsUrlT;
urls?: ElasticCaSettingsUrlT[];
needBody?: true;
method?: string;
};
export type ElasticParsedArgsDescriptionsT = {
[argName: string]: string | undefined;
};
export type ElasticParsedSourceT = {
[dottedMethodName: string]: {
elasticMethod: string | string[];
description: string | undefined;
argsSettings: ElasticCaSettingsT | undefined;
argsDescriptions: ElasticParsedArgsDescriptionsT;
};
};
export type ElasticApiParserOptsT = {
elasticClient?: any; // Elastic client
apiVersion?: string;
prefix?: string;
elasticApiFilePath?: string;
};
export default class ElasticApiParser {
cachedEnums: {
[fieldName: string]: { [stringifiedValues: string]: EnumTypeComposer<any> };
};
apiVersion: string;
prefix: string;
elasticClient: any;
parsedSource: ElasticParsedSourceT;
constructor(opts: ElasticApiParserOptsT = {}) {
// available versions can be found in installed package `elasticsearch`
// in file /node_modules/elasticsearch/src/lib/apis/index.js
this.apiVersion =
opts.apiVersion ||
(opts.elasticClient &&
opts.elasticClient.transport &&
opts.elasticClient.transport._config &&
opts.elasticClient.transport._config.apiVersion) ||
'_default';
const apiFilePath = path.resolve(
opts.elasticApiFilePath || ElasticApiParser.findApiVersionFile(this.apiVersion)
);
const source = ElasticApiParser.loadApiFile(apiFilePath);
this.parsedSource = ElasticApiParser.parseSource(source);
this.elasticClient = opts.elasticClient;
this.prefix = opts.prefix || 'Elastic';
this.cachedEnums = {};
}
static loadFile(absolutePath: string): string {
return fs.readFileSync(absolutePath, 'utf8');
}
static loadApiFile(absolutePath: string): string {
let code;
try {
code = ElasticApiParser.loadFile(absolutePath);
} catch (e) {
throw new Error(`Cannot load Elastic API source file from ${absolutePath}`);
}
return ElasticApiParser.cleanUpSource(code);
}
static loadApiListFile(absolutePath: string): string {
let code;
try {
code = ElasticApiParser.loadFile(absolutePath);
} catch (e) {
throw new Error(`Cannot load Elastic API file with available versions from ${absolutePath}`);
}
return code;
}
static findApiVersionFile(version: string): string {
const esModulePath = path.dirname(require.resolve('elasticsearch'));
const apiFolder = `${esModulePath}/lib/apis/`;
const apiListFile = path.resolve(apiFolder, 'index.js');
const apiListCode = ElasticApiParser.loadApiListFile(apiListFile);
// parsing elasticsearch module 13.x and above
// get '5.3'() { return require('./5_3'); },
const re = new RegExp(`\\'${version}\\'\\(\\).*require\\(\\'(.+)\\'\\)`, 'gi');
const match = re.exec(apiListCode);
if (match && match[1]) {
return path.resolve(apiFolder, `${match[1]}.js`);
}
// parsing elasticsearch module 12.x and below
// '5.0': require('./5_0'),
const re12 = new RegExp(`\\'${version}\\':\\srequire\\(\\'(.+)\\'\\)`, 'gi');
const match12 = re12.exec(apiListCode);
if (match12 && match12[1]) {
return path.resolve(apiFolder, `${match12[1]}.js`);
}
throw new Error(`Can not found Elastic version '${version}' in ${apiListFile}`);
}
static cleanUpSource(code: string): string {
// remove invalid markup
// {<<api-param-type-boolean,`Boolean`>>} converted to {Boolean}
let codeCleaned = code.replace(/{<<.+`(.*)`.+}/gi, '{$1}');
// replace api.indices.prototype['delete'] = ca({
// on api.indices.prototype.delete = ca({
codeCleaned = codeCleaned.replace(/(api.*)\['(.+)'\](.*ca)/gi, '$1.$2$3');
return codeCleaned;
}
static parseParamsDescription(doxItemAST: any): { [fieldName: string]: string | undefined } {
const descriptions = {} as Record<string, string | undefined>;
if (Array.isArray(doxItemAST.tags)) {
doxItemAST.tags.forEach((tag: any) => {
if (!tag || tag.type !== 'param') return;
if (tag.name === 'params') return;
const name = ElasticApiParser.cleanupParamName(tag.name);
if (!name) return;
descriptions[name] = ElasticApiParser.cleanupDescription(tag.description);
});
}
return descriptions;
}
static cleanupDescription(str: string): string | undefined {
if (typeof str === 'string') {
if (str.startsWith('- ')) {
str = str.substr(2);
}
str = str.trim();
return str;
}
return undefined;
}
static cleanupParamName(str: string): string | undefined {
if (typeof str === 'string') {
if (str.startsWith('params.')) {
str = str.substr(7);
}
str = str.trim();
return str;
}
return undefined;
}
static codeToSettings(code: string): ElasticCaSettingsT | undefined {
// find code in ca({});
const reg = /ca\((\{(.|\n)+\})\);/g;
const matches = reg.exec(code);
if (matches && matches[1]) {
return eval('(' + matches[1] + ')'); // eslint-disable-line no-eval
}
return undefined;
}
static getMethodName(str: string): string | string[] {
const parts = str.split('.');
if (parts[0] === 'api') {
parts.shift();
}
if (parts.length === 1) {
return parts[0];
} else {
return parts.filter((o) => o !== 'prototype');
}
}
static parseSource(source: string): ElasticParsedSourceT {
const result = {} as ElasticParsedSourceT;
if (!source || typeof source !== 'string') {
throw Error('Empty source. It should be non-empty string.');
}
const doxAST = dox.parseComments(source, { raw: true });
if (!doxAST || !Array.isArray(doxAST)) {
throw Error('Incorrect response from dox.parseComments');
}
doxAST.forEach((item) => {
if (!item.ctx || !item.ctx.string) {
return;
}
// method description
let description;
if (item.description && item.description.full) {
description = ElasticApiParser.cleanupDescription(item.description.full);
}
const elasticMethod = ElasticApiParser.getMethodName(item.ctx.string);
const dottedMethodName = Array.isArray(elasticMethod)
? elasticMethod.join('.')
: elasticMethod;
result[dottedMethodName] = {
elasticMethod,
description,
argsSettings: ElasticApiParser.codeToSettings(item.code),
argsDescriptions: ElasticApiParser.parseParamsDescription(item),
};
});
return result;
}
generateFieldMap(): ObjectTypeComposerFieldConfigAsObjectDefinition<any, any> {
const result = {} as ObjectTypeComposerFieldConfigAsObjectDefinition<any, any>;
Object.keys(this.parsedSource).forEach((methodName) => {
result[methodName] = this.generateFieldConfig(methodName);
});
const fieldMap = this.reassembleNestedFields(result);
return reorderKeys(fieldMap, [
'cat',
'cluster',
'indices',
'ingest',
'nodes',
'snapshot',
'tasks',
'search',
]);
}
generateFieldConfig(methodName: string, methodArgs?: { [paramName: string]: any }) {
if (!methodName) {
throw new Error(`You should provide Elastic search method.`);
}
if (!this.parsedSource[methodName]) {
throw new Error(`Elastic search method '${methodName}' does not exists.`);
}
const { description, argsSettings, argsDescriptions, elasticMethod } =
this.parsedSource[methodName];
const argMap = this.settingsToArgMap(argsSettings, argsDescriptions);
return {
type: 'JSON',
description,
args: argMap,
// eslint-disable-next-line no-unused-vars
resolve: (_source: any, args: any, context: any, _info: any) => {
const client = (context && context.elasticClient) || this.elasticClient;
if (!client) {
throw new Error(
'You should provide `elasticClient` when created types via ' +
'`opts.elasticClient` or in runtime via GraphQL context'
);
}
if (Array.isArray(elasticMethod)) {
return client[elasticMethod[0]][elasticMethod[1]]({
...methodArgs,
...args,
});
}
return client[elasticMethod]({ ...methodArgs, ...args });
},
};
}
paramToGraphQLArgConfig(
paramCfg: ElasticParamConfigT,
fieldName: string,
description?: string
): ObjectTypeComposerArgumentConfigDefinition {
const result = {
type: this.paramTypeToGraphQL(paramCfg, fieldName),
} as ObjectTypeComposerArgumentConfigAsObjectDefinition;
if (paramCfg.default) {
result.defaultValue = paramCfg.default;
if (result.type === 'Float' || result.type === 'Int') {
const defaultNumber = Number(result.defaultValue);
if (Number.isNaN(defaultNumber)) {
// Handle broken data where default is not valid for the given type
// https://github.com/graphql-compose/graphql-compose-elasticsearch/issues/49
delete result.defaultValue;
} else {
result.defaultValue = defaultNumber;
}
} else if (result.type === 'Boolean') {
const t = result.defaultValue;
result.defaultValue = t === 'true' || t === '1' || t === true;
}
} else if (fieldName === 'format') {
result.defaultValue = 'json';
}
if (description) {
result.description = description;
}
if (Array.isArray(result.defaultValue)) {
result.type = [result.type] as any;
}
return result;
}
paramTypeToGraphQL(
paramCfg: ElasticParamConfigT,
fieldName: string
): EnumTypeComposer<any> | string {
switch (paramCfg.type) {
case 'string':
return 'String';
case 'boolean':
return 'Boolean';
case 'number':
return 'Float';
case 'time':
return 'String';
case 'list':
return 'JSON';
case 'enum':
if (Array.isArray(paramCfg.options)) {
return this.getEnumType(fieldName, paramCfg.options);
}
return 'String';
case undefined:
// some fields may not have type definition in API file,
// eg '@param {anything} params.operationThreading - ?'
return 'JSON';
default:
// console.log(
// // eslint-disable-line
// `New type '${paramCfg.type}' in elastic params setting for field ${fieldName}.`
// );
return 'JSON';
}
}
getEnumType(fieldName: string, values: ReadonlyArray<any>): EnumTypeComposer<any> {
const key = fieldName;
const subKey = JSON.stringify(values);
if (!this.cachedEnums[key]) {
this.cachedEnums[key] = {};
}
if (!this.cachedEnums[key][subKey]) {
const enumValues = values.reduce((result, val) => {
if (val === '') {
result.empty_string = { value: '' };
} else if (val === 'true') {
result.true_string = { value: 'true' };
} else if (val === true) {
result.true_boolean = { value: true };
} else if (val === 'false') {
result.false_string = { value: 'false' };
} else if (val === false) {
result.false_boolean = { value: false };
} else if (val === 'null') {
result.null_string = { value: 'null' };
} else if (Number.isFinite(val)) {
result[`number_${val}`] = { value: val };
} else if (typeof val === 'string') {
result[val] = { value: val };
}
return result;
}, {});
const n = Object.keys(this.cachedEnums[key]).length;
const postfix = n === 0 ? '' : `_${n}`;
this.cachedEnums[key][subKey] = EnumTypeComposer.createTemp({
name: `${this.prefix}Enum_${upperFirst(fieldName)}${postfix}`,
values: enumValues,
});
}
return this.cachedEnums[key][subKey];
}
settingsToArgMap(
settings?: ElasticCaSettingsT,
descriptions: ElasticParsedArgsDescriptionsT = {}
): ObjectTypeComposerArgumentConfigAsObjectDefinition {
const result = {} as ObjectTypeComposerArgumentConfigAsObjectDefinition;
const { params, urls, url, method, needBody } = settings || {};
if (method === 'POST' || method === 'PUT') {
result.body = {
type: needBody ? 'JSON!' : 'JSON',
};
}
if (params) {
Object.keys(params).forEach((k) => {
const fieldConfig = this.paramToGraphQLArgConfig(params[k], k, descriptions[k]);
if (fieldConfig) {
result[k] = fieldConfig;
}
});
}
const urlList = urls || (url ? [url] : null);
if (Array.isArray(urlList)) {
urlList.forEach((item) => {
if (item.req) {
Object.keys(item.req).forEach((k) => {
const fieldConfig = this.paramToGraphQLArgConfig(item.req[k], k, descriptions[k]);
if (fieldConfig) {
result[k] = fieldConfig;
}
});
}
});
}
return result;
}
reassembleNestedFields(
fields: ObjectTypeComposerFieldConfigMapDefinition<any, any>
): ObjectTypeComposerFieldConfigAsObjectDefinition<any, any> {
const result = {} as ObjectTypeComposerFieldConfigAsObjectDefinition<any, any>;
Object.keys(fields).forEach((k) => {
const names = k.split('.');
if (names.length === 1) {
result[names[0]] = fields[k];
} else {
if (!result[names[0]]) {
result[names[0]] = {
type: ObjectTypeComposer.createTemp({
name: `${this.prefix}_${upperFirst(names[0])}`,
// fields: (() => {}),
}),
resolve: () => {
return {};
},
};
}
result[names[0]].type.setField(names[1], fields[k]);
}
});
return result;
}
} | the_stack |
export class Color {
readonly _originalTextIsValid: boolean;
private _hsla?: Array<number>;
constructor(
readonly _rgba: Array<number>,
readonly _format: string,
readonly _originalText: string | null,
) {
this._originalTextIsValid = !!this._originalText;
if (typeof this._rgba[3] === "undefined") {
this._rgba[3] = 1;
}
for (let i = 0; i < 4; ++i) {
if (this._rgba[i] < 0) {
this._rgba[i] = 0;
this._originalTextIsValid = false;
}
if (this._rgba[i] > 1) {
this._rgba[i] = 1;
this._originalTextIsValid = false;
}
}
}
static parse(text: string): Color | null {
const value = text.toLowerCase().replace(/\s+/g, "");
const simple = /^(?:#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8}))$/i;
let match = value.match(simple);
if (match) {
if (match[1]) { // hex
let hex = match[1].toLowerCase();
let format;
if (hex.length === 3) {
format = Color.Format.ShortHEX;
hex = hex.charAt(0) + hex.charAt(0) + hex.charAt(1) + hex.charAt(1) +
hex.charAt(2) + hex.charAt(2);
} else if (hex.length === 4) {
format = Color.Format.ShortHEXA;
hex = hex.charAt(0) + hex.charAt(0) + hex.charAt(1) + hex.charAt(1) +
hex.charAt(2) + hex.charAt(2) +
hex.charAt(3) + hex.charAt(3);
} else if (hex.length === 6) {
format = Color.Format.HEX;
} else {
format = Color.Format.HEXA;
}
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
let a = 1;
if (hex.length === 8) {
a = parseInt(hex.substring(6, 8), 16) / 255;
}
return new Color([r / 255, g / 255, b / 255, a], format, text);
}
return null;
}
// rgb/rgba(), hsl/hsla()
match = text.toLowerCase().match(/^\s*(?:(rgba?)|(hsla?))\((.*)\)\s*$/);
if (match) {
const components = match[3].trim();
let values = components.split(/\s*,\s*/);
if (values.length === 1) {
values = components.split(/\s+/);
if (values[3] === "/") {
values.splice(3, 1);
if (values.length !== 4) {
return null;
}
} else if (
(values.length > 2 && values[2].indexOf("/") !== -1) ||
(values.length > 3 && values[3].indexOf("/") !== -1)
) {
const alpha = values.slice(2, 4).join("");
values = values.slice(0, 2).concat(alpha.split(/\//)).concat(
values.slice(4),
);
} else if (values.length >= 4) {
return null;
}
}
if (
values.length !== 3 && values.length !== 4 || values.indexOf("") > -1
) {
return null;
}
const hasAlpha = (values[3] !== undefined);
if (match[1]) { // rgb/rgba
const rgba = [
Color._parseRgbNumeric(values[0]),
Color._parseRgbNumeric(values[1]),
Color._parseRgbNumeric(values[2]),
hasAlpha ? Color._parseAlphaNumeric(values[3]) : 1,
];
if (rgba.indexOf(null) > -1) {
return null;
}
return new Color(
rgba as number[],
hasAlpha ? Color.Format.RGBA : Color.Format.RGB,
text,
);
}
if (match[2]) { // hsl/hsla
const hsla = [
Color._parseHueNumeric(values[0]),
Color._parseSatLightNumeric(values[1]),
Color._parseSatLightNumeric(values[2]),
hasAlpha ? Color._parseAlphaNumeric(values[3]) : 1,
];
if (hsla.indexOf(null) > -1) {
return null;
}
const rgba = [] as number[];
Color.hsl2rgb(hsla as number[], rgba);
return new Color(
rgba,
hasAlpha ? Color.Format.HSLA : Color.Format.HSL,
text,
);
}
}
return null;
}
private static _parsePercentOrNumber(value: string): number | null {
if (isNaN(Number(value.replace("%", "")))) {
return null;
}
const parsed = parseFloat(value);
if (value.indexOf("%") !== -1) {
if (value.indexOf("%") !== value.length - 1) {
return null;
}
return parsed / 100;
}
return parsed;
}
private static _parseRgbNumeric(value: string): number | null {
const parsed = Color._parsePercentOrNumber(value);
if (parsed === null) {
return null;
}
if (value.indexOf("%") !== -1) {
return parsed;
}
return parsed / 255;
}
private static _parseHueNumeric(value: string): number | null {
const angle = value.replace(/(deg|g?rad|turn)$/, "");
if (isNaN(Number(angle)) || value.match(/\s+(deg|g?rad|turn)/)) {
return null;
}
const number = parseFloat(angle);
if (value.indexOf("turn") !== -1) {
return number % 1;
} else if (value.indexOf("grad") !== -1) {
return (number / 400) % 1;
} else if (value.indexOf("rad") !== -1) {
return (number / (2 * Math.PI)) % 1;
}
return (number / 360) % 1;
}
private static _parseSatLightNumeric(value: string): number | null {
if (
value.indexOf("%") !== value.length - 1 ||
isNaN(Number(value.replace("%", "")))
) {
return null;
}
const parsed = parseFloat(value);
return Math.min(1, parsed / 100);
}
static _parseAlphaNumeric(value: string): number | null {
return Color._parsePercentOrNumber(value);
}
static hsl2rgb(hsl: Array<number>, outRgb: Array<number>): void {
const h = hsl[0];
let s = hsl[1];
const l = hsl[2];
function hue2rgb(p: number, q: number, h: number): number {
if (h < 0) {
h += 1;
} else if (h > 1) {
h -= 1;
}
if ((h * 6) < 1) {
return p + (q - p) * h * 6;
} else if ((h * 2) < 1) {
return q;
} else if ((h * 3) < 2) {
return p + (q - p) * ((2 / 3) - h) * 6;
} else {
return p;
}
}
if (s < 0) {
s = 0;
}
let q;
if (l <= 0.5) {
q = l * (1 + s);
} else {
q = l + s - (l * s);
}
const p = 2 * l - q;
const tr = h + (1 / 3);
const tg = h;
const tb = h - (1 / 3);
outRgb[0] = hue2rgb(p, q, tr);
outRgb[1] = hue2rgb(p, q, tg);
outRgb[2] = hue2rgb(p, q, tb);
outRgb[3] = hsl[3];
}
format(): string {
return this._format;
}
/**
* @return HSLA with components within [0..1]
*/
hsla(): Array<number> {
if (this._hsla) {
return this._hsla;
}
const r = this._rgba[0];
const g = this._rgba[1];
const b = this._rgba[2];
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const diff = max - min;
const add = max + min;
let h;
if (min === max) {
h = 0;
} else if (r === max) {
h = ((1 / 6 * (g - b) / diff) + 1) % 1;
} else if (g === max) {
h = (1 / 6 * (b - r) / diff) + 1 / 3;
} else {
h = (1 / 6 * (r - g) / diff) + 2 / 3;
}
const l = 0.5 * add;
let s;
if (l === 0) {
s = 0;
} else if (l === 1) {
s = 0;
} else if (l <= 0.5) {
s = diff / add;
} else {
s = diff / (2 - add);
}
this._hsla = [h, s, l, this._rgba[3]];
return this._hsla;
}
hasAlpha(): boolean {
return this._rgba[3] !== 1;
}
detectHEXFormat(): string {
let canBeShort = true;
for (let i = 0; i < 4; ++i) {
const c = Math.round(this._rgba[i] * 255);
if (c % 17) {
canBeShort = false;
break;
}
}
const hasAlpha = this.hasAlpha();
const cf = Color.Format;
if (canBeShort) {
return hasAlpha ? cf.ShortHEXA : cf.ShortHEX;
}
return hasAlpha ? cf.HEXA : cf.HEX;
}
asString(format: string): string | null {
if (format === this._format && this._originalTextIsValid) {
return this._originalText;
}
if (!format) {
format = this._format;
}
function toRgbValue(value: number): number {
return Math.round(value * 255);
}
function toHexValue(value: number): string {
const hex = Math.round(value * 255).toString(16);
return hex.length === 1 ? "0" + hex : hex;
}
function toShortHexValue(value: number): string {
return (Math.round(value * 255) / 17).toString(16);
}
switch (format) {
case Color.Format.Original:
return this._originalText;
case Color.Format.RGB:
if (this.hasAlpha()) {
return null;
}
return `rgb(${toRgbValue(this._rgba[0])}, ${
toRgbValue(this._rgba[1])
}, ${toRgbValue(this._rgba[2])})`;
case Color.Format.RGBA:
return `rgba(${toRgbValue(this._rgba[0])}, ${
toRgbValue(this._rgba[1])
}, ${toRgbValue(this._rgba[2])}, ${this._rgba[3]})`;
case Color.Format.HSL: {
if (this.hasAlpha()) {
return null;
}
const hsl = this.hsla();
return `hsl(${Math.round(hsl[0] * 360)}, ${
Math.round(hsl[1] * 100)
}%, ${Math.round(hsl[2] * 100)}%)`;
}
case Color.Format.HSLA: {
const hsla = this.hsla();
return `hsla(${Math.round(hsla[0] * 360)}, ${
Math.round(hsla[1] * 100)
}%, ${Math.round(hsla[2] * 100)}%, ${hsla[3]})`;
}
case Color.Format.HEXA:
return `#${toHexValue(this._rgba[0])}${toHexValue(this._rgba[1])}${
toHexValue(this._rgba[2])
}${toHexValue(this._rgba[3])}`.toLowerCase();
case Color.Format.HEX:
if (this.hasAlpha()) {
return null;
}
return `#${toHexValue(this._rgba[0])}${toHexValue(this._rgba[1])}${
toHexValue(this._rgba[2])
}`.toLowerCase();
case Color.Format.ShortHEXA: {
const hexFormat = this.detectHEXFormat();
if (
hexFormat !== Color.Format.ShortHEXA &&
hexFormat !== Color.Format.ShortHEX
) {
return null;
}
return `#${toShortHexValue(this._rgba[0])}${
toShortHexValue(this._rgba[1])
}${toShortHexValue(this._rgba[2])}${toShortHexValue(this._rgba[3])}`
.toLowerCase();
}
case Color.Format.ShortHEX:
if (this.hasAlpha()) {
return null;
}
if (this.detectHEXFormat() !== Color.Format.ShortHEX) {
return null;
}
return `#${toShortHexValue(this._rgba[0])}${
toShortHexValue(this._rgba[1])
}${toShortHexValue(this._rgba[2])}`.toLowerCase();
}
return this._originalText;
}
rgba(): Array<number> {
return this._rgba.slice();
}
canonicalRGBA(): Array<number> {
const rgba = new Array(4);
for (let i = 0; i < 3; ++i) {
rgba[i] = Math.round(this._rgba[i] * 255);
}
rgba[3] = this._rgba[3];
return rgba;
}
static Regex =
/((?:rgb|hsl)a?\([^)]+\)|#[0-9a-fA-F]{8}|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3,4}|\b[a-zA-Z]+\b(?!-))/g;
static Format = {
Original: "original",
HEX: "hex",
ShortHEX: "shorthex",
HEXA: "hexa",
ShortHEXA: "shorthexa",
RGB: "rgb",
RGBA: "rgba",
HSL: "hsl",
HSLA: "hsla",
};
} | the_stack |
'use strict';
import * as editorCommon from 'vs/editor/common/editorCommon';
import {ViewPart} from 'vs/editor/browser/view/viewPart';
import {FastDomNode, createFastDomNode} from 'vs/base/browser/styleMutator';
import {ViewContext} from 'vs/editor/common/view/viewContext';
import {ViewLinesViewportData} from 'vs/editor/common/viewLayout/viewLinesViewportData';
import {InlineDecoration} from 'vs/editor/common/viewModel/viewModel';
export interface IVisibleLineData {
getDomNode(): HTMLElement;
setDomNode(domNode: HTMLElement): void;
onContentChanged(): void;
onLinesInsertedAbove(): void;
onLinesDeletedAbove(): void;
onLineChangedAbove(): void;
onTokensChanged(): void;
onConfigurationChanged(e:editorCommon.IConfigurationChangedEvent): void;
getLineOuterHTML(out:string[], lineNumber: number, deltaTop: number): void;
getLineInnerHTML(lineNumber: number): string;
shouldUpdateHTML(startLineNumber:number, lineNumber:number, inlineDecorations:InlineDecoration[]): boolean;
layoutLine(lineNumber: number, deltaTop:number): void;
}
interface IRendererContext<T extends IVisibleLineData> {
domNode: HTMLElement;
rendLineNumberStart: number;
lines: T[];
linesLength: number;
getInlineDecorationsForLineInViewport(lineNumber:number): InlineDecoration[];
viewportTop: number;
viewportHeight: number;
scrollDomNode: HTMLElement;
scrollDomNodeIsAbove: boolean;
}
export interface ILine {
onContentChanged(): void;
onLinesInsertedAbove(): void;
onLinesDeletedAbove(): void;
onLineChangedAbove(): void;
onTokensChanged(): void;
}
export class RenderedLinesCollection<T extends ILine> {
private _lines: T[];
private _rendLineNumberStart:number;
private _createLine:()=>T;
constructor(createLine:()=>T) {
this._lines = [];
this._rendLineNumberStart = 1;
this._createLine = createLine;
}
_set(rendLineNumberStart:number, lines:T[]): void {
this._lines = lines;
this._rendLineNumberStart = rendLineNumberStart;
}
_get(): { rendLineNumberStart:number; lines:T[]; } {
return {
rendLineNumberStart: this._rendLineNumberStart,
lines: this._lines
};
}
/**
* @returns Inclusive line number that is inside this collection
*/
public getStartLineNumber(): number {
return this._rendLineNumberStart;
}
/**
* @returns Inclusive line number that is inside this collection
*/
public getEndLineNumber(): number {
return this._rendLineNumberStart + this._lines.length - 1;
}
public getCount(): number {
return this._lines.length;
}
public getLine(lineNumber:number): T {
let lineIndex = lineNumber - this._rendLineNumberStart;
if (lineIndex < 0 || lineIndex >= this._lines.length) {
throw new Error('Illegal value for lineNumber: ' + lineNumber);
}
return this._lines[lineIndex];
}
/**
* @returns Lines that were removed from this collection
*/
public onModelLinesDeleted(deleteFromLineNumber:number, deleteToLineNumber:number): T[] {
if (this.getCount() === 0) {
// no lines
return null;
}
let startLineNumber = this.getStartLineNumber();
let endLineNumber = this.getEndLineNumber();
// Record what needs to be deleted, notify lines that survive after deletion
let deleteStartIndex = 0;
let deleteCount = 0;
for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
let lineIndex = lineNumber - this._rendLineNumberStart;
if (deleteFromLineNumber <= lineNumber && lineNumber <= deleteToLineNumber) {
// this is a line to be deleted
if (deleteCount === 0) {
// this is the first line to be deleted
deleteStartIndex = lineIndex;
deleteCount = 1;
} else {
deleteCount++;
}
} else if (lineNumber > deleteToLineNumber) {
// this is a line after the deletion
this._lines[lineIndex].onLinesDeletedAbove();
}
}
// Adjust this._rendLineNumberStart for lines deleted above
if (deleteFromLineNumber < startLineNumber) {
// Something was deleted above
let deleteAboveCount = 0;
if (deleteToLineNumber < startLineNumber) {
// the entire deleted lines are above
deleteAboveCount = deleteToLineNumber - deleteFromLineNumber + 1;
} else {
deleteAboveCount = startLineNumber - deleteFromLineNumber;
}
this._rendLineNumberStart -= deleteAboveCount;
}
let deleted = this._lines.splice(deleteStartIndex, deleteCount);
return deleted;
}
public onModelLineChanged(changedLineNumber:number): boolean {
if (this.getCount() === 0) {
// no lines
return false;
}
let startLineNumber = this.getStartLineNumber();
let endLineNumber = this.getEndLineNumber();
// Notify lines after the change
let notifiedSomeone = false;
for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
let lineIndex = lineNumber - this._rendLineNumberStart;
if (lineNumber === changedLineNumber) {
this._lines[lineIndex].onContentChanged();
notifiedSomeone = true;
} else if (lineNumber > changedLineNumber) {
// this is a line after the changed one
this._lines[lineIndex].onLineChangedAbove();
notifiedSomeone = true;
}
}
return notifiedSomeone;
}
public onModelLinesInserted(insertFromLineNumber:number, insertToLineNumber:number): T[] {
if (this.getCount() === 0) {
// no lines
return null;
}
let insertCnt = insertToLineNumber - insertFromLineNumber + 1;
let startLineNumber = this.getStartLineNumber();
let endLineNumber = this.getEndLineNumber();
// Notify lines that survive after insertion
for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
let lineIndex = lineNumber - this._rendLineNumberStart;
if (insertFromLineNumber <= lineNumber) {
this._lines[lineIndex].onLinesInsertedAbove();
}
}
if (insertFromLineNumber <= startLineNumber) {
// inserting above the viewport
this._rendLineNumberStart += insertCnt;
return null;
}
if (insertFromLineNumber > endLineNumber) {
// inserting below the viewport
return null;
}
if (insertCnt + insertFromLineNumber > endLineNumber) {
// insert inside the viewport in such a way that all remaining lines are pushed outside
let deleted = this._lines.splice(insertFromLineNumber - this._rendLineNumberStart, endLineNumber - insertFromLineNumber + 1);
return deleted;
}
// insert inside the viewport, push out some lines, but not all remaining lines
let newLines: T[] = [];
for (let i = 0; i < insertCnt; i++) {
newLines[i] = this._createLine();
}
let insertIndex = insertFromLineNumber - this._rendLineNumberStart;
let beforeLines = this._lines.slice(0, insertIndex);
let afterLines = this._lines.slice(insertIndex, this._lines.length - insertCnt);
let deletedLines = this._lines.slice(this._lines.length - insertCnt, this._lines.length);
this._lines = beforeLines.concat(newLines).concat(afterLines);
return deletedLines;
}
public onModelTokensChanged(changedFromLineNumber:number, changedToLineNumber:number): boolean {
if (this.getCount() === 0) {
// no lines
return false;
}
let startLineNumber = this.getStartLineNumber();
let endLineNumber = this.getEndLineNumber();
// Notify lines after the change
let notifiedSomeone = false;
for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
let lineIndex = lineNumber - this._rendLineNumberStart;
if (changedFromLineNumber <= lineNumber && lineNumber <= changedToLineNumber) {
this._lines[lineIndex].onTokensChanged();
notifiedSomeone = true;
}
}
return notifiedSomeone;
}
}
export abstract class ViewLayer<T extends IVisibleLineData> extends ViewPart {
protected domNode: FastDomNode;
protected _linesCollection: RenderedLinesCollection<T>;
private _renderer: ViewLayerRenderer<T>;
private _scrollDomNode: HTMLElement;
private _scrollDomNodeIsAbove: boolean;
constructor(context:ViewContext) {
super(context);
this.domNode = this._createDomNode();
this._linesCollection = new RenderedLinesCollection<T>(() => this._createLine());
this._scrollDomNode = null;
this._scrollDomNodeIsAbove = false;
this._renderer = new ViewLayerRenderer<T>(
() => this._createLine(),
() => this._extraDomNodeHTML()
);
}
public dispose(): void {
super.dispose();
this._linesCollection = null;
}
protected _extraDomNodeHTML(): string {
return '';
}
// ---- begin view event handlers
public onConfigurationChanged(e:editorCommon.IConfigurationChangedEvent): boolean {
let startLineNumber = this._linesCollection.getStartLineNumber();
let endLineNumber = this._linesCollection.getEndLineNumber();
for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
let line = this._linesCollection.getLine(lineNumber);
line.onConfigurationChanged(e);
}
return true;
}
public onLayoutChanged(layoutInfo:editorCommon.EditorLayoutInfo): boolean {
return true;
}
public onScrollChanged(e:editorCommon.IScrollEvent): boolean {
return e.scrollTopChanged;
}
public onZonesChanged(): boolean {
return true;
}
public onModelFlushed(): boolean {
this._linesCollection = new RenderedLinesCollection<T>(() => this._createLine());
this._scrollDomNode = null;
// No need to clear the dom node because a full .innerHTML will occur in ViewLayerRenderer._render
return true;
}
public onModelLinesDeleted(e:editorCommon.IViewLinesDeletedEvent): boolean {
let deleted = this._linesCollection.onModelLinesDeleted(e.fromLineNumber, e.toLineNumber);
if (deleted) {
// Remove from DOM
for (let i = 0, len = deleted.length; i < len; i++) {
let lineDomNode = deleted[i].getDomNode();
if (lineDomNode) {
this.domNode.domNode.removeChild(lineDomNode);
}
}
}
return true;
}
public onModelLineChanged(e:editorCommon.IViewLineChangedEvent): boolean {
return this._linesCollection.onModelLineChanged(e.lineNumber);
}
public onModelLinesInserted(e:editorCommon.IViewLinesInsertedEvent): boolean {
let deleted = this._linesCollection.onModelLinesInserted(e.fromLineNumber, e.toLineNumber);
if (deleted) {
// Remove from DOM
for (let i = 0, len = deleted.length; i < len; i++) {
let lineDomNode = deleted[i].getDomNode();
if (lineDomNode) {
this.domNode.domNode.removeChild(lineDomNode);
}
}
}
return true;
}
public onModelTokensChanged(e:editorCommon.IViewTokensChangedEvent): boolean {
return this._linesCollection.onModelTokensChanged(e.fromLineNumber, e.toLineNumber);
}
// ---- end view event handlers
public _renderLines(linesViewportData:ViewLinesViewportData): void {
let inp = this._linesCollection._get();
let ctx: IRendererContext<T> = {
domNode: this.domNode.domNode,
rendLineNumberStart: inp.rendLineNumberStart,
lines: inp.lines,
linesLength: inp.lines.length,
getInlineDecorationsForLineInViewport: (lineNumber:number) => linesViewportData.getInlineDecorationsForLineInViewport(lineNumber),
viewportTop: linesViewportData.viewportTop,
viewportHeight: linesViewportData.viewportHeight,
scrollDomNode: this._scrollDomNode,
scrollDomNodeIsAbove: this._scrollDomNodeIsAbove
};
// Decide if this render will do a single update (single large .innerHTML) or many updates (inserting/removing dom nodes)
let resCtx = this._renderer.renderWithManyUpdates(ctx, linesViewportData.startLineNumber, linesViewportData.endLineNumber, linesViewportData.relativeVerticalOffset);
this._linesCollection._set(resCtx.rendLineNumberStart, resCtx.lines);
this._scrollDomNode = resCtx.scrollDomNode;
this._scrollDomNodeIsAbove = resCtx.scrollDomNodeIsAbove;
}
public _createDomNode(): FastDomNode {
let domNode = createFastDomNode(document.createElement('div'));
domNode.setClassName('view-layer');
domNode.setPosition('absolute');
domNode.domNode.setAttribute('role', 'presentation');
domNode.domNode.setAttribute('aria-hidden', 'true');
return domNode;
}
protected abstract _createLine(): T;
}
class ViewLayerRenderer<T extends IVisibleLineData> {
private _createLine: () => T;
private _extraDomNodeHTML: () => string;
constructor(createLine: () => T, extraDomNodeHTML: () => string) {
this._createLine = createLine;
this._extraDomNodeHTML = extraDomNodeHTML;
}
public renderWithManyUpdates(ctx: IRendererContext<T>, startLineNumber: number, stopLineNumber: number, deltaTop:number[]): IRendererContext<T> {
return this._render(ctx, startLineNumber, stopLineNumber, deltaTop);
}
private _render(inContext: IRendererContext<T>, startLineNumber: number, stopLineNumber: number, deltaTop:number[]): IRendererContext<T> {
var ctx: IRendererContext<T> = {
domNode: inContext.domNode,
rendLineNumberStart: inContext.rendLineNumberStart,
lines: inContext.lines.slice(0),
linesLength: inContext.linesLength,
getInlineDecorationsForLineInViewport: inContext.getInlineDecorationsForLineInViewport,
viewportTop: inContext.viewportTop,
viewportHeight: inContext.viewportHeight,
scrollDomNode: inContext.scrollDomNode,
scrollDomNodeIsAbove: inContext.scrollDomNodeIsAbove
};
var canRemoveScrollDomNode = true;
if (ctx.scrollDomNode) {
var time = this._getScrollDomNodeTime(ctx.scrollDomNode);
if ((new Date()).getTime() - time < 1000) {
canRemoveScrollDomNode = false;
}
}
if (canRemoveScrollDomNode && ((ctx.rendLineNumberStart + ctx.linesLength - 1 < startLineNumber) || (stopLineNumber < ctx.rendLineNumberStart))) {
// There is no overlap whatsoever
ctx.rendLineNumberStart = startLineNumber;
ctx.linesLength = stopLineNumber - startLineNumber + 1;
ctx.lines = [];
for (var x = startLineNumber; x <= stopLineNumber; x++) {
ctx.lines[x - startLineNumber] = this._createLine();
}
this._finishRendering(ctx, true, deltaTop);
ctx.scrollDomNode = null;
return ctx;
}
// Update lines which will remain untouched
this._renderUntouchedLines(
ctx,
Math.max(startLineNumber - ctx.rendLineNumberStart, 0),
Math.min(stopLineNumber - ctx.rendLineNumberStart, ctx.linesLength - 1),
deltaTop,
startLineNumber
);
var fromLineNumber: number,
toLineNumber: number,
removeCnt: number;
if (ctx.rendLineNumberStart > startLineNumber) {
// Insert lines before
fromLineNumber = startLineNumber;
toLineNumber = Math.min(stopLineNumber, ctx.rendLineNumberStart - 1);
if (fromLineNumber <= toLineNumber) {
this._insertLinesBefore(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
ctx.linesLength += toLineNumber - fromLineNumber + 1;
// Clean garbage above
if (ctx.scrollDomNode && ctx.scrollDomNodeIsAbove) {
if (ctx.scrollDomNode.parentNode) {
ctx.scrollDomNode.parentNode.removeChild(ctx.scrollDomNode);
}
ctx.scrollDomNode = null;
}
}
} else if (ctx.rendLineNumberStart < startLineNumber) {
// Remove lines before
removeCnt = Math.min(ctx.linesLength, startLineNumber - ctx.rendLineNumberStart);
if (removeCnt > 0) {
this._removeLinesBefore(ctx, removeCnt);
ctx.linesLength -= removeCnt;
}
}
ctx.rendLineNumberStart = startLineNumber;
if (ctx.rendLineNumberStart + ctx.linesLength - 1 < stopLineNumber) {
// Insert lines after
fromLineNumber = ctx.rendLineNumberStart + ctx.linesLength;
toLineNumber = stopLineNumber;
if (fromLineNumber <= toLineNumber) {
this._insertLinesAfter(ctx, fromLineNumber, toLineNumber, deltaTop, startLineNumber);
ctx.linesLength += toLineNumber - fromLineNumber + 1;
// Clean garbage below
if (ctx.scrollDomNode && !ctx.scrollDomNodeIsAbove) {
if (ctx.scrollDomNode.parentNode) {
ctx.scrollDomNode.parentNode.removeChild(ctx.scrollDomNode);
}
ctx.scrollDomNode = null;
}
}
} else if (ctx.rendLineNumberStart + ctx.linesLength - 1 > stopLineNumber) {
// Remove lines after
fromLineNumber = Math.max(0, stopLineNumber - ctx.rendLineNumberStart + 1);
toLineNumber = ctx.linesLength - 1;
removeCnt = toLineNumber - fromLineNumber + 1;
if (removeCnt > 0) {
this._removeLinesAfter(ctx, removeCnt);
ctx.linesLength -= removeCnt;
}
}
this._finishRendering(ctx, false, deltaTop);
return ctx;
}
private _renderUntouchedLines(ctx: IRendererContext<T>, startIndex: number, endIndex: number, deltaTop:number[], deltaLN:number): void {
var i: number,
lineNumber: number;
for (i = startIndex; i <= endIndex; i++) {
lineNumber = ctx.rendLineNumberStart + i;
var lineDomNode = ctx.lines[i].getDomNode();
if (lineDomNode) {
ctx.lines[i].layoutLine(lineNumber, deltaTop[lineNumber - deltaLN]);
}
}
}
private _insertLinesBefore(ctx: IRendererContext<T>, fromLineNumber: number, toLineNumber: number, deltaTop:number[], deltaLN:number): void {
var newLines:T[] = [],
line:T,
lineNumber: number;
for (lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
line = this._createLine();
newLines.push(line);
}
ctx.lines = newLines.concat(ctx.lines);
}
private _getScrollDomNodeTime(domNode: HTMLElement): number {
var lastScrollTime = domNode.getAttribute('last-scroll-time');
if (lastScrollTime) {
return parseInt(lastScrollTime, 10);
}
return 0;
}
private _removeIfNotScrollDomNode(ctx: IRendererContext<T>, domNode: HTMLElement, isAbove: boolean) {
var time = this._getScrollDomNodeTime(domNode);
if (!time) {
ctx.domNode.removeChild(domNode);
return;
}
if (ctx.scrollDomNode) {
var otherTime = this._getScrollDomNodeTime(ctx.scrollDomNode);
if (otherTime > time) {
// The other is the real scroll dom node
ctx.domNode.removeChild(domNode);
return;
}
if (ctx.scrollDomNode.parentNode) {
ctx.scrollDomNode.parentNode.removeChild(ctx.scrollDomNode);
}
ctx.scrollDomNode = null;
}
ctx.scrollDomNode = domNode;
ctx.scrollDomNodeIsAbove = isAbove;
}
private _removeLinesBefore(ctx: IRendererContext<T>, removeCount: number): void {
var i: number;
for (i = 0; i < removeCount; i++) {
var lineDomNode = ctx.lines[i].getDomNode();
if (lineDomNode) {
this._removeIfNotScrollDomNode(ctx, lineDomNode, true);
}
}
ctx.lines.splice(0, removeCount);
}
private _insertLinesAfter(ctx: IRendererContext<T>, fromLineNumber: number, toLineNumber: number, deltaTop:number[], deltaLN:number): void {
var newLines:T[] = [],
line:T,
lineNumber: number;
for (lineNumber = fromLineNumber; lineNumber <= toLineNumber; lineNumber++) {
line = this._createLine();
newLines.push(line);
}
ctx.lines = ctx.lines.concat(newLines);
}
private _removeLinesAfter(ctx: IRendererContext<T>, removeCount: number): void {
var i: number,
removeIndex = ctx.linesLength - removeCount;
for (i = 0; i < removeCount; i++) {
var lineDomNode = ctx.lines[removeIndex + i].getDomNode();
if (lineDomNode) {
this._removeIfNotScrollDomNode(ctx, lineDomNode, false);
}
}
ctx.lines.splice(removeIndex, removeCount);
}
private static _resolveInlineDecorations<T extends IVisibleLineData>(ctx: IRendererContext<T>): InlineDecoration[][] {
let result: InlineDecoration[][] = [];
for (let i = 0, len = ctx.linesLength; i < len; i++) {
let lineNumber = i + ctx.rendLineNumberStart;
result[i] = ctx.getInlineDecorationsForLineInViewport(lineNumber);
}
return result;
}
private _finishRenderingNewLines(ctx: IRendererContext<T>, domNodeIsEmpty:boolean, newLinesHTML: string[], wasNew: boolean[]): void {
var lastChild = <HTMLElement>ctx.domNode.lastChild;
if (domNodeIsEmpty || !lastChild) {
ctx.domNode.innerHTML = this._extraDomNodeHTML() + newLinesHTML.join('');
} else {
lastChild.insertAdjacentHTML('afterend', newLinesHTML.join(''));
}
var currChild = <HTMLElement>ctx.domNode.lastChild;
for (let i = ctx.linesLength - 1; i >= 0; i--) {
let line = ctx.lines[i];
if (wasNew[i]) {
line.setDomNode(currChild);
currChild = <HTMLElement>currChild.previousSibling;
}
}
}
private _finishRenderingInvalidLines(ctx: IRendererContext<T>, invalidLinesHTML: string[], wasInvalid: boolean[]): void {
var hugeDomNode = document.createElement('div');
hugeDomNode.innerHTML = invalidLinesHTML.join('');
var lineDomNode:HTMLElement,
source:HTMLElement;
for (let i = 0; i < ctx.linesLength; i++) {
let line = ctx.lines[i];
if (wasInvalid[i]) {
source = <HTMLElement>hugeDomNode.firstChild;
lineDomNode = line.getDomNode();
lineDomNode.parentNode.replaceChild(source, lineDomNode);
line.setDomNode(source);
}
}
}
private _finishRendering(ctx: IRendererContext<T>, domNodeIsEmpty:boolean, deltaTop:number[]): void {
let inlineDecorations = ViewLayerRenderer._resolveInlineDecorations(ctx);
var i: number,
len: number,
line: IVisibleLineData,
lineNumber: number,
hadNewLine = false,
wasNew: boolean[] = [],
newLinesHTML: string[] = [],
hadInvalidLine = false,
wasInvalid: boolean[] = [],
invalidLinesHTML: string[] = [];
for (i = 0, len = ctx.linesLength; i < len; i++) {
line = ctx.lines[i];
lineNumber = i + ctx.rendLineNumberStart;
if (line.shouldUpdateHTML(ctx.rendLineNumberStart, lineNumber, inlineDecorations[i])) {
var lineDomNode = line.getDomNode();
if (!lineDomNode) {
// Line is new
line.getLineOuterHTML(newLinesHTML, lineNumber, deltaTop[i]);
wasNew[i] = true;
hadNewLine = true;
} else {
// Line is invalid
line.getLineOuterHTML(invalidLinesHTML, lineNumber, deltaTop[i]);
wasInvalid[i] = true;
hadInvalidLine = true;
// lineDomNode.innerHTML = line.getLineInnerHTML(lineNumber);
}
}
}
if (hadNewLine) {
this._finishRenderingNewLines(ctx, domNodeIsEmpty, newLinesHTML, wasNew);
}
if (hadInvalidLine) {
this._finishRenderingInvalidLines(ctx, invalidLinesHTML, wasInvalid);
}
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/virtualMachinesMappers";
import * as Parameters from "../models/parameters";
import { VMwareCloudSimpleClientContext } from "../vMwareCloudSimpleClientContext";
/** Class representing a VirtualMachines. */
export class VirtualMachines {
private readonly client: VMwareCloudSimpleClientContext;
/**
* Create a VirtualMachines.
* @param {VMwareCloudSimpleClientContext} client Reference to the service client.
*/
constructor(client: VMwareCloudSimpleClientContext) {
this.client = client;
}
/**
* Returns list virtual machine within subscription
* @summary Implements list virtual machine within subscription method
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachinesListBySubscriptionResponse>
*/
listBySubscription(options?: Models.VirtualMachinesListBySubscriptionOptionalParams): Promise<Models.VirtualMachinesListBySubscriptionResponse>;
/**
* @param callback The callback
*/
listBySubscription(callback: msRest.ServiceCallback<Models.VirtualMachineListResponse>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
listBySubscription(options: Models.VirtualMachinesListBySubscriptionOptionalParams, callback: msRest.ServiceCallback<Models.VirtualMachineListResponse>): void;
listBySubscription(options?: Models.VirtualMachinesListBySubscriptionOptionalParams | msRest.ServiceCallback<Models.VirtualMachineListResponse>, callback?: msRest.ServiceCallback<Models.VirtualMachineListResponse>): Promise<Models.VirtualMachinesListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{
options
},
listBySubscriptionOperationSpec,
callback) as Promise<Models.VirtualMachinesListBySubscriptionResponse>;
}
/**
* Returns list of virtual machine within resource group
* @summary Implements list virtual machine within RG method
* @param resourceGroupName The name of the resource group
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachinesListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: Models.VirtualMachinesListByResourceGroupOptionalParams): Promise<Models.VirtualMachinesListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.VirtualMachineListResponse>): void;
/**
* @param resourceGroupName The name of the resource group
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: Models.VirtualMachinesListByResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.VirtualMachineListResponse>): void;
listByResourceGroup(resourceGroupName: string, options?: Models.VirtualMachinesListByResourceGroupOptionalParams | msRest.ServiceCallback<Models.VirtualMachineListResponse>, callback?: msRest.ServiceCallback<Models.VirtualMachineListResponse>): Promise<Models.VirtualMachinesListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.VirtualMachinesListByResourceGroupResponse>;
}
/**
* Get virtual machine
* @summary Implements virtual machine GET method
* @param resourceGroupName The name of the resource group
* @param virtualMachineName virtual machine name
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachinesGetResponse>
*/
get(resourceGroupName: string, virtualMachineName: string, options?: msRest.RequestOptionsBase): Promise<Models.VirtualMachinesGetResponse>;
/**
* @param resourceGroupName The name of the resource group
* @param virtualMachineName virtual machine name
* @param callback The callback
*/
get(resourceGroupName: string, virtualMachineName: string, callback: msRest.ServiceCallback<Models.VirtualMachine>): void;
/**
* @param resourceGroupName The name of the resource group
* @param virtualMachineName virtual machine name
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, virtualMachineName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VirtualMachine>): void;
get(resourceGroupName: string, virtualMachineName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VirtualMachine>, callback?: msRest.ServiceCallback<Models.VirtualMachine>): Promise<Models.VirtualMachinesGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
virtualMachineName,
options
},
getOperationSpec,
callback) as Promise<Models.VirtualMachinesGetResponse>;
}
/**
* Create Or Update Virtual Machine
* @summary Implements virtual machine PUT method
* @param resourceGroupName The name of the resource group
* @param virtualMachineName virtual machine name
* @param virtualMachineRequest Create or Update Virtual Machine request
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachinesCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, virtualMachineName: string, virtualMachineRequest: Models.VirtualMachine, options?: msRest.RequestOptionsBase): Promise<Models.VirtualMachinesCreateOrUpdateResponse> {
return this.beginCreateOrUpdate(resourceGroupName,virtualMachineName,virtualMachineRequest,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.VirtualMachinesCreateOrUpdateResponse>;
}
/**
* Delete virtual machine
* @summary Implements virtual machine DELETE method
* @param resourceGroupName The name of the resource group
* @param virtualMachineName virtual machine name
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachinesDeleteResponse>
*/
deleteMethod(resourceGroupName: string, virtualMachineName: string, options?: msRest.RequestOptionsBase): Promise<Models.VirtualMachinesDeleteResponse> {
return this.beginDeleteMethod(resourceGroupName,virtualMachineName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.VirtualMachinesDeleteResponse>;
}
/**
* Patch virtual machine properties
* @summary Implements virtual machine PATCH method
* @param resourceGroupName The name of the resource group
* @param virtualMachineName virtual machine name
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachinesUpdateResponse>
*/
update(resourceGroupName: string, virtualMachineName: string, options?: Models.VirtualMachinesUpdateOptionalParams): Promise<Models.VirtualMachinesUpdateResponse> {
return this.beginUpdate(resourceGroupName,virtualMachineName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.VirtualMachinesUpdateResponse>;
}
/**
* Power on virtual machine
* @summary Implements a start method for a virtual machine
* @param resourceGroupName The name of the resource group
* @param virtualMachineName virtual machine name
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachinesStartResponse>
*/
start(resourceGroupName: string, virtualMachineName: string, options?: msRest.RequestOptionsBase): Promise<Models.VirtualMachinesStartResponse> {
return this.beginStart(resourceGroupName,virtualMachineName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.VirtualMachinesStartResponse>;
}
/**
* Power off virtual machine, options: shutdown, poweroff, and suspend
* @summary Implements shutdown, poweroff, and suspend method for a virtual machine
* @param resourceGroupName The name of the resource group
* @param virtualMachineName virtual machine name
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachinesStopResponse>
*/
stop(resourceGroupName: string, virtualMachineName: string, options?: Models.VirtualMachinesStopOptionalParams): Promise<Models.VirtualMachinesStopResponse> {
return this.beginStop(resourceGroupName,virtualMachineName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.VirtualMachinesStopResponse>;
}
/**
* Create Or Update Virtual Machine
* @summary Implements virtual machine PUT method
* @param resourceGroupName The name of the resource group
* @param virtualMachineName virtual machine name
* @param virtualMachineRequest Create or Update Virtual Machine request
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreateOrUpdate(resourceGroupName: string, virtualMachineName: string, virtualMachineRequest: Models.VirtualMachine, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
virtualMachineName,
virtualMachineRequest,
options
},
beginCreateOrUpdateOperationSpec,
options);
}
/**
* Delete virtual machine
* @summary Implements virtual machine DELETE method
* @param resourceGroupName The name of the resource group
* @param virtualMachineName virtual machine name
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(resourceGroupName: string, virtualMachineName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
virtualMachineName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* Patch virtual machine properties
* @summary Implements virtual machine PATCH method
* @param resourceGroupName The name of the resource group
* @param virtualMachineName virtual machine name
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginUpdate(resourceGroupName: string, virtualMachineName: string, options?: Models.VirtualMachinesBeginUpdateOptionalParams): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
virtualMachineName,
options
},
beginUpdateOperationSpec,
options);
}
/**
* Power on virtual machine
* @summary Implements a start method for a virtual machine
* @param resourceGroupName The name of the resource group
* @param virtualMachineName virtual machine name
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginStart(resourceGroupName: string, virtualMachineName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
virtualMachineName,
options
},
beginStartOperationSpec,
options);
}
/**
* Power off virtual machine, options: shutdown, poweroff, and suspend
* @summary Implements shutdown, poweroff, and suspend method for a virtual machine
* @param resourceGroupName The name of the resource group
* @param virtualMachineName virtual machine name
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginStop(resourceGroupName: string, virtualMachineName: string, options?: Models.VirtualMachinesBeginStopOptionalParams): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
virtualMachineName,
options
},
beginStopOperationSpec,
options);
}
/**
* Returns list virtual machine within subscription
* @summary Implements list virtual machine within subscription method
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachinesListBySubscriptionNextResponse>
*/
listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.VirtualMachinesListBySubscriptionNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.VirtualMachineListResponse>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VirtualMachineListResponse>): void;
listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VirtualMachineListResponse>, callback?: msRest.ServiceCallback<Models.VirtualMachineListResponse>): Promise<Models.VirtualMachinesListBySubscriptionNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listBySubscriptionNextOperationSpec,
callback) as Promise<Models.VirtualMachinesListBySubscriptionNextResponse>;
}
/**
* Returns list of virtual machine within resource group
* @summary Implements list virtual machine within RG method
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachinesListByResourceGroupNextResponse>
*/
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.VirtualMachinesListByResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.VirtualMachineListResponse>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VirtualMachineListResponse>): void;
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VirtualMachineListResponse>, callback?: msRest.ServiceCallback<Models.VirtualMachineListResponse>): Promise<Models.VirtualMachinesListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByResourceGroupNextOperationSpec,
callback) as Promise<Models.VirtualMachinesListByResourceGroupNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listBySubscriptionOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.VMwareCloudSimple/virtualMachines",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion,
Parameters.filter,
Parameters.top,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.VirtualMachineListResponse
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/virtualMachines",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion,
Parameters.filter,
Parameters.top,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.VirtualMachineListResponse
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/virtualMachines/{virtualMachineName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.virtualMachineName0
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.VirtualMachine
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/virtualMachines/{virtualMachineName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.virtualMachineName1
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.referer,
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "virtualMachineRequest",
mapper: {
...Mappers.VirtualMachine,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.VirtualMachine,
headersMapper: Mappers.VirtualMachinesCreateOrUpdateHeaders
},
201: {
bodyMapper: Mappers.VirtualMachine,
headersMapper: Mappers.VirtualMachinesCreateOrUpdateHeaders
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/virtualMachines/{virtualMachineName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.virtualMachineName0
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.referer,
Parameters.acceptLanguage
],
responses: {
202: {
headersMapper: Mappers.VirtualMachinesDeleteHeaders
},
204: {
headersMapper: Mappers.VirtualMachinesDeleteHeaders
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const beginUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/virtualMachines/{virtualMachineName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.virtualMachineName0
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: {
tags: [
"options",
"tags"
]
},
mapper: {
...Mappers.PatchPayload,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.VirtualMachine
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const beginStartOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/virtualMachines/{virtualMachineName}/start",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.virtualMachineName0
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.referer,
Parameters.acceptLanguage
],
responses: {
200: {
headersMapper: Mappers.VirtualMachinesStartHeaders
},
202: {
headersMapper: Mappers.VirtualMachinesStartHeaders
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const beginStopOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/virtualMachines/{virtualMachineName}/stop",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.virtualMachineName0
],
queryParameters: [
Parameters.mode,
Parameters.apiVersion
],
headerParameters: [
Parameters.referer,
Parameters.acceptLanguage
],
requestBody: {
parameterPath: {
mode: [
"options",
"mode1"
]
},
mapper: Mappers.VirtualMachineStopMode
},
responses: {
200: {
headersMapper: Mappers.VirtualMachinesStopHeaders
},
202: {
headersMapper: Mappers.VirtualMachinesStopHeaders
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const listBySubscriptionNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.VirtualMachineListResponse
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const listByResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.VirtualMachineListResponse
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
}; | the_stack |
import { pool_mgr } from "../pool/pool_mgr"
import { gen_handler } from "../util"
import { POP_UI_BASE } from "./pop_ui_base"
import { TweenUtil } from "../tween/tweenutil"
import { TweenFunc } from "../tween/tweenfunc"
import { event_mgr, Event_Name } from "../event/event_mgr";
import { LoadingQueue } from "../loader/loading_queue";
const panel_overlay_bg = "panel_overlay_bg";
const isDualInstanceView = (path:string) => {
const config:UI_CONFIG = UI_CONFIG_MAP[path];
return config && config.dualInstance;
}
const isModalView = (path:string) => {
const config:UI_CONFIG = UI_CONFIG_MAP[path];
return !config || config.needOverlayBg != false;
}
const isFullScreenView = (path:string) => {
const config:UI_CONFIG = UI_CONFIG_MAP[path];
return config && config.fullScreen;
}
const isDestroyAtOnce = (path:string) => {
const config:UI_CONFIG = UI_CONFIG_MAP[path];
return config && config.destroyAtOnce;
}
const getOverlayBgOpacity = (path:string) => {
const config:UI_CONFIG = UI_CONFIG_MAP[path];
if(!config || config.overlayBgOpacity == null) {
return 175;
}
return config.overlayBgOpacity;
}
export class pop_mgr
{
private static inst:pop_mgr;
private view_map:Map<string, PopView[]>;
private view_stack:PopView[];
private overlayNode:cc.Node;
private constructor()
{
this.view_map = new Map();
this.view_stack = [];
event_mgr.get_inst().add(Event_Name.UI_SHOW, this.onViewShow, this);
event_mgr.get_inst().add(Event_Name.UI_HIDE, this.onViewHide, this);
}
static get_inst():pop_mgr
{
if(!this.inst) {
this.inst = new pop_mgr();
}
return this.inst;
}
show(path:string, transition?:UI_TRANSITION, ...params)
{
let views = this.view_map.get(path);
if(!isDualInstanceView(path) && views && views.length > 0) {
return views[0];
}
if(!views) {
views = [];
this.view_map.set(path, views);
}
const view = new PopView(path);
const scene = cc.director.getScene();
if(cc.isValid(scene)) {
const viewRoot = scene.getChildByName("Canvas");
if(cc.isValid(viewRoot)) {
view.setParent(viewRoot);
view.setTransition(transition);
view.setModal(isModalView(path));
view.show(UI_CONFIG_MAP[path], ...params);
views.push(view);
}
}
return view;
}
/** deprecated */
hide_bypath(path:string)
{
const views = this.view_map.get(path);
if(!views || views.length <= 0 || isDualInstanceView(path)) {
return;
}
const view = views.pop();
view.hide();
}
has_views()
{
let ret = false;
this.view_map.forEach(views => {
if(views.length > 0) {
ret = true;
}
});
if(!ret) {
ret = this.view_stack.length > 0;
}
return ret;
}
top_view()
{
if(this.view_stack.length > 0) {
return this.view_stack[this.view_stack.length - 1];
}
return null;
}
clear()
{
this.view_map.forEach(views => {
views.forEach(view => view.hide());
});
this.view_map.clear();
this.view_stack.length = 0;
if(cc.isValid(this.overlayNode)) {
this.overlayNode.destroy();
this.overlayNode = null;
}
cc.log(`PopMgr clear`);
}
private onViewShow(view:PopView)
{
cc.log(`PopMgr, onViewShow, view path=${view.getPath()}`);
this._pushViewToStack(view);
this._updateOverlay();
}
private onViewHide(view:PopView)
{
cc.log(`PopMgr, onViewHide, view path=${view.getPath()}`);
this._removeViewFromMap(view);
this._popViewFromStack(view);
this._updateOverlay();
}
private _removeViewFromMap(view:PopView)
{
const path = view.getPath();
const views = this.view_map.get(path);
if(views) {
const idx = views.indexOf(view);
if(idx != -1) {
views.splice(idx, 1);
}
}
}
private _pushViewToStack(view:PopView)
{
if(this.view_stack.indexOf(view) == -1) {
this.view_stack.push(view);
}
}
private _popViewFromStack(view:PopView)
{
const idx = this.view_stack.indexOf(view);
if(idx != -1) {
this.view_stack.splice(idx, 1);
}
}
private _updateOverlay()
{
//找到最上层模态view
const topModalView = this.getToppestModalView();
if(!topModalView) {
this._removeOverlay();
return;
}
this._addOverlay(topModalView);
}
private _removeOverlay()
{
const overlayNode = this.overlayNode;
if(cc.isValid(overlayNode) && overlayNode.parent) {
overlayNode.removeFromParent(true);
overlayNode.destroy();
this.overlayNode = null;
cc.log(`PopMgr, removeOverlay`);
}
}
private _addOverlay(view:PopView)
{
cc.log(`PopMgr, _addOverlay, view=${view.getPath()}`);
const viewRoot = view.getParent();
if(!cc.isValid(viewRoot)) {
cc.log(`PopMgr, _addOverlay, invalid viewRoot 1`);
return;
}
const overlayNode = viewRoot.getChildByName(panel_overlay_bg);
if(overlayNode) {
this.overlayNode = overlayNode;
this._addOverlayUnderView(overlayNode, view);
// this._debugOverlay(viewRoot, overlayNode);
return;
}
LoadingQueue.getInst().loadPrefabObj(UI_NAME.overlay_bg, gen_handler((overlayNode:cc.Node) => {
if(!cc.isValid(viewRoot)) {
cc.log(`PopMgr, _addOverlay, invalid viewRoot 2`);
return;
}
if(view != this.getToppestModalView()) {
// cc.log(`PopMgr, _addOverlay, ${view.getPath()} isn't toppest modal view`);
return;
}
this.overlayNode = overlayNode;
overlayNode.parent = viewRoot;
overlayNode.name = panel_overlay_bg;
this._addOverlayUnderView(overlayNode, view);
// this._debugOverlay(viewRoot, overlayNode);
}));
}
private _addOverlayUnderView(overlayNode:cc.Node, view:PopView)
{
cc.log(`PopMgr, _addOverlayUnderView, view=${view.getPath()}`);
overlayNode.opacity = getOverlayBgOpacity(view.getPath());
const viewZOrder = view.getNode().getSiblingIndex();
if(overlayNode.getSiblingIndex() < viewZOrder) {
overlayNode.setSiblingIndex(viewZOrder - 1);
}
else {
overlayNode.setSiblingIndex(viewZOrder);
}
}
private getToppestModalView()
{
const len = this.view_stack.length;
if(len <= 0) {
return null;
}
let modalView:PopView;
for(let i = len - 1; i >= 0; i--) {
const view = this.view_stack[i];
const path = view.getPath();
if(isModalView(path) && !isFullScreenView(path)) {
modalView = view;
break;
}
}
return modalView;
}
private _debugOverlay(viewRoot:cc.Node, overlayNode:cc.Node)
{
cc.log("---------debug viewtree start-----------");
viewRoot.children.forEach(c => cc.log(c.name + "\n"));
cc.log(`overlay opcaity=${overlayNode.opacity}`);
cc.log("---------debug viewtree end-----------");
}
}
export class PopView
{
private _path:string;
private _node:cc.Node;
private _parent:cc.Node;
private _posX:number;
private _posY:number;
private _transition:UI_TRANSITION;
private _config:UI_CONFIG;
private _params:any[];
private _isActive:boolean;
private _isModal:boolean;
private _isHide:boolean;
constructor(path:string)
{
this._path = path;
pool_mgr.get_inst().get_ui(path, gen_handler((node:cc.Node)=>{
if(this._isHide) {
pool_mgr.get_inst().put_ui(path, node);
return;
}
this._node = node;
if(cc.isValid(this._parent)) {
this._setParent(this._parent, this._posX, this._posY);
}
if(this._transition != null) {
this._setTransition(this._transition);
}
if(this._params != null) {
this._show(this._config, ...this._params);
}
if(this._isActive != null) {
this._setActive(this._isActive);
}
if(this._isModal != null) {
this._setModal(this._isModal);
}
}, this));
}
show(config:UI_CONFIG, ...params)
{
this._config = config;
this._params = params;
if(this.isValid()) {
this._show(config, ...params);
}
}
private _show(config:UI_CONFIG, ...params)
{
const path = this._path;
cc.log(`PopView show, path=${path}`);
event_mgr.get_inst().fire(Event_Name.UI_SHOW, this);
const uiBase = this._node.getComponent(POP_UI_BASE);
uiBase.setView(this);
uiBase.__show__(...params);
}
hide()
{
const path = this._path;
if(this._isHide) {
cc.log(`PopView hide, path=${path}, view is already hided`);
return;
}
this._isHide = true;
if(cc.isValid(this._node)) {
const uiBase = this._node.getComponent(POP_UI_BASE);
uiBase.__hide__();
uiBase.setView(null);
pool_mgr.get_inst().put_ui(path, this._node, isDestroyAtOnce(path));
cc.log(`PopView hide, path=${path}`);
event_mgr.get_inst().fire(Event_Name.UI_HIDE, this);
}
}
setParent(parent:cc.Node, x = 0, y = 0)
{
this._parent = parent;
this._posX = x;
this._posY = y;
if(this.isValid()) {
this._setParent(parent, x, y);
}
}
private _setParent(parent:cc.Node, x = 0, y = 0)
{
this._node.setParent(parent);
this._node.setPosition(x, y);
}
setActive(active:boolean)
{
this._isActive = active;
if(this.isValid()) {
this._setActive(active);
}
}
private _setActive(active:boolean)
{
this._node.active = active;
}
setModal(isModal:boolean)
{
if(this._isModal == isModal) {
return;
}
this._isModal = isModal;
if(this.isValid()) {
this._setModal(isModal);
}
}
private _setModal(isModal:boolean)
{
const hasComp = this._node.getComponent(cc.BlockInputEvents);
if(isModal && !hasComp) {
this._node.addComponent(cc.BlockInputEvents);
}
else if(!isModal && hasComp) {
this._node.removeComponent(cc.BlockInputEvents);
}
}
setTransition(transition:UI_TRANSITION)
{
this._transition = transition;
if(this.isValid()) {
this._setTransition(transition);
}
}
private _setTransition(transition:UI_TRANSITION)
{
transition = transition || {transType:UI_TRANSITION_TYPE.None};
switch(transition.transType)
{
case UI_TRANSITION_TYPE.FadeIn:
TweenUtil.from({target:this._node, duration:transition.duration || 1, opacity:0, tweenFunc:transition.tweenFunc || TweenFunc.Linear});
break;
}
}
private isValid()
{
return cc.isValid(this._node) && !this._isHide;
}
getPath()
{
return this._path;
}
getParent()
{
return this._parent;
}
getNode()
{
return this._node;
}
}
//界面prefab路径配置, 相对于assets/resources目录
export const UI_NAME = {
overlay_bg:"prefabs/panels/panel_overlay_bg",
settlement:"prefabs/panels/panel_settlement",
setting:"prefabs/panels/panel_setting",
msgBox:"prefabs/panels/panel_msgBox",
}
const UI_CONFIG_MAP = {
[UI_NAME.msgBox]: {dualInstance:true},
[UI_NAME.settlement]: {fullScreen:true, destroyAtOnce:true},
}
export interface UI_CONFIG
{
needOverlayBg?:boolean;
overlayBgOpacity?:number;
dualInstance?:boolean;
fullScreen?:boolean;
destroyAtOnce?:boolean;
}
interface UI_TRANSITION
{
transType:UI_TRANSITION_TYPE;
tweenFunc?:Function;
duration?:number;
}
export const enum UI_TRANSITION_TYPE
{
None = 1,
FadeIn,
DropDown,
PopUp,
LeftIn,
RightIn,
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.